public string DeclinePhrase(string words, string caseName = "Nominative")
        {
            var phrase     = new CyrPhrase(nouns, adjs);
            var declineRes = phrase.Decline(words, GetConditionsEnum.Similar);

            return(GetDeclensionInCase(declineRes, caseName));
        }
Exemple #2
0
        static void PhraseSamples()
        {
            {
                string phrase = "пушистый кот";
                Console.WriteLine("Склоняю словосочетание с поиском слов по точному совпадению.");
                CyrResult result = cyrPhrase.Decline(phrase, GetConditionsEnum.Strict);
                WriteToConsole(phrase, result);
            }

            {
                string phrase = "кушистый мот";
                Console.WriteLine("Склоняю словосочетание с поиском слов по неточному совпадению.");
                CyrResult result = cyrPhrase.Decline(phrase, GetConditionsEnum.Similar);
                WriteToConsole(phrase, result);
            }
        }
Exemple #3
0
        public ActionResult Phrase(string w)
        {
            ViewBag.Page = "Decline.Phrase";

            if (string.IsNullOrEmpty(w))
            {
                return(View());
            }

            List <string> errors   = new List <string>();
            CyrPhrase     phrase   = new CyrPhrase(this.NounCollection, this.AdjectiveCollection);
            CyrResult     singular = null;
            CyrResult     plural   = null;

            try
            {
                singular = phrase.Decline(w, GetConditionsEnum.Similar);
                plural   = phrase.DeclinePlural(w, GetConditionsEnum.Similar);
            }
            catch (CyrWordNotFoundException ex)
            {
                errors.Add(string.Format("Слово \"<strong>{0}</strong>\" не найдено в коллекции. Попбробуйте убрать слово из фразы.", ex.Word));
                return(View());
            }

            ViewBag.Text     = w;
            ViewBag.Errors   = errors;
            ViewBag.Singular = singular;
            ViewBag.Plural   = plural;
            ViewBag.Cases    = CyrDeclineCase.GetEnumerable().ToArray();

            return(View());
        }
Exemple #4
0
        private void btnDecline_Click(object sender, EventArgs e)
        {
            if (txtWord.Text.IsNullOrEmpty())
            {
                MessageBox.Show("Необходимо ввести слово или фразу!");
            }

            CyrPhrase phrase = new CyrPhrase(nounCollection, adjCollection);
            CyrResult result;

            try
            {
                if (ddlAction.SelectedIndex == 0)
                {
                    result = phrase.Decline(txtWord.Text, GetConditionsEnum.Similar);
                }
                else
                {
                    result = phrase.DeclinePlural(txtWord.Text, GetConditionsEnum.Similar);
                }
            }
            catch (CyrWordNotFoundException ex)
            {
                MessageBox.Show(string.Format("Слово {0} не найдено в коллекции!", ex.Word));
                return;
            }

            this.SetResult(result);
        }
Exemple #5
0
        private void btnDecline_Click(object sender, EventArgs e)
        {
            if (txtWord.Text.IsNullOrEmpty())
            {
                MessageBox.Show("Необходимо ввести слово или фразу!");
            }

            CyrPhrase phrase = new CyrPhrase(nounCollection, adjCollection);
            CyrResult result;

            try
            {
                if (ddlAction.SelectedIndex == 0)
                {
                    result = phrase.Decline(txtWord.Text, GetConditionsEnum.Similar);
                }
                else
                {
                    result = phrase.DeclinePlural(txtWord.Text, GetConditionsEnum.Similar);
                }
            }
            catch (CyrWordNotFoundException ex)
            {
                MessageBox.Show(string.Format("Слово {0} не найдено в коллекции!", ex.Word));
                return;
            }

            this.SetResult(result);
        }
Exemple #6
0
        public CyrResult DeclinePhrase(string phrase)
        {
            CyrPhrase cyrPhrase = new CyrPhrase(cyrNounCollection, cyrAdjectiveCollection);
            CyrResult result    = cyrPhrase.Decline(phrase, GetConditionsEnum.Similar);

            cyrPhrase = null;
            return(result);
        }
