Exemplo n.º 1
0
    public static Apteka operator ++(Apteka apteka)
    {
        Apteka    newApteka = new Apteka();
        Exception a;
        string    f;
        int       n;

        try
        {
            if (apteka.numOfMeds >= Apteka.maxNumOfMeds)
            {
                throw a = new Exception("0");
            }
            newApteka.name        = apteka.name;
            newApteka.num         = apteka.num;
            newApteka.numOfMeds   = apteka.numOfMeds;
            newApteka.numOfProzs  = apteka.numOfProzs;
            newApteka.numOfWorlds = apteka.numOfWorlds;
            for (n = 0; n < apteka.numOfMeds; n++)
            {
                newApteka.lek[n] = new Lek();
                newApteka.lek[n] = apteka.lek[n];
            }
            for (n = 0; n < apteka.numOfProzs; n++)
            {
                newApteka.proizvoditel[n] = new Proizvoditel();
                newApteka.proizvoditel[n] = apteka.proizvoditel[n];
            }
            for (n = 0; n < apteka.numOfWorlds; n++)
            {
                newApteka.naz_world[n] = new Naz_world();
                newApteka.naz_world[n] = apteka.naz_world[n];
            }
            Console.WriteLine("Добавить лекарство - 1, производителя - 2, страну производства - 3");
            f = Console.ReadLine();
            if (f == "1")
            {
                newApteka.lek[apteka.numOfMeds] = new Lek();
                newApteka.lek[apteka.numOfMeds].read();
                newApteka.numOfMeds = ++apteka.numOfMeds;
            }
            else if (f == "2")
            {
                newApteka.proizvoditel[apteka.numOfProzs] = new Proizvoditel();
                newApteka.proizvoditel[apteka.numOfProzs].read(1);
                newApteka.numOfProzs = ++apteka.numOfProzs;
            }
            else
            {
                newApteka.naz_world[apteka.numOfWorlds] = new Naz_world();
                newApteka.naz_world[apteka.numOfWorlds].read(1);
                newApteka.numOfWorlds = ++apteka.numOfWorlds;
            }
            return(newApteka);
        }
        catch (Exception)
        {
            return(apteka);
        }
    }
Exemplo n.º 2
0
    public static Apteka operator +(Apteka apteka1, Apteka apteka2)
    {
        int       n, i;
        Apteka    newApteka = new Apteka();
        Exception a;

        try
        {
            if (apteka1.numOfMeds + apteka2.numOfMeds > Apteka.maxNumOfMeds)
            {
                throw a = new Exception("0");
            }
            newApteka.name      = apteka1.name;
            newApteka.num       = apteka1.num;
            newApteka.numOfMeds = apteka1.numOfMeds + apteka2.numOfMeds;
            for (n = 0; n < apteka1.numOfMeds; n++)
            {
                newApteka.lek[n] = apteka1.lek[n];
            }
            i = apteka1.numOfMeds;
            for (n = 0; n < apteka2.numOfMeds; n++)
            {
                newApteka.lek[i] = apteka2.lek[n];
                i++;
            }
            newApteka.numOfProzs = apteka1.numOfProzs + apteka2.numOfProzs;
            for (n = 0; n < apteka1.numOfProzs; n++)
            {
                newApteka.proizvoditel[n] = apteka1.proizvoditel[n];
            }
            i = apteka1.numOfProzs;
            for (n = 0; n < apteka2.numOfProzs; n++)
            {
                newApteka.proizvoditel[i] = apteka2.proizvoditel[n];
                i++;
            }
            newApteka.numOfWorlds = apteka1.numOfWorlds + apteka2.numOfWorlds;
            for (n = 0; n < apteka1.numOfWorlds; n++)
            {
                newApteka.naz_world[n] = apteka1.naz_world[n];
            }
            i = apteka1.numOfWorlds;
            for (n = 0; n < apteka2.numOfWorlds; n++)
            {
                newApteka.naz_world[i] = apteka2.naz_world[n];
                i++;
            }
            return(newApteka);
        }
        catch (Exception)
        {
            return(apteka1);
        }
    }