Exemple #7
0
        public static List <string> GetPhraseDeclension(string phrase)
        {
            var singular = _cyrPhraseCollection.Decline(phrase, GetConditionsEnum.Strict).ToArray();
            var plural   = _cyrPhraseCollection.DeclinePlural(phrase, GetConditionsEnum.Strict).ToArray();
            var result   = new List <string>();

            result.AddRange(singular.Where(singularWord => !string.IsNullOrEmpty(singularWord)));
            result.AddRange(plural.Where(singularWord => !string.IsNullOrEmpty(singularWord)));
            return(result.Distinct().ToList());
        }
Exemple #8
0
        public ActionResult List(string w)
        {
            ViewBag.Page = "Decline.List";

            if (w.IsNullOrEmpty())
            {
                return(View());
            }

            string[] items = w.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            if (!items.Any())
            {
                return(View());
            }

            List <CyrResult> singulars = new List <CyrResult>();
            List <CyrResult> plurals   = new List <CyrResult>();
            List <string>    errors    = new List <string>();

            if (items.Length > MaxPhrasesToDecline)
            {
                errors.Add($"За один раз можно склонять максимум {MaxPhrasesToDecline} фраз!");
            }

            for (int i = 0; i < items.Length && i < MaxPhrasesToDecline; i++)
            {
                string    item     = items[i];
                CyrPhrase phrase   = new CyrPhrase(this.NounCollection, this.AdjectiveCollection);
                CyrResult singular = null;
                CyrResult plural   = null;

                try
                {
                    singular = phrase.Decline(item, GetConditionsEnum.Similar);
                    plural   = phrase.DeclinePlural(item, GetConditionsEnum.Similar);
                }
                catch (CyrWordNotFoundException ex)
                {
                    errors.Add(string.Format("Слово \"<strong>{0}</strong>\" не найдено в коллекции. Попбробуйте убрать слово из фразы.", ex.Word));
                    continue;
                }

                singulars.Add(singular);
                plurals.Add(plural);
            }

            ViewBag.Text      = w;
            ViewBag.Errors    = errors;
            ViewBag.Singulars = singulars;
            ViewBag.Plurals   = plurals;
            ViewBag.Cases     = CyrDeclineCase.GetEnumerable().ToArray();

            return(View());
        }
 public static CyrResult DeclineSingular(CyrPhrase decliner, string phrase)
 {
     try
     {
         return(decliner.Decline(phrase, GetConditionsEnum.Strict));
     }
     catch
     {
         return(null);
     }
 }
        public DeclensionResult DeclensionOfPhrase(OriginalData originalData)
        {
            var preparationData = PrepareData(originalData.Input);

            try
            {
                var result = cyrPhrase.Decline(preparationData, GetConditionsEnum.Strict);
                return(new DeclensionResult(result, originalData));
            }
            catch (Exception ex)
            {
                return(new DeclensionResult(ex.Message, originalData));
            }
        }
Exemple #11
0
        protected void DeclineTextFile(HttpPostedFileBase File, bool Plural)
        {
            string name = Guid.NewGuid() + ".txt";
            string path = Path.Combine(TempFolder, name);

            CyrDeclineCase[] cases  = CyrDeclineCase.GetEnumerable().ToArray();
            CyrPhrase        phrase = new CyrPhrase(NounCollection, AdjectiveCollection);

            TextReader reader       = new StreamReader(File.InputStream, true);
            TextWriter writer       = new StreamWriter(path, false, System.Text.Encoding.UTF8);
            string     line         = reader.ReadLine();
            int        totalPhrases = 0;
            int        errorPhrases = 0;

            for (int i = 0; i < cases.Length; i++)
            {
                if (i > 0)
                {
                    writer.Write(" | ");
                }

                writer.Write(cases[i].NameRu);
                writer.Write(" ");
                writer.Write(cases[i].Description);
            }

            while (line.IsNotNullOrEmpty())
            {
                totalPhrases++;

                try
                {
                    CyrResult result;

                    if (Plural)
                    {
                        result = phrase.DeclinePlural(line, GetConditionsEnum.Similar);
                    }
                    else
                    {
                        result = phrase.Decline(line, GetConditionsEnum.Similar);
                    }

                    writer.Write(Environment.NewLine);

                    for (int i = 0; i < cases.Length; i++)
                    {
                        if (i > 0)
                        {
                            writer.Write(" | ");
                        }

                        writer.Write(result[cases[i].Index]);
                    }
                }
                catch (CyrWordNotFoundException ex)
                {
                    writer.Write(Environment.NewLine);
                    writer.Write(string.Format("Слово \"{0}\" не найдено в коллекции. Попбробуйте убрать слово из фразы.", ex.Word));
                    errorPhrases++;
                }

                line = reader.ReadLine();
            }

            reader.Dispose();
            writer.Close();
            writer.Dispose();
            ViewBag.DownloadFileName = name;
            ViewBag.TotalPhrases     = totalPhrases;
            ViewBag.ErrorPhrases     = errorPhrases;
        }