Exemplo n.º 3
0
 public void Update(Apteka apteka)
 {
     _apteka.Aptekas.Update(apteka);
     _apteka.SaveChanges();
 }
Exemplo n.º 4
0
 public void Remove(Apteka apteka)
 {
     _apteka.Aptekas.Remove(apteka);
     _apteka.SaveChanges();
 }
Exemplo n.º 5
0
 public void Insert(Apteka apteka)
 {
     _apteka.Aptekas.Add(apteka);
     _apteka.SaveChanges();
 }
Exemplo n.º 6
0
    static void Main(string[] args)
    {
        Apteka[]       apteka1 = new Apteka[10];
        Lek[]          lek1 = new Lek[10];
        Proizvoditel[] proz1 = new Proizvoditel[10];
        Naz_world[]    world1 = new Naz_world[10];
        int            numOfMeds, i, max, n, numOfProzs, numOfWorlds = 0, lekAmount, d;

        int[]  date = new int[3];
        double price;
        double lekPrice;
        string f, mass, name, num, lekMass, lekName;

        string[] s1 = new string[10], worlds = new string[10], world_naz = new string[10], import = new string[10];
        Console.WriteLine("Использовать или read чтобы ввести данные(1 - read, 2 - init)");
        f = Console.ReadLine();
        if (f == "1")
        {
            apteka1[0] = new Apteka();
            apteka1[0].read();
        }
        else if (f == "2")
        {
            Console.WriteLine("Ввести все параметры (1), только название (2), не вводить параметры(3)");
            f = Console.ReadLine();
            if (f == "1")
            {
                Console.WriteLine("Введите название аптеки: ");
                name = Console.ReadLine();
                Console.WriteLine("Введите номер аптеки: ");
                num       = Console.ReadLine();
                numOfMeds = 0;;
                Console.WriteLine("Добавить лекарство ?(1 - да, 0 - нет)");
                f = Console.ReadLine();
                while (f == "1")
                {
                    Console.WriteLine("Введите название лекарства: ");
                    lekName = Console.ReadLine();
                    Console.WriteLine("Введите код лекарства: ");
                    lekMass = Console.ReadLine();
                    do
                    {
                        Console.WriteLine("Введите цену: ");
                        try
                        {
                            lekPrice = Convert.ToDouble(Console.ReadLine());
                        }
                        catch (FormatException) {
                            lekPrice = -1;
                        }
                    } while (lekPrice < 0);
                    do
                    {
                        Console.WriteLine("Введите колличество лекарства: ");
                        try
                        {
                            lekAmount = Convert.ToInt32(Console.ReadLine());
                        }
                        catch (FormatException)
                        {
                            lekAmount = -1;
                        }
                    } while (lekAmount < 0);
                    lek1[numOfMeds] = new Lek(lekName, lekMass, lekPrice, lekAmount);
                    numOfMeds++;
                    Console.WriteLine("Добавить лекарство ?(1 - да, 0 - нет)");
                    f = Console.ReadLine();
                    if (f == "0")
                    {
                        break;
                    }
                }
                numOfProzs = 0;
                Console.WriteLine("Добавить производителя ? (1 - да, 0 - нет)");
                f = Console.ReadLine();
                while (f == "1")
                {
                    Console.WriteLine("Введите название производителя: ");
                    lekName = Console.ReadLine();
                    Console.WriteLine("Введите код производителя: ");
                    lekMass = Console.ReadLine();
                    do
                    {
                        Console.WriteLine("Введите цену: ");
                        try
                        {
                            lekPrice = Convert.ToDouble(Console.ReadLine());
                        }
                        catch (FormatException)
                        {
                            lekPrice = -1;
                        }
                    } while (lekPrice < 0);
                    do
                    {
                        Console.WriteLine("Введите колличество лекарства: ");
                        try
                        {
                            lekAmount = Convert.ToInt32(Console.ReadLine());
                        }
                        catch (FormatException)
                        {
                            lekAmount = -1;
                        }
                    } while (lekAmount < 0);
                    Console.WriteLine("Введите дату (00.00.0000) день, месяц, год после ввода дня, месяца, года нажимайте Enter)");
                    date[0] = Convert.ToInt32(Console.ReadLine());
                    date[1] = Convert.ToInt32(Console.ReadLine());
                    date[2] = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("Введите страну производства (чтобы закончить введите пустую строку)");
                    numOfWorlds = 0;
                    d           = -1;
                    do
                    {
                        numOfWorlds++;
                        d++;
                        worlds[d] = Console.ReadLine();
                    } while (worlds[d] != "");
                    proz1[numOfProzs] = new Proizvoditel(lekName, lekMass, lekPrice, lekAmount, date, worlds);
                    numOfProzs++;
                    Console.WriteLine("Добавить ещё производителя ?(1 - да, 0 - нет)");
                    f = Console.ReadLine();
                }
                apteka1[0] = new Apteka(name, num, numOfMeds, lek1, numOfProzs, proz1, numOfWorlds, world1);
            }
            else if (f == "2")
            {
                Console.WriteLine("Введите название аптеки: ");
                name       = Console.ReadLine();
                apteka1[0] = new Apteka(name);
            }
            else
            {
                apteka1[0] = new Apteka();
            }
        }
        i   = 0;
        max = 1;
        f   = "1";
        while (f != "10")
        {
            Console.WriteLine("Введите номер следующего действия:");
            Console.WriteLine("1 - показать информацию о аптеки");
            Console.WriteLine("2 - добавить новое лекарство");
            Console.WriteLine("3 - изменить цену лекарства");
            Console.WriteLine("4 - добавить аптеку");
            Console.WriteLine("5 - показать все аптеки");
            Console.WriteLine("6 - сменить аптеку");
            Console.WriteLine("7 - сложить аптеки");
            Console.WriteLine("8 - добавить страну производства лекарства");
            Console.WriteLine("9 - копирование");
            Console.WriteLine("10 - выйти");
            f = Console.ReadLine();
            if (f == "1")
            {
                apteka1[i].display();
            }
            else if (f == "2")
            {
                apteka1[i] = ++apteka1[i];
            }
            else if (f == "3")
            {
                Console.WriteLine("Введите код лекарства: ");
                mass = Console.ReadLine();
                do
                {
                    Console.WriteLine("Введите новую цену: ");
                    try
                    {
                        price = Convert.ToDouble(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        price = -1;
                    }
                } while (price < 0);
                apteka1[i].priceChange(mass, price);
            }
            else if (f == "4")
            {
                apteka1[max] = new Apteka();
                apteka1[max].read();
                i = max;
                max++;
            }
            else if (f == "5")
            {
                for (n = 0; n < max; n++)
                {
                    Console.WriteLine("Аптека: " + apteka1[n].Name);
                }
            }
            else if (f == "6")
            {
                Console.WriteLine("Введите название аптеки: ");
                name = Console.ReadLine();
                for (n = 0; n < max; n++)
                {
                    if (apteka1[n].Name == name)
                    {
                        i = n;
                        n = max;
                    }
                }
            }
            else if (f == "7")
            {
                Console.WriteLine("Введите название аптеки: ");
                name = Console.ReadLine();
                for (n = 0; n < max; n++)
                {
                    if (apteka1[n].Name == name)
                    {
                        apteka1[i] = apteka1[i] + apteka1[n];
                        n          = max;
                    }
                }
            }
            else if (f == "8")
            {
                Console.WriteLine("Введите код лекарства: ");
                mass = Console.ReadLine();
                apteka1[i].add(mass);
            }
            else if (f == "9")
            {
                date[0]         = date[1] = date[2] = 1;
                worlds[0]       = "aaa";
                proz1[0]        = new Proizvoditel("proz", "proz", 1, 1, date, world_naz);
                worlds[0]       = "zzz";
                world1[0]       = new Naz_world("world", "world", 2, 2, import, world_naz);
                proz1[1]        = (Proizvoditel)proz1[0].Clone();
                proz1[1].Amount = 2;
                proz1[0].display();
                world1[1]        = world1[0];
                world1[1].Amount = 3;
                world1[0].display();
            }
        }
    }
Exemplo n.º 7
0
        //определение параметров аптеки
        private async Task <List <Apteka> > GetAptekaModel(string aptekaId)
        {
            List <Apteka> data = new List <Apteka>();

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    await connection.OpenAsync();

                    SqlCommand query = new SqlCommand
                    {
                        CommandText = $@"select CONVERT(VARCHAR(20), reg.region) RegionId, 
                                               isnull(apt.Region, '') RegionName, 
                                               isnull(cl.naimen, '') FullAptekaName, 
                                               isnull(apt.TaxType, '') TaxType
                                        from opeka_base.dbo.AptInfo apt
                                                left join [vm-sql2008].Ges.dbo.spr_region reg on case
                                                    when apt.Region = 'Республика Мордовия' then 'Республика Мордовия (Саранск)'
                                                    when apt.Region = 'Удмуртия' then 'Удмуртская республика'
                                                    when apt.Region = 'КОМИ (1 зона Сыктывкар)' then 'Республика Коми (1 зона)'
                                                    when apt.Region = 'Республика Саха' then 'Респ. Саха (1 зона)'
                                                    when apt.Region = 'КОМИ (2 зона Сыктывкар)' then 'Республика Коми (2 зона)'
                                                    when apt.Region = 'Марий Эл республика' then 'Республика Марий-Эл'
                                                    when apt.Region = 'Красноярский край (зона 3)' then 'Красноярский край (3 зона)'
                                                    when apt.Region = 'Красноярский край (зона 1)' then 'Красноярский край (1 зона)'
                                                    when apt.Region = 'Москва (город)' then 'г.Москва'
                                                    when apt.Region = 'ХМАО (Сургут)' then 'Ханты-Мансийский автономный округ'
                                                    when apt.Region = 'Санкт-Петербург (город)' then 'г.Санкт-Петербург'
                                                    when apt.Region = 'ЯНАО (2 зона Уренгой)' then 'Ямало-Ненецкий автономный округ(2 зона)'
                                                    when apt.Region = 'Татарстан' then 'Республика Татарстан'
                                                    when apt.Region = 'ЯНАО (1 зона Уренгой) ' then 'Ямало-Ненецкий автономный округ(1 зона)'
                                                    when apt.Region = 'Башкирия' then 'Республика Башкортостан'
                                                    else apt.Region end = reg.name_reg
                                                left join [Servsql].admzakaz.dbo.clients cl on cl.kp = apt.IDApt
                                        where apt.idapt = @aptekaId;",
                        Connection  = connection
                    };
                    query.Parameters.AddWithValue("aptekaId", int.Parse(aptekaId));
                    SqlDataReader reader = await query.ExecuteReaderAsync();

                    while (await reader.ReadAsync())
                    {
                        Apteka row = new Apteka
                        {
                            RegionId       = reader["RegionId"] as string,
                            RegionName     = reader["RegionName"] as string,
                            FullAptekaName = reader["FullAptekaName"] as string,
                            TaxType        = reader["TaxType"] as string
                        };
                        if (string.IsNullOrEmpty(row.RegionId))
                        {
                            throw new Exception("Ошибка! Не найден регион для аптеки apteka_id = " + aptekaId);
                        }
                        data.Add(row);
                    }
                    reader.Close();
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message + Environment.NewLine + e.StackTrace);
            }
            return(data);
        }