Exemple #12
0
        protected void DeclineExcelFile(HttpPostedFileBase File, bool Plural)
        {
            ExcelPackage package;

            try
            {
                package = new ExcelPackage(File.InputStream);
            }
            catch
            {
                ViewBag.Errors = new string[] { $"Не удается открыть {File.FileName} файл, возможно файл поврежден или не является правильным документом Microsoft Excel." };
                return;
            }

            string name = Guid.NewGuid() + ".xlsx";
            string path = Path.Combine(TempFolder, name);

            CyrDeclineCase[] cases  = CyrDeclineCase.GetEnumerable().ToArray();
            CyrPhrase        phrase = new CyrPhrase(NounCollection, AdjectiveCollection);

            ExcelWorksheet input        = package.Workbook.Worksheets[1];
            ExcelWorksheet output       = package.Workbook.Worksheets.Add("Результат");
            int            rowIndex     = 1;
            string         line         = input.Cells[rowIndex, 1].Value?.ToString();
            int            totalPhrases = 0;
            int            errorPhrases = 0;

            foreach (CyrDeclineCase dc in cases)
            {
                output.Cells[rowIndex, dc.Index].Value = $"{dc.NameRu}, {dc.Description}";
            }

            while (line.IsNotNullOrEmpty())
            {
                rowIndex++;
                totalPhrases++;

                try
                {
                    CyrResult result;

                    if (Plural)
                    {
                        result = phrase.DeclinePlural(line, GetConditionsEnum.Similar);
                    }
                    else
                    {
                        result = phrase.Decline(line, GetConditionsEnum.Similar);
                    }

                    foreach (CyrDeclineCase dc in cases)
                    {
                        output.Cells[rowIndex, dc.Index].Value = result[dc.Index];
                    }
                }
                catch (CyrWordNotFoundException ex)
                {
                    output.Cells[rowIndex, 1].Value = string.Format("Слово \"{0}\" не найдено в коллекции. Попбробуйте убрать слово из фразы.", ex.Word);
                    errorPhrases++;
                }

                line = input.Cells[rowIndex, 1].Value?.ToString();
            }

            output.Cells.AutoFitColumns();
            package.SaveAs(new FileInfo(path));
            package.Dispose();
            ViewBag.DownloadFileName = name;
            ViewBag.TotalPhrases     = totalPhrases;
            ViewBag.ErrorPhrases     = errorPhrases;
        }
        public ActionResult Phrase(string w)
        {
            ViewBag.Page = "Decline.Phrase";

            if (string.IsNullOrEmpty(w))
            {
                return View();
            }

            List<string> errors = new List<string>();
            CyrPhrase phrase = new CyrPhrase(this.NounCollection, this.AdjectiveCollection);
            CyrResult singular = null;
            CyrResult plural = null;

            try
            {
                singular = phrase.Decline(w, GetConditionsEnum.Similar);
                plural = phrase.DeclinePlural(w, GetConditionsEnum.Similar);
            }
            catch (CyrWordNotFoundException ex)
            {
                errors.Add(string.Format("Слово \"<strong>{0}</strong>\" не найдено в коллекции. Попбробуйте убрать слово из фразы.", ex.Word));
                return View();
            }

            ViewBag.Text = w;
            ViewBag.Errors = errors;
            ViewBag.Singular = singular;
            ViewBag.Plural = plural;

            return View();
        }
Exemple #14
0
        public ActionResult CreateContract(Guid callID)
        {
            var callData    = db.Calls.ToList();
            var itemsData   = db.Items.ToList();
            var custData    = db.Customers.ToList();
            var repData     = db.Representatives.ToList();
            var callDetails = db.CallDetails.ToList();
            //var progdata = db.Programs.ToList();

            var callData2 = (from c in db.CallDetails
                             join item in itemsData on c.ItemID equals item.ItemID
                             join calcdet in db.CalcDetails.ToList() on item.CalcDetailsID equals calcdet.CalcID
                             where (c.CallID == callID)
                             select new ContractViewModel.Itm {
                itemname = item.ItemName, Qty = c.ItemQty.ToString(), itemsubtype = item.ItemSubtype.ItemSubtype1, additionals = item.Additional, calcDate = calcdet.CalcDate.ToString(), calcNum = calcdet.CalcNum
            }).ToList();


            ContractViewModel contract = new ContractViewModel();

            CultureInfo ci = new CultureInfo("RU-ru");

            contract = (from cd in callData
                        join cust in custData on cd.CustomerID equals cust.CustomerID
                        join rep in repData on cust.RepresentativeID equals rep.RepresentativeID
                        join calldet in callDetails on cd.CallID equals calldet.CallID
                        join item in itemsData on calldet.ItemID equals item.ItemID

                        where (cd.CallID == (Guid)callID)
                        select new ContractViewModel {
                CallID = cd.CallID,
                callDate = cd.CallDate.ToString("dd MMMM yyyy г.", ci),
                sampleActDate = cd.SampleActDate.ToString("dd MMMM yyyy г.", ci),
                callNumber = cd.DocNumber.ToString(),
                expAffNum = cd.AffidavitNum.ToString(),
                expAffDate = cd.AffidavitDate.ToString("dd MMMM yyyy г.", ci),
                contractDate = cd.ContractDate,
                repdoc = rep.RepDoc.ToString(),
                repFName = rep.FirstName.ToString(),
                repMName = rep.MidName.ToString(),
                repFamName = rep.FamilyName.ToString(),
                repPosition = rep.Position.ToString(),
                repPhone = rep.PhoneNumber.ToString(),
                custName = cust.Name.ToString(),
                custAddress = cust.Address.ToString(),
                custTaxID = cust.TaxID.ToString(),
                custBIC = cust.BIC.ToString(),
                custPhoneNumber = cust.PhoneNumber.ToString(),
                custOKPO = cust.OKPO.ToString(),
                custAccount = cust.Account.ToString(),
                custBankBranch = cust.BankBranch.ToString(),
                custBranchAddress = cust.BranchAddress.ToString(),
                custBankCode = cust.BankCode.ToString(),
                custMPhoneNumber = cust.MPhoneNumber.ToString()
            }

                        ).FirstOrDefault();

            contract.itmList = callData2;

            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            //                              ВВОД ДАННЫХ В ШАБЛОН ДОГОВОРА                                        //

            ///////////////////////////////////////////////////////////////////////////////////////////////////////


            List <string> expertData = callexp.Split(' ').Reverse().ToList();

            string expName = expertData[0] + expertData[1] + expertData[2];

            int nameIndex = callexp.IndexOf(expName);

            string expertPosition = callexp.Remove(nameIndex, expName.Length);

            string firstWordInPosition = callexp.Split(' ').First();

            int firstWordIndex = expertPosition.IndexOf(firstWordInPosition);

            string expPositionTail = expertPosition.Remove(firstWordIndex, firstWordInPosition.Length);

            CyrNounCollection      nouns = new CyrNounCollection();
            CyrAdjectiveCollection adj   = new CyrAdjectiveCollection();
            CyrPhrase phrase             = new CyrPhrase(nouns, adj);
            CyrResult expname            = phrase.Decline(expName, GetConditionsEnum.Strict);

            expName = expname.Genitive;

            CyrNoun   strict        = nouns.Get(firstWordInPosition, GetConditionsEnum.Strict);
            CyrResult expPosition   = strict.Decline();
            string    firstWordDecl = expPosition.Genitive;

            expertPosition = string.Concat(firstWordDecl, expPositionTail);

            firstWordInPosition = contract.repPosition.Split(' ').First();

            firstWordIndex = contract.repPosition.IndexOf(firstWordInPosition);

            string repPositionTail = contract.repPosition.Remove(firstWordIndex, firstWordInPosition.Length);

            CyrResult repname = phrase.Decline((contract.repFamName + contract.repFName + contract.repMName), GetConditionsEnum.Strict);
            string    repName = repname.Genitive;

            strict = nouns.Get(firstWordInPosition, GetConditionsEnum.Strict);
            CyrResult repPosition = strict.Decline();

            firstWordDecl = repPosition.Genitive;
            string representativePosition = string.Concat(firstWordDecl, expPositionTail);


            try
            {
                Document document = new Document();
                document.LoadFromFile("~/Content/FileTemplates/ContractTemplateCorporate.docx");
                BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
                bookmarkNavigator.MoveToBookmark("ContractNum");
                bookmarkNavigator.ReplaceBookmarkContent(contract.callNumber, true);

                bookmarkNavigator.MoveToBookmark("ContractDay");
                if (contract.contractDate.HasValue)
                {
                    bookmarkNavigator.ReplaceBookmarkContent((contract.contractDate?.ToString("dd", new CultureInfo("ru-RU"))), true);

                    bookmarkNavigator.MoveToBookmark("ContractMonth");
                    bookmarkNavigator.ReplaceBookmarkContent(contract.contractDate?.ToString(" MMMM ", new CultureInfo("ru-RU")), true);

                    bookmarkNavigator.MoveToBookmark("ContractYear");
                    bookmarkNavigator.ReplaceBookmarkContent(contract.contractDate?.ToString(" yyyy г.", new CultureInfo("ru-RU")), true);
                }

                else
                {
                    bookmarkNavigator.ReplaceBookmarkContent((DateTime.Today.ToString("dd", new CultureInfo("ru-RU"))), true);

                    bookmarkNavigator.MoveToBookmark("ContractMonth");
                    bookmarkNavigator.ReplaceBookmarkContent(DateTime.Today.ToString(" MMMM ", new CultureInfo("ru-RU")), true);

                    bookmarkNavigator.MoveToBookmark("ContractYear");
                    bookmarkNavigator.ReplaceBookmarkContent(DateTime.Today.ToString(" yyyy г.", new CultureInfo("ru-RU")), true);
                }

                bookmarkNavigator.MoveToBookmark("ContractExpertPosition");
                bookmarkNavigator.ReplaceBookmarkContent(expertPosition, true);

                bookmarkNavigator.MoveToBookmark("ContractExpertFullName");
                bookmarkNavigator.ReplaceBookmarkContent(expName, true);

                bookmarkNavigator.MoveToBookmark("AffidavitNum");
                bookmarkNavigator.ReplaceBookmarkContent(contract.expAffNum, true);

                bookmarkNavigator.MoveToBookmark("AffidavitDate");
                bookmarkNavigator.ReplaceBookmarkContent(contract.expAffDate, true);

                bookmarkNavigator.MoveToBookmark("CustomerName");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custName, true);

                bookmarkNavigator.MoveToBookmark("CustomerDoc");
                bookmarkNavigator.ReplaceBookmarkContent(" ", true);

                bookmarkNavigator.MoveToBookmark("RepresentativePosition");
                bookmarkNavigator.ReplaceBookmarkContent(representativePosition, true);

                bookmarkNavigator.MoveToBookmark("RepresentativeName");
                bookmarkNavigator.ReplaceBookmarkContent(repName, true);

                bookmarkNavigator.MoveToBookmark("CustomerCompanyDoc");
                bookmarkNavigator.ReplaceBookmarkContent(contract.repdoc, true);

                foreach (ContractViewModel.Itm i in contract.itmList)
                {
                    CyrResult it_name = phrase.Decline(i.itemsubtype, GetConditionsEnum.Strict);
                    i.itemsubtype = it_name.Genitive;

                    bookmarkNavigator.MoveToBookmark("ItemName");
                    bookmarkNavigator.ReplaceBookmarkContent(i.itemsubtype + i.itemname, true);

                    string progname = (from prog in db.Programs.ToList()
                                       join t in db.ItemTypes.ToList() on prog.ItemTypeID equals t.ItemTypeID
                                       join st in db.ItemSubtypes.ToList() on t.ItemTypeID equals st.ItemTypeID
                                       join item in db.Items.ToList() on st.ItemSubtypeID equals item.ItemSubtypeID
                                       where item.ItemName == i.itemname
                                       select prog.ProgramNameShort).FirstOrDefault();


                    bookmarkNavigator.MoveToBookmark("ProgramShortName");
                    bookmarkNavigator.ReplaceBookmarkContent(progname, true);

                    bookmarkNavigator.MoveToBookmark("ItemsNum");
                    bookmarkNavigator.ReplaceBookmarkContent(i.Qty, true);


                    string [] stringarr       = i.additionals.Split(' ');
                    CyrResult addCyr          = phrase.Decline(stringarr[0], GetConditionsEnum.Strict);
                    string    additionals     = addCyr.Genitive;
                    int       index           = i.additionals.IndexOf(additionals);
                    string    additionalsTail = i.additionals.Remove(index, stringarr[0].Length);

                    bookmarkNavigator.MoveToBookmark("Additionals");
                    bookmarkNavigator.ReplaceBookmarkContent(additionals + additionalsTail, true);

                    bookmarkNavigator.MoveToBookmark("CalculationOrderDate");
                    bookmarkNavigator.ReplaceBookmarkContent(i.calcDate, true);

                    bookmarkNavigator.MoveToBookmark("CalculationOrderNum");
                    bookmarkNavigator.ReplaceBookmarkContent(i.calcNum, true);
                }

                decimal TotalSum = 0;
                var     costs    = from callitem in callDetails
                                   where (callitem.CallID == callID)
                                   select callitem.ItemTestCost;
                TotalSum = costs.Sum(c => Convert.ToDecimal(c));

                bookmarkNavigator.MoveToBookmark("TotalSum");
                bookmarkNavigator.ReplaceBookmarkContent(TotalSum.ToString(), true);

                bookmarkNavigator.MoveToBookmark("TestingDurationCalDays");
                bookmarkNavigator.ReplaceBookmarkContent("30", true);

                bookmarkNavigator.MoveToBookmark("ExpertFIO");
                bookmarkNavigator.ReplaceBookmarkContent(expName, true);

                bookmarkNavigator.MoveToBookmark("RepresentativeFIO");
                bookmarkNavigator.ReplaceBookmarkContent(repName, true);

                bookmarkNavigator.MoveToBookmark("CustomerName2");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custName, true);

                bookmarkNavigator.MoveToBookmark("TaxID");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custTaxID, true);

                bookmarkNavigator.MoveToBookmark("OKPO");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custOKPO, true);

                bookmarkNavigator.MoveToBookmark("CustomerAddress");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custAddress, true);

                bookmarkNavigator.MoveToBookmark("CustomerPhoneNum");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custPhoneNumber, true);

                bookmarkNavigator.MoveToBookmark("CustomerMphoneNum");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custMPhoneNumber, true);

                bookmarkNavigator.MoveToBookmark("BankAccount");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custAccount, true);

                bookmarkNavigator.MoveToBookmark("BankBranch");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custBankBranch, true);

                bookmarkNavigator.MoveToBookmark("BankAddress");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custBranchAddress, true);

                bookmarkNavigator.MoveToBookmark("BankCode");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custBankCode, true);

                bookmarkNavigator.MoveToBookmark("BIC");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custBIC, true);

                //Save doc file.

                if (document != null)
                {
                    string path = Server.MapPath(@"~\Area\Manager\Files\Contracts\");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    document.SaveToFile(path + @"docx\" + contract.CallID.ToString() + ".docx", Spire.Doc.FileFormat.Docx);
                    document.SaveToFile(path + @"pdf\" + contract.CallID.ToString() + ".pdf", Spire.Doc.FileFormat.PDF);
                    ViewBag.pdf = (path + @"pdf\" + contract.CallID.ToString() + ".pdf");
                }
            }

            catch (Exception e)
            {
                return(new HttpNotFoundResult(e.ToString()));
            }



            return(View());
        }
Exemple #15
0
#pragma warning disable IDE0060 // Удалите неиспользуемый параметр
        private static void Main(string[] args)
#pragma warning restore IDE0060 // Удалите неиспользуемый параметр
        {
            var logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console()
                         .WriteTo.File("logs\\foodbot.txt", rollingInterval: RollingInterval.Day)
                         .CreateLogger();

            IConfiguration configuration = new ConfigurationBuilder()
                                           .AddJsonFile("appsettings.json", true, true)
                                           .AddJsonFile("food.json", true, true)
                                           .AddJsonFile("vk.json", true, true)
                                           .Build();

            //собираем беседы в контейнер
            var      collection         = new ServiceCollection();
            Assembly ConsoleAppAssembly = typeof(Program).Assembly;
            var      ConsoleAppTypes    =
                from type in ConsoleAppAssembly.GetTypes()
                where !type.IsAbstract
                where typeof(IConversation).IsAssignableFrom(type)
                select type;

            foreach (var type in ConsoleAppTypes)
            {
                collection.AddTransient(typeof(IConversation), type);
            }

            var conf = new Dictionary <Categories, List <string> >();

            configuration.GetSection("Categories").Bind(conf);
            var cyrPhrase      = new CyrPhrase(new CyrNounCollection(), new CyrAdjectiveCollection());
            var foodDictionary = new Dictionary <Categories, List <string> >();

            foreach (KeyValuePair <Categories, List <string> > cat in conf)
            {
                var l = new List <string>();

                foreach (var food in cat.Value)
                {
                    var s = cyrPhrase.Decline(food.ToLower(), Cyriller.Model.GetConditionsEnum.Similar).ToList();
                    var p = cyrPhrase.DeclinePlural(food.ToLower(), Cyriller.Model.GetConditionsEnum.Similar).ToList();
                    l.AddRange(s.Union(p).Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList());
                }

                foodDictionary.Add(cat.Key, l);
            }

            cyrPhrase = null;

            var client = new TelegramBotClient(configuration["BotKey"]);

            collection.AddSingleton <BotEngine>();
            collection.AddSingleton(client);
            collection.AddSingleton(configuration);
            collection.AddTransient <IJob, ParseVkJob>();
            collection.AddTransient <StateRepository>();
            collection.AddTransient <NoticeRepository>();
            collection.AddTransient <VkParser>();
            collection.AddSingleton(foodDictionary);
            collection.AddSingleton <ILogger>(logger);
            collection.AddTransient <Categorizer>();
            collection.AddTransient <Geocoding>();
            var serviceProvider = collection.BuildServiceProvider();

            // on-start self-check
            var me = client.GetMeAsync().Result;

            Console.WriteLine(
                $"Hello! I am user {me.Id} and my name is {me.FirstName}."
                );

            // регистрируем движок и вешаем события
            BotEngine engine = serviceProvider.GetService <BotEngine>();

            client.OnMessage       += engine.BotOnMessageReceived;
            client.OnReceiveError  += engine.BotOnReceiveError;
            client.OnInlineQuery   += engine.BotOnInlineQuery;
            client.OnCallbackQuery += engine.BotOnCallbackQuery;

            // endless background job
            Thread workerThread = new Thread(async() =>
            {
                while (true)
                {
                    var jobs = serviceProvider.GetServices <IJob>().ToList();
                    foreach (IJob j in jobs)
                    {
                        try
                        {
                            await j.Execute();
                        }
                        catch (Exception ex)
                        {
                            logger.Error("{@ex}", ex);
                        }
                    }
                    ;
                    Thread.Sleep(int.Parse(configuration["JobSleepTimer"]));
                }
            });

            workerThread.Start();

            client.StartReceiving();
            Console.ReadLine();
            client.StopReceiving();
        }