Exemplo n.º 8
0
        //главная страница сайта
        public async Task <IActionResult> Index()
        {
            //если в браузере есть куки с ключом aptekaId, то выполняем автоматическую аутентификацию используя этот идентификатор aptekaId
            if (HttpContext.Request.Cookies.ContainsKey("aptekaId") && !IsAuthenticated())
            {
                string _aptekaId = HttpContext.Request.Cookies["aptekaId"];
                await AutoLoginByCookie(_aptekaId);

                return(RedirectToAction("Index"));
            }

            if (!IsAuthenticated())
            {
                HttpContext.Session.Remove("aptekaModel");
                HttpContext.Session.Remove("aptekaId");
                HttpContext.Session.Remove("userString");
                return(View("Logout"));
            }

            //определяем адрес на который пришел запрос gv.qwerty.plus или gnvls.qwerty.plus
            string requestUrl = HttpContext.Request.Host.Host;

            ViewBag.requestUrl = requestUrl;
            //ViewBag.requestUrl = "gv.qwerty.plus";
            //requestUrl = "gv.qwerty.plus";

            //параметры для постраничной навигации
            int offset    = 0;  //default value
            int rowsCount = 20; //default value

            //id аптеки получаем из сессии, значение сохранено в сессию при аутентификации
            string aptekaId = HttpContext.Session.GetString("aptekaId");

            //проверяем наличие значения id аптеки, если его нет, то отправляем на страницу аутентификации
            if (string.IsNullOrEmpty(aptekaId))
            {
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

                //return RedirectToPage("/Account/Login");
                return(View("Logout"));
            }

            //сохраняем id аптеки в куки на стороне клиента, используется для автоматической аутентификации
            //if (!HttpContext.Request.Cookies.ContainsKey("aptekaId") || HttpContext.Request.Cookies["aptekaId"] != aptekaId)
            //{
            //}
            var cookieOptions = new CookieOptions()
            {
                Path        = "/",
                HttpOnly    = true,
                IsEssential = true,
                SameSite    = SameSiteMode.Strict,
                Expires     = DateTime.Now.AddMonths(1) //срок жизни куки атоматической авторизации
            };

            HttpContext.Response.Cookies.Append("aptekaId", aptekaId, cookieOptions);

            ViewBag.aptekaId = aptekaId;
            Apteka aptekaModel = null;

            //заносим модель аптеки в сессию
            if (HttpContext.Session.Keys.Contains("aptekaModel"))
            {
                aptekaModel = HttpContext.Session.Get <Apteka>("aptekaModel");
            }
            else
            {
                List <Apteka> apteka = await GetAptekaModel(aptekaId);

                HttpContext.Session.Set("aptekaModel", apteka.First());
            }

            //срабатывает только при первом обращении к контроллеру, когда модели аптеки еще нет в сессии
            if (aptekaModel == null)
            {
                aptekaModel = HttpContext.Session.Get <Apteka>("aptekaModel");
            }

            ViewBag.RegionId       = aptekaModel.RegionId;
            ViewBag.RegionName     = aptekaModel.RegionName;
            ViewBag.FullAptekaName = aptekaModel.FullAptekaName;
            ViewBag.TaxType        = aptekaModel.TaxType;

            string userString = string.Empty;

            if (Request.Method == "POST")
            {
                //сохраняем строку поиска в сессию, используется для выгрузки данных в csv
                if (Request.Form.Keys.Contains("userString"))
                {
                    userString = Request.Form["userString"];
                    HttpContext.Session.SetString("userString", userString);
                }
            }

            try
            {
                //создаем временную таблицу с результатами
                await CreateTempDataTable(aptekaId, aptekaModel.RegionId);

                //определяем количество страниц для навигации сайта
                int pagesCount = await GetRecordsCount(aptekaId, userString);

                if (Request.Method == "GET")
                {
                    pagesCount         = (int)Math.Ceiling((double)pagesCount / rowsCount);
                    ViewBag.PagesCount = pagesCount;
                }

                if (Request.Method == "POST")
                {
                    int currentPage = 1;

                    if (!string.IsNullOrEmpty(Request.Form["currentPage"]))
                    {
                        currentPage = int.Parse(Request.Form["currentPage"]);
                    }

                    if (!string.IsNullOrEmpty(Request.Form["rowsCount"]))
                    {
                        rowsCount = int.Parse(Request.Form["rowsCount"]);
                    }
                    pagesCount         = (int)Math.Ceiling((double)pagesCount / rowsCount);
                    ViewBag.PagesCount = pagesCount;

                    if (!string.IsNullOrEmpty(Request.Form["direction"]))
                    {
                        switch (Request.Form["direction"])
                        {
                        case "next":
                            if (currentPage < pagesCount)
                            {
                                currentPage++;
                            }
                            offset = (currentPage - 1) * rowsCount;
                            break;

                        case "prev":
                            if (currentPage > 1)
                            {
                                currentPage--;
                            }
                            offset = (currentPage - 1) * rowsCount;
                            break;

                        case "first":
                            offset = 0;
                            break;

                        case "last":
                            offset = (pagesCount - 1) * rowsCount;
                            break;

                        case "select-page":
                            offset = (currentPage - 1) * rowsCount;
                            break;

                        case "page-size":
                            offset = (currentPage - 1) * rowsCount;
                            break;
                        }
                    }
                }

                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    await connection.OpenAsync();

                    string name    = string.Empty;
                    string barcode = string.Empty;

                    if (Regex.IsMatch(userString, @"^\d+$") && userString.Length >= 8)
                    {
                        barcode = userString;
                    }
                    else
                    {
                        name = userString;
                    }

                    SqlCommand query = new SqlCommand();
                    query.CommandText = SqlCommandText.ForSite1;
                    query.Connection  = connection;
                    query.Parameters.AddWithValue("offset", offset);
                    query.Parameters.AddWithValue("rowsCount", rowsCount);
                    //query.Parameters.AddWithValue("aptekaId", int.Parse(aptekaId));
                    //query.Parameters.AddWithValue("regionId", int.Parse(aptekaModel.RegionId));
                    query.Parameters.AddWithValue("name", "%" + name + "%");
                    query.Parameters.AddWithValue("barcode", "%" + barcode + "%");
                    query.Parameters.AddWithValue("tableName", "tmp_gnvls_" + aptekaId);

                    SqlDataReader reader = await query.ExecuteReaderAsync();

                    if (reader.HasRows)
                    {
                        while (await reader.ReadAsync())
                        {
                            Reestr row = new Reestr
                            {
                                FullAptekaName          = reader["FullAptekaName"] as string,
                                Mhh                     = reader["Mhh"] as string,
                                Series                  = reader["Series"] as string,
                                Name                    = reader["Name"] as string,
                                Pro                     = reader["Pro"] as string,
                                Barcode                 = reader["Barcode"] as string,
                                Nds                     = reader["Nds"] as string,
                                ProducerRegisteredPrice = reader["ProducerRegisteredPrice"] as string,
                                ProducerRealPrice       = reader["ProducerRealPrice"] as string,
                                PurchasePriceWithoutVAT = reader["PurchasePriceWithoutVAT"] as string,
                                PremiumInPercentOpt     = reader["PremiumInPercentOpt"] as string,
                                PremiumInRubOpt         = reader["PremiumInRubOpt"] as string,
                                MaxOptPercent           = reader["MaxOptPercent"] as string,
                                PurchasePrice           = reader["PurchasePrice"] as string,
                                RetailPriceWithoutVAT   = reader["RetailPriceWithoutVAT"] as string,
                                PremiumInPercentRetail  = reader["PremiumInPercentRetail"] as string,
                                PremiumInRubRetail      = reader["PremiumInRubRetail"] as string,
                                MaxRetailPercent        = reader["MaxRetailPercent"] as string,
                                RetailPrice             = reader["RetailPrice"] as string
                            };
                            data.Add(row);
                        }
                    }
                    else
                    {
                        ViewBag.Message = "Запрошенная информация не найдена";
                    }
                    reader.Close();
                }
            }
            catch (SqlException e)
            {
                ViewBag.Message = "Ошибка получения данных с сервера, обновите страницу";
                WebExtensions.WriteToLog(logPath, DateTime.Now + " " + e.Message + Environment.NewLine + e.StackTrace + Environment.NewLine);
            }
            catch (Exception e)
            {
                ViewBag.Message = "Произошла критическая ошибка в работе приложения, пожалуйста перезагрузите ваш браузер, если ошибка будет повторяться - обратитесь к разработчику сайта";
                WebExtensions.WriteToLog(logPath, DateTime.Now + " " + e.Message + Environment.NewLine + e.StackTrace + Environment.NewLine);
            }

            if (Request.Method == "POST")
            {
                if (requestUrl == "gv.qwerty.plus")
                {
                    return(PartialView("_IndexGv", data));
                }
                return(PartialView("_Index", data));
            }

            if (requestUrl == "gv.qwerty.plus")
            {
                return(View("IndexGv", data));
            }
            return(View("Index", data));
        }
Exemplo n.º 9
0
        public async Task <IActionResult> DownloadScv()
        {
            if (!IsAuthenticated())
            {
                HttpContext.Session.Remove("aptekaModel");
                HttpContext.Session.Remove("aptekaId");
                HttpContext.Session.Remove("userString");
                return(View("Logout"));
            }

            //string path = Path.Combine(Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory), "files", "gnvls.csv");
            try
            {
                IEnumerable <Reestr> data = await GetCsvData();

                using (MemoryStream memoryStream = new MemoryStream())
                    //using (StreamWriter writer = new StreamWriter(path, false, Encoding.GetEncoding(1251), 1024))
                    using (StreamWriter writer = new StreamWriter(memoryStream, Encoding.GetEncoding(1251)))
                        using (CsvWriter csvWriter = new CsvWriter(writer))
                        {
                            writer.AutoFlush = true; //автоматом сбрасывает буффер в поток, при каждом вызове Write
                            csvWriter.Configuration.Delimiter       = ";";
                            csvWriter.Configuration.HasHeaderRecord = true;
                            csvWriter.Configuration.RegisterClassMap <ReestrClassMap>();
                            csvWriter.WriteHeader <Reestr>();
                            csvWriter.NextRecord();
                            csvWriter.WriteRecords(data);
                            memoryStream.Position = 0;
                            return(File(memoryStream.ToArray(), "application/octet-stream", "gnvls.csv"));
                        }
                //return PhysicalFile(path, "application/octet-stream", "Files/gnvls.csv");
            }
            catch (SqlException e)
            {
                //для заполнения шапки страницы получаем из сессии модель аптеки и ее id
                if (HttpContext.Session.Keys.Contains("aptekaModel"))
                {
                    Apteka aptekaModel = HttpContext.Session.Get <Apteka>("aptekaModel");
                    ViewBag.FullAptekaName = aptekaModel.FullAptekaName;
                    ViewBag.RegionName     = aptekaModel.RegionName;
                    ViewBag.TaxType        = aptekaModel.TaxType;
                }
                ViewBag.aptekaId = HttpContext.Session.GetString("aptekaId");

                ViewBag.Message = "Ошибка получения данных с сервера, обновите страницу и попробуйте повторно выгрузить данные";
                WebExtensions.WriteToLog(logPath, DateTime.Now + " " + e.Message + Environment.NewLine + e.StackTrace + Environment.NewLine);
                return(View("Index", data));
            }
            catch (Exception e)
            {
                //для заполнения шапки страницы получаем из сессии модель аптеки и ее id
                if (HttpContext.Session.Keys.Contains("aptekaModel"))
                {
                    Apteka aptekaModel = HttpContext.Session.Get <Apteka>("aptekaModel");
                    ViewBag.FullAptekaName = aptekaModel.FullAptekaName;
                    ViewBag.RegionName     = aptekaModel.RegionName;
                    ViewBag.TaxType        = aptekaModel.TaxType;
                }
                ViewBag.aptekaId = HttpContext.Session.GetString("aptekaId");

                ViewBag.Message = "Произошла ошибка в работе приложения, обновите страницу";
                WebExtensions.WriteToLog(logPath, DateTime.Now + " " + e.Message + Environment.NewLine + e.StackTrace + Environment.NewLine);
                return(View("Index", data));
            }
        }
Exemplo n.º 10
0
        public async Task <IEnumerable <Reestr> > GetCsvData()
        {
            string aptekaId    = HttpContext.Session.GetString("aptekaId");
            Apteka aptekaModel = HttpContext.Session.Get <Apteka>("aptekaModel");

            string name    = string.Empty;
            string barcode = string.Empty;

            if (HttpContext.Session.Keys.Contains("userString"))
            {
                string userString = HttpContext.Session.GetString("userString");
                if (Regex.IsMatch(userString, @"^\d+$") && userString.Length >= 8)
                {
                    barcode = userString;
                }
                else
                {
                    name = userString;
                }
            }

            SqlCommand query = new SqlCommand();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                await connection.OpenAsync();

                query.CommandText = SqlCommandText.ForCsv1;
                query.Connection  = connection;
                //query.Parameters.AddWithValue("aptekaId", int.Parse(aptekaId));
                //query.Parameters.AddWithValue("regionId", int.Parse(aptekaModel.RegionId));
                query.Parameters.AddWithValue("name", "%" + name + "%");
                query.Parameters.AddWithValue("barcode", "%" + barcode + "%");
                query.Parameters.AddWithValue("tableName", "tmp_gnvls_" + aptekaId);
                SqlDataReader reader = await query.ExecuteReaderAsync();

                if (reader.HasRows)
                {
                    while (await reader.ReadAsync())
                    {
                        Reestr row = new Reestr
                        {
                            FullAptekaName          = reader["FullAptekaName"] as string,
                            Mhh                     = reader["Mhh"] as string,
                            Series                  = reader["Series"] as string,
                            Name                    = reader["Name"] as string,
                            Pro                     = reader["Pro"] as string,
                            Barcode                 = reader["Barcode"] as string,
                            Nds                     = reader["Nds"] as string,
                            ProducerRegisteredPrice = reader["ProducerRegisteredPrice"] as string,
                            ProducerRealPrice       = reader["ProducerRealPrice"] as string,
                            PurchasePriceWithoutVAT = reader["PurchasePriceWithoutVAT"] as string,
                            PremiumInPercentOpt     = reader["PremiumInPercentOpt"] as string,
                            PremiumInRubOpt         = reader["PremiumInRubOpt"] as string,
                            MaxOptPercent           = reader["MaxOptPercent"] as string,
                            PurchasePrice           = reader["PurchasePrice"] as string,
                            RetailPriceWithoutVAT   = reader["RetailPriceWithoutVAT"] as string,
                            PremiumInPercentRetail  = reader["PremiumInPercentRetail"] as string,
                            PremiumInRubRetail      = reader["PremiumInRubRetail"] as string,
                            MaxRetailPercent        = reader["MaxRetailPercent"] as string,
                            RetailPrice             = reader["RetailPrice"] as string
                        };
                        data.Add(row);
                    }
                }
                reader.Close();
            }
            return(data);
        }