Exemple #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            context = new SaalutDataClasses1DataContext();

            if (Request.QueryString["GID"] == null)
            {
                //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                Response.Redirect("TermoTickets.aspx");
            }


            Int32.TryParse(Request.QueryString["GID"], out goodID);
            Int32.TryParse(Request.QueryString["TID"], out typeID);
            Int32.TryParse(Request.QueryString["QTY"], out qty);
            Int32.TryParse(Request.QueryString["PID"], out printerID);

            string dateTm = Session["DataVremTextBox1"].ToString();

            if (goodID == 0)
            {
                //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                Response.Redirect("TermoTickets.aspx");
            }



            //------
            if (!IsPostBack)
            {
                TermLabelUtils utl = new TermLabelUtils();
                utl.PrintTermoLabel(goodID, typeID, qty, printerID, dateTm);
            }
        }
Exemple #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }

            Int32.TryParse(Request.QueryString["ID"], out jourID);

            if (jourID == 0)
            {
                Response.Redirect("~/SkladTSD/Default.aspx");
            }

            JourNumLabel1.Text = "Журнал N " + jourID.ToString();
            Page.Title         = "Журнал N " + jourID.ToString();

            JourLinesLinqDataSource1.WhereParameters[0].DefaultValue = jourID.ToString();

            BarcodeTextBox1.Focus();
            if (!IsPostBack)
            {
                BarcodeTextBox2.Text = "1";
            }
        }
Exemple #3
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (context == null)
     {
         context = new SaalutDataClasses1DataContext();
     }
 }
Exemple #4
0
        protected void SubmitButton1_Click(object sender, EventArgs e)
        {
            OutInfoLiteral1.Text = "";

            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }

            string findStr = ForFindTextBox1.Text;

            var goodArt = (from g in context.Goods
                           where g.Articul == findStr
                           select g).FirstOrDefault();

            if (goodArt == null)
            {
                Int32 findInt = 0;
                Int32.TryParse(findStr, out findInt);

                var goodPlu = (from g in context.Goods
                               where g.PLU == findInt
                               select g).FirstOrDefault();
                if (goodPlu == null)
                {
                    var barcode = (from b in context.Barcodes
                                   where b.Barcode1 == findStr
                                   select b).FirstOrDefault();
                    if (barcode == null)
                    {
                        OutInfoLiteral1.Text = "Товар не найден, попробуйте найти по Артикулу или Штрих-коду или обратитесь в ИТ службу.";
                    }
                    else
                    {
                        UKMDataBaseConnects utl = new UKMDataBaseConnects();
                        utl.UpdateGood(barcode.Good, barcode.Good.Articul);
                        //2
                        utl.UpdateGood(barcode.Good, barcode.Good.Articul);
                        GoodInfo(barcode.Good);
                    }
                }
                else
                {
                    UKMDataBaseConnects utl = new UKMDataBaseConnects();
                    utl.UpdateGood(goodPlu, goodPlu.Articul);
                    //2
                    utl.UpdateGood(goodPlu, goodPlu.Articul);
                    GoodInfo(goodPlu);
                }
            }
            else
            {
                UKMDataBaseConnects utl = new UKMDataBaseConnects();
                utl.UpdateGood(goodArt, goodArt.Articul);
                //2
                utl.UpdateGood(goodArt, goodArt.Articul);
                GoodInfo(goodArt);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            context = new SaalutDataClasses1DataContext();

            if (!IsPostBack)
            {
                DataVremTextBox1.Text = String.Format("{0:d/M/yyyy HH:mm}", DateTime.Now);
            }
        }
Exemple #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SaalutDataClasses1DataContext context = new SaalutDataClasses1DataContext();
            CheckBoxList chb = new CheckBoxList();

            chb.ID = "WTCheckBoxList1";

            var weights = from w in context.WeightDeparts
                          where w.Active == true
                          orderby w.Num
                          select w;

            string lastW = "";

            foreach (WeightDepart wt in weights)
            {
                if (lastW == wt.Num)
                {
                    continue;
                }

                string weightName = "Весы №" + wt.Num + " ";
                var    wds        = from w in context.WeightDeparts
                                    where w.Num == wt.Num &&
                                    w.Active == true
                                    select w;
                foreach (WeightDepart wtd in wds)
                {
                    var dept = (from d in context.Departments
                                where d.ID == wtd.DepartmentID &&
                                d.Active == true
                                select d).FirstOrDefault();

                    if (dept == null)
                    {
                        continue;
                    }

                    weightName += dept.DepartName + " ";
                }

                ListItem itm = new ListItem();
                itm.Value = wt.Num;
                itm.Text  = weightName;
                chb.Items.Add(itm);

                lastW = wt.Num;
            }

            if (weights.Count() > 0)
            {
                WeightsPlaceHolder1.Controls.Add(chb);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }

            if (!IsPostBack)
            {
                txbOnDate.Text = DateTime.Today.ToString("yyyyMMdd");
            }
        }
Exemple #8
0
        protected void LoadArtButton2_Click(object sender, EventArgs e)
        {
            context = new SaalutDataClasses1DataContext();

            var good = (from g in context.Goods
                        where g.Articul == ArtTextBox1.Text
                        select g).FirstOrDefault();

            UKMDataBaseConnects utl = new UKMDataBaseConnects();

            utl.UpdateGood(good, ArtTextBox1.Text);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            context = new SaalutDataClasses1DataContext();

            if (Request.QueryString["ID"] == null)
            {
                Response.Redirect("~/NewJours.aspx");
            }

            Int32.TryParse(Request.QueryString["ID"], out jourID);

            if (jourID == 0)
            {
                Response.Redirect("~/NewJours.aspx");
            }

            NewJourLineLinqDataSource1.WhereParameters[0].DefaultValue = jourID.ToString();
            NewJourLineLinqDataSource1.DataBind();


            if (!IsPostBack)
            {
                if (Session["JourCart"] == null)
                {
                    Session["JourCart"] = new JourCart();
                }

                if (Session["PrintTemplateCart"] == null)
                {
                    Session["PrintTemplateCart"] = new PrintTemplateCart();
                }
            }

            var jour = (from j in context.PriceChangeJours
                        where j.ID == jourID
                        select j).FirstOrDefault();

            if (jour == null)
            {
                Response.Redirect("~/Default.aspx");
            }

            if (jour.Order_no != 0)
            {
                JournalNumLabel1.Text = "Журнал УКМ N: " + jour.Order_no.ToString();
            }
            else
            {
                JournalNumLabel1.Text = "Журнал УКМ N: " + jour.ID.ToString();
            }
        }
Exemple #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }

            if (!IsPostBack)
            {
                Session["JourCart"] = new JourCart();

                Session["PrintTemplateCart"] = new PrintTemplateCart();
            }
        }
Exemple #11
0
        // загрузка через кулоад по отделам
        public void SaveToLog(string type, string message)
        {
            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }

            Log log = new Log();

            log.TimeStamp = DateTime.Now;
            log.Type      = type;
            log.Message   = message;
            context.Logs.InsertOnSubmit(log);
            context.SubmitChanges();
        }
        public RfcConfigParameters GetParameters(String destinationName)
        {
            if (contextD == null)
            {
                contextD = new SaalutDataClasses1DataContext();
            }

            if ("AEP".Equals(destinationName))
            {
                var settingsSP = (from s in contextD.SettingsSAPERPTbls
                                  select s).FirstOrDefault();

                RfcConfigParameters parms = new RfcConfigParameters();
                parms.Add(RfcConfigParameters.Name, settingsSP.SystemID);
                parms.Add(RfcConfigParameters.AppServerHost, settingsSP.MessageServerHost);
                if (settingsSP.LogonGroup != null || settingsSP.LogonGroup != "")
                {
                    parms.Add(RfcConfigParameters.LogonGroup, settingsSP.LogonGroup);
                }
                parms.Add(RfcConfigParameters.SystemID, settingsSP.SystemID);
                parms.Add(RfcConfigParameters.SystemNumber, settingsSP.SystemNumber);
                if (settingsSP.SAPRouter != null || settingsSP.SAPRouter != "")
                {
                    parms.Add(RfcConfigParameters.SAPRouter, settingsSP.SAPRouter);
                }
                parms.Add(RfcConfigParameters.User, settingsSP.SAPUser);
                parms.Add(RfcConfigParameters.Password, settingsSP.SAPPassword);
                parms.Add(RfcConfigParameters.Client, settingsSP.Client);
                parms.Add(RfcConfigParameters.Language, "en");
                parms.Add(RfcConfigParameters.PoolSize, "5");
                parms.Add(RfcConfigParameters.MaxPoolSize, "10");
                parms.Add(RfcConfigParameters.IdleTimeout, "600");
                return(parms);
            }
            else
            {
                return(null);
            }
        }
Exemple #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            context = new SaalutDataClasses1DataContext();

            if (Request.QueryString["GID"] == null)
            {
                //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                Response.Redirect("TermoTickets.aspx");
            }


            Int32.TryParse(Request.QueryString["GID"], out goodID);
            Int32.TryParse(Request.QueryString["TID"], out typeID);


            if (goodID == 0)
            {
                //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                Response.Redirect("TermoTickets.aspx");
            }

            //------

            Image img = new Image();

            if (typeID == 0)
            {
                img.ImageUrl = "Services/TermoLabelImage.ashx?GID=" + goodID.ToString();
            }
            else
            {
                img.ImageUrl = "Services/TermoLabelProizvodstvo.ashx?GID=" + goodID.ToString();
            }

            CennicPlaceHolder1.Controls.Add(img);
        }
Exemple #14
0
        protected void GoodInfo(Good good)
        {
            string Division = WebConfigurationManager.AppSettings["Division"];


            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }

            var store = (from s in context.StoreInfos
                         select s).FirstOrDefault();

            OutInfoLiteral1.Text += "Артикул: " + good.Articul + ".<br />";
            OutInfoLiteral1.Text += "Наименование: " + good.Name + ".<br />";
            OutInfoLiteral1.Text += "Подробно: " + good.Descr + ".<br /><br />";

            if (good.PLU == 0)
            {
                OutInfoLiteral1.Text += "Нет PLU на указанный товар в УКМ.<br />";
            }
            else
            {
                OutInfoLiteral1.Text += "PLU: " + good.PLU + ".<br />";
            }


            OutInfoLiteral1.Text += "Ш/К: " + good.Barcode + ".<br />";

            // ищем цену

            // + цена по новому
            DataTable prices;

            MySqlConnection cnx = null;

            try
            {
                cnx = new MySqlConnection(connStr);
                MySqlDataAdapter adapter = new MySqlDataAdapter();

                // Prices
                string       cmdText = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ; select item, price, version, deleted from ukmserver.trm_in_pricelist_items where item = '" + good.Articul + "' and pricelist_id = '" + store.PriceList_ID_UKM.ToString() + "'  and deleted = 0; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ; ";
                MySqlCommand cmd     = new MySqlCommand(cmdText, cnx);
                cmd.CommandTimeout = 30000;

                // Create a fill a Dataset
                DataSet ds5 = new DataSet();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds5);

                prices = ds5.Tables[0];
            }
            catch (MySqlException ex)
            {
                return;
            }
            finally
            {
                if (cnx != null)
                {
                    cnx.Close();
                }
            }

            // - цена по новому


            string priceVal = "Нет цены на указанный товар в УКМ.<br />";
            //var price = (from p in dataContext.Prices
            //             where p.GoodID == good.ID
            //             && p.Active == true
            //             select p).FirstOrDefault();
            //if (price != null)
            //{
            //    double priceFromDB = price.Price1.Value;

            //    if (template.EdinicZa100Gr != null)
            //    {
            //        if (template.EdinicZa100Gr.Value)
            //        {
            //            priceFromDB = priceFromDB / 10;
            //        }
            //    }
            //    priceVal = priceFromDB.ToString();
            //}

            // + новая цена
            decimal price = 0;

            if (prices != null)
            {
                foreach (DataRow row in prices.Rows)
                {
                    price = (decimal)row[1];
                }
            }
            if (price != 0)
            {
                if (Division == "RF")
                {
                    string pricet = price.ToString();
                    pricet   = pricet.Substring(0, pricet.Length - 2);
                    priceVal = "Цена: " + pricet + "<br />";
                }
                else
                if (Division == "RB")
                {
                    string pricet = price.ToString();
                    pricet   = pricet.Substring(0, pricet.Length - 5);
                    priceVal = "Цена: " + pricet + "<br />";
                }
            }
            // - новая цена
            OutInfoLiteral1.Text += priceVal;

            if (good.DepartmentID == null)
            {
                OutInfoLiteral1.Text += "Не указан отдел на указанный товар в УКМ.<br />";
            }
            else
            {
                var weights = from w in context.WeightDeparts
                              where w.Active == true &&
                              w.DepartmentID == good.DepartmentID
                              select w;
                if (weights.Count() > 0)
                {
                    OutInfoLiteral1.Text += "Товар привязан к следующим весам:<br />";
                }
                else
                {
                    OutInfoLiteral1.Text += "Товар не имеет привязки к весам.<br />";
                }

                foreach (WeightDepart wt in weights)
                {
                    string weightName = "Весы №" + wt.Num + " ";
                    var    wds        = from w in context.WeightDeparts
                                        where w.Num == wt.Num &&
                                        w.Active == true
                                        select w;
                    foreach (WeightDepart wtd in wds)
                    {
                        var dept = (from d in context.Departments
                                    where d.ID == wtd.DepartmentID &&
                                    d.Active == true
                                    select d).FirstOrDefault();

                        if (dept == null)
                        {
                            continue;
                        }

                        weightName += dept.DepartName + " ";
                    }

                    OutInfoLiteral1.Text += weightName + "<br />";
                }
            }
        }
Exemple #15
0
        public void ProcessRequest(HttpContext context)
        {
            string Division = WebConfigurationManager.AppSettings["Division"];


            string journalLineID = (context.Request.QueryString["LID"]).ToUpper();
            string printTmplID   = (context.Request.QueryString["TID"]).ToUpper();

            string proizvoditel = (context.Request.QueryString["PID"]).ToUpper();

            SaalutDataClasses1DataContext dataContext = new SaalutDataClasses1DataContext();

            int jlID = 0;

            Int32.TryParse(journalLineID, out jlID);

            var jl = (from j in dataContext.PriceChangeLine
                      where j.ID == jlID
                      select j).FirstOrDefault();

            if (jl == null)
            {
                return;
            }

            var good = (from g in dataContext.Goods
                        where g.ID == jl.GoodID
                        select g).FirstOrDefault();

            if (good == null)
            {
                return;
            }

            // settings
            var settings = (from s in dataContext.Settings
                            select s).FirstOrDefault();

            var store = (from s in dataContext.StoreInfos
                         where s.Active == true
                         select s).FirstOrDefault();

            if (store == null)
            {
                return;
            }

            //+ 06052014
            var storeExt = (from s in dataContext.StoreInfoExt
                            select s).FirstOrDefault();
            //- 06052014

            int ptID = 0;

            Int32.TryParse(printTmplID, out ptID);

            //+07052014
            if (ptID == 0)
            {
                if (good.PrintTemplateID != null)
                {
                    ptID = good.PrintTemplateID.Value;
                }
            }
            //-07052014

            var pt = (from p in dataContext.PrintTemplates
                      where p.ID == ptID
                      select p).FirstOrDefault();

            if (pt == null)
            {
                // ищем шаблон на верхнем уровне.
                if (good.Group.PrintTemplateID == null)
                {
                    int upGroupID = 0;
                    if (good.Group.GroupRangeID != 0 && good.Group.GroupRangeID != null)
                    {
                        upGroupID = good.Group.GroupRangeID.Value;
                    }
                    while (upGroupID != 0)
                    {
                        var grp = (from g in dataContext.Groups
                                   where g.ID == upGroupID
                                   select g).FirstOrDefault();
                        if (grp == null)
                        {
                            continue;
                        }

                        if (grp.PrintTemplateID == null)
                        {
                            if (grp.GroupRangeID != 0 && grp.GroupRangeID != null)
                            {
                                upGroupID = grp.GroupRangeID.Value;
                                continue;
                            }
                            else
                            {
                                upGroupID = 0;
                            }
                        }
                        else
                        {
                            ptID = grp.PrintTemplateID.Value;
                            break;
                        }

                        if (good.Group.GroupRangeID != 0 && good.Group.GroupRangeID != null)
                        {
                            upGroupID = good.Group.GroupRangeID.Value;
                        }

                        if (grp.GroupRangeID == null)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    ptID = good.Group.PrintTemplateID.Value;
                }
            }

            // проверяем нашли ли шаблон
            if (ptID == 0)
            {
                return; // возврат если не нашли
            }
            var template = (from t in dataContext.PrintTemplates
                            where t.ID == ptID
                            select t).FirstOrDefault();

            if (template == null)
            {
                return;
            }

            //+ 06052014
            var templateExt = (from t in dataContext.PrintTemplatesExt
                               where t.PrintTemplateID == ptID
                               select t).FirstOrDefault();
            //- 06052014

            Unit a      = new Unit(template.ShirinaCennicaMM.Value, UnitTypes.Mm);
            int  wImage = Int32.Parse(Math.Round(a.To(UnitTypes.Px).Value, 0).ToString()); //длинна картинки
            Unit b      = new Unit(template.VisotaCennicaMM.Value, UnitTypes.Mm);
            int  hImage = Int32.Parse(Math.Round(b.To(UnitTypes.Px).Value, 0).ToString()); //длинна картинки

            int otstupKray = 1;                                                            //отсутуп от края справа и снизу (справа может быть в 2 раза больше)

            wImage = wImage * mapSize;                                                     // увеличим размерчик для улучшения качества
            hImage = hImage * mapSize;

            int wGraph = wImage - otstupKray;
            int hGraph = hImage - otstupKray;


            Bitmap image = new Bitmap(wImage, hImage);

            // Get the physical path of the current application.
            string appPath = HttpRuntime.AppDomainAppPath;
            // Get the complete physical path of the file to read.
            string file      = appPath + @"\" + template.FileName;
            Image  backImage = Image.FromFile(file);


            Graphics graf = Graphics.FromImage(image);

            graf.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

            //graf.SmoothingMode = SmoothingMode.None;
            //graf.InterpolationMode = InterpolationMode.Low;
            //graf.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.Default;
            //graf.PixelOffsetMode = PixelOffsetMode.None;

            SolidBrush whiteBrush = new SolidBrush(Color.White);
            SolidBrush blackBrush = new SolidBrush(Color.Black);


            graf.FillRectangle(blackBrush, 0, 0, wImage, hImage);
            if (template.TemplateName.Contains("акционный"))
            {
                graf.FillRectangle(whiteBrush, 0, 0, wImage, hImage);
            }
            else
            {
                graf.FillRectangle(whiteBrush, 1, 1, wImage - 2, hImage - 2);
            }


            // Информация ценника

            if (template.GoodNameFontWeight.Value != 0)
            {
                string        descr = good.Descr;
                StringBuilder str   = new StringBuilder();

                descr = descr.Replace("\r\n", "\n");
                descr = descr.Replace("\r", "\n");
                descr = descr.Replace("\t", " ");


                int length = descr.Length;
                int from   = 0;

                int strok = 3; //не более 3 строк в наименование
                while (length >= template.GoodNameSimvolovVStr)
                {
                    str.Append(descr.Substring(from, template.GoodNameSimvolovVStr.Value) + "\n");
                    from   += template.GoodNameSimvolovVStr.Value;
                    length -= template.GoodNameSimvolovVStr.Value;

                    if (strok == 1)
                    {
                        break;
                    }
                    strok--;
                }
                if (length < template.GoodNameSimvolovVStr)
                {
                    str.Append(descr.Substring(from, length));
                }

                string[] textParagraphs = str.ToString().Trim().Split('\n');


                Font fontGoodName = new Font(FontFamily.GenericSansSerif, template.GoodNameFontWeight.Value * mapSize, FontStyle.Bold);
                //Font fontGoodName = new Font("Arial", 96 / 8, FontStyle.Bold);
                int i = 0;
                foreach (string strText in textParagraphs.ToArray())
                {
                    using (StringFormat sf = new StringFormat())
                    {
                        if (template.GoodNameCentrovano == true)
                        {
                            sf.Alignment     = StringAlignment.Center;
                            sf.LineAlignment = StringAlignment.Center;
                        }
                        else
                        {
                            sf.Alignment     = StringAlignment.Near;
                            sf.LineAlignment = StringAlignment.Near;
                        }

                        sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
                        sf.FormatFlags  = StringFormatFlags.NoWrap;

                        int otstPx = 0;
                        if (i != 0)
                        {
                            Unit o = new Unit(template.GoodNameOtstupMM.Value, UnitTypes.Mm);
                            otstPx = Int32.Parse(Math.Round(o.To(UnitTypes.Px).Value, 0).ToString()); //длинна картинки
                        }
                        graf.DrawString(strText.Trim(), fontGoodName, blackBrush, template.GoodNameX.Value * mapSize, (template.GoodNameY.Value + (i * otstPx)) * mapSize, sf);
                    }
                    i++;
                }
            }


            // + цена по новому
            DataTable prices;

            MySqlConnection cnx = null;

            try
            {
                cnx = new MySqlConnection(connStr);
                MySqlDataAdapter adapter = new MySqlDataAdapter();

                // Prices
                string       cmdText = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ; select item, price, version, deleted from ukmserver.trm_in_pricelist_items where item = '" + good.Articul + "' and pricelist_id = '" + store.PriceList_ID_UKM.ToString() + "'  and deleted = 0; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ; ";
                MySqlCommand cmd     = new MySqlCommand(cmdText, cnx);
                cmd.CommandTimeout = 30000;

                // Create a fill a Dataset
                DataSet ds5 = new DataSet();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds5);

                prices = ds5.Tables[0];
            }
            catch (MySqlException ex)
            {
                return;
            }
            finally
            {
                if (cnx != null)
                {
                    cnx.Close();
                }
            }

            // - цена по новому


            string priceVal = "нет цены";
            //var price = (from p in dataContext.Prices
            //             where p.GoodID == good.ID
            //             && p.Active == true
            //             select p).FirstOrDefault();
            //if (price != null)
            //{
            //    double priceFromDB = price.Price1.Value;

            //    if (template.EdinicZa100Gr != null)
            //    {
            //        if (template.EdinicZa100Gr.Value)
            //        {
            //            priceFromDB = priceFromDB / 10;
            //        }
            //    }
            //    priceVal = priceFromDB.ToString();
            //}

            // + новая цена
            decimal price = 0;

            if (prices != null)
            {
                foreach (DataRow row in prices.Rows)
                {
                    price = (decimal)row[1];
                }
            }
            if (price != 0)
            {
                if (template.EdinicZa100Gr != null)
                {
                    if (template.EdinicZa100Gr.Value)
                    {
                        price = price / 10;
                    }
                }

                priceVal = price.ToString();
            }
            // - новая цена

            string priceRub = "0";
            string priceKop = "00";

            int priceValZap = priceVal.IndexOf(",");

            if (priceValZap != -1)
            {
                priceRub = priceVal.Substring(0, priceValZap);
                priceKop = priceVal.Substring(priceValZap + 1, priceVal.Length - priceValZap - 1);
            }
            else
            {
                priceValZap = priceVal.IndexOf(".");
                if (priceValZap != -1)
                {
                    priceRub = priceVal.Substring(0, priceValZap);
                    priceKop = priceVal.Substring(priceValZap + 1, priceVal.Length - priceValZap - 1);
                }
                else
                {
                    priceRub = priceVal;
                }
            }

            if (priceKop.Length == 1)
            {
                priceKop += "0";
            }

            if (priceKop.Length >= 3)
            {
                priceKop = priceKop.Substring(0, 2);
            }

            if (price != 0)
            {
                int iPriceRub = Int32.Parse(priceRub);
                priceRub = iPriceRub.ToString("N0", CultureInfo.CreateSpecificCulture("ru-RU"));

                if (Division == "RF")
                {
                    if (template.PriceRubFromRightToLeft == false)
                    {
                        if (priceRub.Length == 1)
                        {
                            priceRub = "   " + priceRub;
                        }
                        if (priceRub.Length == 2)
                        {
                            priceRub = "  " + priceRub;
                        }
                        if (priceRub.Length == 3)
                        {
                            priceRub = " " + priceRub;
                        }
                    }
                    else
                    {
                        if (priceRub.Length == 1)
                        {
                            priceRub = "     " + priceRub;
                        }
                        if (priceRub.Length == 2)
                        {
                            priceRub = "    " + priceRub;
                        }
                        if (priceRub.Length == 3)
                        {
                            priceRub = "  " + priceRub;
                        }
                        if (priceRub.Length == 4)
                        {
                            priceRub = " " + priceRub;
                        }
                    }
                }
                else
                if (Division == "RB")
                {
                    if (priceRub.Length == 2)
                    {
                        priceRub = "      " + priceRub;
                    }
                    if (priceRub.Length == 3)
                    {
                        priceRub = "     " + priceRub;
                    }
                    if (priceRub.Length == 4)
                    {
                        priceRub = "     " + priceRub;
                    }
                    if (priceRub.Length == 5)
                    {
                        priceRub = "    " + priceRub;
                    }
                    if (priceRub.Length == 6)
                    {
                        priceRub = "   " + priceRub;
                    }
                    if (priceRub.Length == 7)
                    {
                        priceRub = "  " + priceRub;
                    }
                }
            }

            if (template.PriceRubFontWeight.Value != 0)
            {
                Font fontPriceRub = new Font("Arial black", template.PriceRubFontWeight.Value * mapSize, FontStyle.Bold);
                //Font fontPriceRub = new Font("Arial black", 64, FontStyle.Bold);
                graf.DrawString(priceRub, fontPriceRub, blackBrush, template.PriceRubX.Value * mapSize, template.PriceRubY.Value * mapSize);
            }

            if (template.SlovoRubFontWeigh.Value != 0)
            {
                Font font = new Font(FontFamily.GenericSansSerif, template.SlovoRubFontWeigh.Value * mapSize, FontStyle.Regular);
                if (template.SlovoRubUnderline.Value == true)
                {
                    font = new Font(FontFamily.GenericSansSerif, template.SlovoRubFontWeigh.Value * mapSize, FontStyle.Underline);
                }
                graf.DrawString("РУБ", font, blackBrush, template.SlovoRubX.Value * mapSize, template.SlovoRubY.Value * mapSize);
            }

            if (template.PriceKopFontWeight.Value != 0 && Division != "RB")
            {
                Font fontPriceKop = new Font("Arial black", template.PriceKopFontWeight.Value * mapSize, FontStyle.Bold);
                graf.DrawString(priceKop, fontPriceKop, blackBrush, template.PriceKopX.Value * mapSize, template.PriceKopY.Value * mapSize);
            }

            if (template.SlovoKopFontWeight.Value != 0 && Division != "RB")
            {
                Font font = new Font(FontFamily.GenericSansSerif, template.SlovoKopFontWeight.Value * mapSize, FontStyle.Regular);
                if (template.SlovoKopUnderline.Value == true)
                {
                    font = new Font(FontFamily.GenericSansSerif, template.SlovoKopFontWeight.Value * mapSize, FontStyle.Underline);
                }
                graf.DrawString("КОП", font, blackBrush, template.SlovoKopX.Value * mapSize, template.SlovoKopY.Value * mapSize);
            }

            if (!template.EdinicZa100Gr.Value && template.EdinicFontWeight.Value != 0)
            {
                Font fontEdinic = new Font(FontFamily.GenericSansSerif, template.EdinicFontWeight.Value * mapSize, FontStyle.Regular);
                graf.DrawString("ед.изм.: " + good.Edinic, fontEdinic, blackBrush, template.EdinicX.Value * mapSize, template.EdinicY.Value * mapSize);
            }

            if (template.EdinicZa100Gr.Value && template.EdinicFontWeight.Value != 0)
            {
                Font fontEdinic = new Font(FontFamily.GenericSansSerif, template.EdinicFontWeight.Value * mapSize, FontStyle.Regular);
                graf.DrawString("Цена за 100 гр.", fontEdinic, blackBrush, template.EdinicX.Value * mapSize, template.EdinicY.Value * mapSize);
            }

            if (template.SostavFontWeight.Value != 0)
            {
                string Contents = good.Contents.Trim();

                if (Contents != "")
                {
                    if (Contents.Substring(0, 6).ToUpper() != "СОСТАВ")
                    {
                        Contents = "Состав: " + Contents;
                    }
                }

                StringBuilder str = new StringBuilder();

                Contents = Contents.Replace("\r\n", "\n");
                Contents = Contents.Replace("\r", "\n");
                Contents = Contents.Replace("\t", " ");


                int length = Contents.Length;
                int from   = 0;


                while (length >= template.SostavSimvolovVStr)
                {
                    str.Append(Contents.Substring(from, template.SostavSimvolovVStr.Value) + "\n");
                    from   += template.SostavSimvolovVStr.Value;
                    length -= template.SostavSimvolovVStr.Value;
                }
                if (length < template.SostavSimvolovVStr)
                {
                    str.Append(Contents.Substring(from, length));
                }

                string[] textParagraphs = str.ToString().Trim().Split('\n');


                Font fontSostav = new Font(FontFamily.GenericSansSerif, template.SostavFontWeight.Value * mapSize, FontStyle.Regular);

                int i = 0;
                foreach (string strText in textParagraphs.ToArray())
                {
                    using (StringFormat sf = new StringFormat())
                    {
                        sf.Alignment     = StringAlignment.Near;
                        sf.LineAlignment = StringAlignment.Near;
                        sf.HotkeyPrefix  = System.Drawing.Text.HotkeyPrefix.None;
                        sf.FormatFlags   = StringFormatFlags.NoWrap;

                        int otstPx = 0;
                        if (i != 0)
                        {
                            Unit o = new Unit(template.SostavOtstupMM.Value, UnitTypes.Mm);
                            otstPx = Int32.Parse(Math.Round(o.To(UnitTypes.Px).Value, 0).ToString()); //длинна картинки
                        }
                        graf.DrawString(strText.Trim(), fontSostav, blackBrush, template.SostavX.Value * mapSize, (template.SostavY.Value + (i * otstPx)) * mapSize);
                    }
                    i++;
                }
            }



            if (template.ProizvoditelFontWeight.Value != 0)
            {
                string contsts = good.Producer;
                if (contsts.Length > 0)
                {
                    contsts = contsts.Substring(0, 1).ToUpper() + contsts.Substring(1).ToLower();
                }
                contsts += " " + proizvoditel;
                Font fontProizvoditel = new Font(FontFamily.GenericSansSerif, template.ProizvoditelFontWeight.Value * mapSize, FontStyle.Regular);
                graf.DrawString((contsts).Trim(), fontProizvoditel, blackBrush, template.ProizvoditeX.Value * mapSize, template.ProizvoditeY.Value * mapSize);
            }

            if (template.MagazinFontWeight.Value != 0)
            {
                if (store != null)
                {
                    Font fontMagazin = new Font(FontFamily.GenericSansSerif, template.MagazinFontWeight.Value * mapSize, FontStyle.Regular);
                    graf.DrawString(store.StoreName.Trim(), fontMagazin, blackBrush, template.MagazinX.Value * mapSize, template.MagazinY.Value * mapSize);
                }
            }

            if (template.JurlicoFontWeight.Value != 0)
            {
                if (store != null)
                {
                    if (store.Company != null)
                    {
                        Font font = new Font(FontFamily.GenericSansSerif, template.JurlicoFontWeight.Value * mapSize, FontStyle.Regular);
                        graf.DrawString(store.Company.Trim(), font, blackBrush, template.JurlicoX.Value * mapSize, template.JurlicoY.Value * mapSize);
                    }
                }
            }

            if (template.FactAddressFontWeight.Value != 0)
            {
                if (store != null)
                {
                    if (store.AddressFact != null)
                    {
                        Font fontAddressFact = new Font(FontFamily.GenericSansSerif, template.FactAddressFontWeight.Value * mapSize, FontStyle.Regular);
                        graf.DrawString(store.AddressFact.Trim(), fontAddressFact, blackBrush, template.FactAddressX.Value * mapSize, template.FactAddressY.Value * mapSize);
                    }
                }
            }

            if (template.JurAddressFontWeight.Value != 0)
            {
                if (store != null)
                {
                    if (store.AddressJur != null)
                    {
                        Font fontAddressJur = new Font(FontFamily.GenericSansSerif, template.JurAddressFontWeight.Value * mapSize, FontStyle.Regular);
                        graf.DrawString(store.AddressJur.Trim(), fontAddressJur, blackBrush, template.JurAddressX.Value * mapSize, template.JurAddressY.Value * mapSize);
                    }
                }
            }

            if (template.DataFontWeight.Value != 0)
            {
                Font fontData = new Font(FontFamily.GenericSansSerif, template.DataFontWeight.Value * mapSize, FontStyle.Regular);
                graf.DrawString("Дата:" + DateTime.Today.ToString("dd.MM"), fontData, blackBrush, template.DataX.Value * mapSize, template.DataY.Value * mapSize);
            }


            //Image img = image.GetThumbnailImage(wImage / mapSize, hImage / mapSize, null, (new System.IntPtr(0)));


            if (template.BarcodeShirinaMM.Value != -1 && template.BarcodeVisotaMM.Value != -1)
            {
                Graphics graf2 = Graphics.FromImage(image);

                string barcode = good.Barcode;
                if (barcode == "" || barcode == "0" || barcode == null) // bug fix
                {
                    var barkodes_all = (from brk in dataContext.Barcodes
                                        where brk.GoodID == good.ID &&
                                        brk.Active == true
                                        select brk).FirstOrDefault();
                    if (barkodes_all != null)
                    {
                        barcode = barkodes_all.Barcode1;
                    }
                }

                //bug fix
                if (barcode == "" || barcode == "0" || barcode == null)
                {
                    UKMDataBaseConnects utl = new UKMDataBaseConnects();
                    utl.UpdateGood(good, good.Articul);
                    //2
                    utl.UpdateGood(good, good.Articul);
                }

                if (barcode.Length >= 13)
                {
                    barcode = barcode.Substring(0, 12);
                }

                if (barcode.Length < 12)
                {
                    int ii = 12 - barcode.Length;
                    for (int i = 1; i <= ii; i++)
                    {
                        barcode += "0";
                    }
                }

                BarcodeEAN13 encoderEAN13 = new BarcodeEAN13();
                Image        barcImg      = encoderEAN13.Encode(barcode);

                Rectangle nr = new Rectangle(0, barcImg.Height / 2, barcImg.Width, barcImg.Height / 3);

                if (settings != null)
                {
                    if (template.BarcodeShirinaMM.Value != 0 && template.BarcodeVisotaMM.Value != 0)
                    {
                        //if (settings.ResizeBarcodes.Value)
                        //{
                        Unit c   = new Unit(template.BarcodeShirinaMM.Value, UnitTypes.Mm);
                        int  wBC = Int32.Parse(Math.Round(c.To(UnitTypes.Px).Value, 0).ToString()); //длинна картинки
                        Unit d   = new Unit(template.BarcodeVisotaMM.Value, UnitTypes.Mm);
                        int  hBC = Int32.Parse(Math.Round(d.To(UnitTypes.Px).Value, 0).ToString()); //длинна картинки

                        graf2.DrawImage(this.ResizeImg(barcImg, wBC, hBC), new Point(template.BarcodeX.Value, template.BarcodeY.Value));
                    }
                    else
                    {
                        if (templateExt != null)
                        {
                            if (templateExt.MalenkiyBarcode.Value == true)
                            {
                                graf2.DrawImage(this.cropImage(barcImg, nr), new Point(template.BarcodeX.Value, template.BarcodeY.Value));
                            }
                            else
                            {
                                graf2.DrawImage(barcImg, new Point(template.BarcodeX.Value, template.BarcodeY.Value));
                            }
                        }
                        else
                        {
                            graf2.DrawImage(this.cropImage(barcImg, nr), new Point(template.BarcodeX.Value, template.BarcodeY.Value));
                        }
                    }
                }
                else
                {
                    graf2.DrawImage(barcImg, new Point(template.BarcodeX.Value, template.BarcodeY.Value));
                }
            }


            //+ 06052014 PrintTemplateExt
            decimal priceOld = 0;

            if (storeExt != null)
            {
                DataTable pricesOld;

                MySqlConnection cnxOld = null;
                try
                {
                    cnxOld = new MySqlConnection(connStr);
                    MySqlDataAdapter adapterOld = new MySqlDataAdapter();

                    // Prices
                    string       cmdText = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ; select item, price, version, deleted from ukmserver.trm_in_pricelist_items where item = '" + good.Articul + "' and pricelist_id = '" + storeExt.OsnPriceList_ID_UKM.ToString() + "'  and deleted = 0; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ; ";
                    MySqlCommand cmd     = new MySqlCommand(cmdText, cnxOld);
                    cmd.CommandTimeout = 30000;

                    // Create a fill a Dataset
                    DataSet ds5 = new DataSet();
                    adapterOld.SelectCommand = cmd;
                    adapterOld.Fill(ds5);

                    pricesOld = ds5.Tables[0];
                }
                catch (MySqlException ex)
                {
                    return;
                }
                finally
                {
                    if (cnxOld != null)
                    {
                        cnxOld.Close();
                    }
                }

                string priceValOld = "";
                //var price = (from p in dataContext.Prices
                //             where p.GoodID == good.ID
                //             && p.Active == true
                //             select p).FirstOrDefault();
                //if (price != null)
                //{
                //    double priceFromDB = price.Price1.Value;

                //    if (template.EdinicZa100Gr != null)
                //    {
                //        if (template.EdinicZa100Gr.Value)
                //        {
                //            priceFromDB = priceFromDB / 10;
                //        }
                //    }
                //    priceVal = priceFromDB.ToString();
                //}


                if (pricesOld != null)
                {
                    foreach (DataRow row in pricesOld.Rows)
                    {
                        priceOld = (decimal)row[1];
                    }
                }
                if (priceOld != 0)
                {
                    if (template.EdinicZa100Gr != null)
                    {
                        if (template.EdinicZa100Gr.Value)
                        {
                            priceOld = priceOld / 10;
                        }
                    }

                    priceValOld = priceOld.ToString();
                }


                string priceRubOld = "0";
                string priceKopOld = "00";

                int priceValZapOld = priceValOld.IndexOf(",");
                if (priceValZapOld != -1)
                {
                    priceRubOld = priceValOld.Substring(0, priceValZapOld);
                    priceKopOld = priceValOld.Substring(priceValZapOld + 1, priceValOld.Length - priceValZapOld - 1);
                }
                else
                {
                    priceValZapOld = priceValOld.IndexOf(".");
                    if (priceValZapOld != -1)
                    {
                        priceRubOld = priceValOld.Substring(0, priceValZapOld);
                        priceKopOld = priceValOld.Substring(priceValZapOld + 1, priceValOld.Length - priceValZapOld - 1);
                    }
                    else
                    {
                        priceRubOld = priceValOld;
                    }
                }

                if (priceKopOld.Length == 1)
                {
                    priceKopOld += "0";
                }

                if (priceKopOld.Length >= 3)
                {
                    priceKopOld = priceKopOld.Substring(0, 2);
                }

                if (priceOld != 0)
                {
                    int iPriceRubOld = Int32.Parse(priceRubOld);
                    priceRubOld = iPriceRubOld.ToString("N0", CultureInfo.CreateSpecificCulture("ru-RU"));

                    if (Division == "RF")
                    {
                        if (priceRubOld.Length == 1)
                        {
                            priceRubOld = "   " + priceRubOld;
                        }
                        if (priceRubOld.Length == 2)
                        {
                            priceRubOld = "  " + priceRubOld;
                        }
                        if (priceRubOld.Length == 3)
                        {
                            priceRubOld = " " + priceRubOld;
                        }
                    }
                    else
                    if (Division == "RB")
                    {
                        if (priceRubOld.Length == 2)
                        {
                            priceRubOld = "      " + priceRubOld;
                        }
                        if (priceRubOld.Length == 3)
                        {
                            priceRubOld = "     " + priceRubOld;
                        }
                        if (priceRubOld.Length == 4)
                        {
                            priceRubOld = "     " + priceRubOld;
                        }
                        if (priceRubOld.Length == 5)
                        {
                            priceRubOld = "    " + priceRubOld;
                        }
                        if (priceRubOld.Length == 6)
                        {
                            priceRubOld = "   " + priceRubOld;
                        }
                        if (priceRubOld.Length == 7)
                        {
                            priceRubOld = "  " + priceRubOld;
                        }
                    }
                }

                if (template.OldPriceRubFontWeight.Value != 0)
                {
                    Font fontPriceRub = new Font(FontFamily.GenericSansSerif, template.OldPriceRubFontWeight.Value * mapSize, FontStyle.Regular);
                    graf.DrawString(priceRubOld, fontPriceRub, blackBrush, template.OldPriceRubX.Value * mapSize, template.OldPriceRubY.Value * mapSize);
                }

                if (template.OldSlovoRubFontWeigh.Value != 0)
                {
                    Font font = new Font(FontFamily.GenericSansSerif, template.OldSlovoRubFontWeigh.Value * mapSize, FontStyle.Regular);
                    graf.DrawString("РУБ", font, blackBrush, template.OldSlovoRubX.Value * mapSize, template.OldSlovoRubY.Value * mapSize);
                }

                if (template.OldPriceKopFontWeight.Value != 0 && Division != "RB")
                {
                    Font fontPriceKop = new Font(FontFamily.GenericSansSerif, template.OldPriceKopFontWeight.Value * mapSize, FontStyle.Regular);
                    graf.DrawString(priceKopOld, fontPriceKop, blackBrush, template.OldPriceKopX.Value * mapSize, template.OldPriceKopY.Value * mapSize);
                }

                if (template.OldSlovoKopFontWeight.Value != 0 && Division != "RB")
                {
                    Font font = new Font(FontFamily.GenericSansSerif, template.OldSlovoKopFontWeight.Value * mapSize, FontStyle.Regular);

                    graf.DrawString("КОП", font, blackBrush, template.OldSlovoKopX.Value * mapSize, template.OldSlovoKopY.Value * mapSize);
                }
            }

            if (templateExt != null)
            {
                if (templateExt.SlovoCenaFontWeight.Value != 0)
                {
                    Font fontData = new Font(FontFamily.GenericSansSerif, templateExt.SlovoCenaFontWeight.Value * mapSize, FontStyle.Regular);
                    graf.DrawString(templateExt.SlovoCena, fontData, blackBrush, templateExt.SlovoCenaX.Value * mapSize, templateExt.SlovoCenaY.Value * mapSize);
                }
                if (templateExt.DopTextFontWeight.Value != 0)
                {
                    double priceOldD = Double.Parse(priceOld.ToString());
                    double priceD    = Double.Parse(price.ToString());

                    double percentDec = (priceOldD - priceD) / priceOldD * 100;
                    percentDec = Math.Round(percentDec);

                    Font fontData = new Font(FontFamily.GenericSansSerif, templateExt.DopTextFontWeight.Value * mapSize, FontStyle.Bold);
                    graf.DrawString(templateExt.DopText + " " + percentDec.ToString() + "%", fontData, blackBrush, templateExt.DopTextX.Value * mapSize, templateExt.DopTextY.Value * mapSize);
                }
                if (templateExt.SlovoObichCenaFontWeight.Value != 0)
                {
                    Font fontData = new Font(FontFamily.GenericSansSerif, templateExt.SlovoObichCenaFontWeight.Value * mapSize, FontStyle.Regular);
                    graf.DrawString(templateExt.SlovoObichCena, fontData, blackBrush, templateExt.SlovoObichCenaX.Value * mapSize, templateExt.SlovoObichCenaY.Value * mapSize);
                }
            }
            //- 06052014


            MemoryStream memStream = new MemoryStream();

            context.Response.ContentType = "image/png";
            image.Save(memStream, ImageFormat.Png);

            memStream.WriteTo(context.Response.OutputStream);


            graf.Dispose();
            image.Dispose();
            backImage.Dispose();
        }
Exemple #16
0
        protected void PrintRightNow_Click2(object sender, EventArgs e)
        {
            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }

            var setting = (from s in context.Settings
                           select s).FirstOrDefault();

            if (setting.MobileTermoPrinterNetPath == null || setting.MobileTermoPrinterNetPath == "")
            {
                PriceLabel1.Text = "Нет настроек печати!";
                return;
            }

            var template = (from t in context.TermoCennic
                            where t.Active == true
                            select t).FirstOrDefault();

            if (template == null)
            {
                PriceLabel1.Text = "Нет шаблона печати!";
                return;
            }



            var store = (from s in context.StoreInfos
                         where s.Active == true
                         select s).FirstOrDefault();

            string barcodeText = BarcodeTextBox1.Text.Trim();

            var barcode = (from p in context.Barcodes
                           where p.Barcode1 == barcodeText &&
                           p.Active == true    // bug fix barkode
                           select p).FirstOrDefault();

            if (barcode == null)
            {
                PriceLabel1.Text = "Ш/К не найден.";
                return;
            }

            var lineCheck = (from l in context.PriceChangeLine
                             where l.JournalID == jourID &&
                             l.GoodID == barcode.GoodID
                             select l).FirstOrDefault();

            if (lineCheck == null)
            {
                PriceChangeLine nl = new PriceChangeLine();
                nl.GoodID     = barcode.GoodID;
                nl.JournalID  = jourID;
                nl.ItemID_UKM = barcode.Good.Articul;

                nl.Active    = true;
                nl.TimeStamp = DateTime.Now;
                nl.Akcionniy = false;
                context.PriceChangeLine.InsertOnSubmit(nl);
            }

            TermoCennicQuoue cq = new TermoCennicQuoue();

            cq.JournalID     = jourID;
            cq.GoodID        = barcode.GoodID;
            cq.TermoCennicID = template.ID;
            cq.TimeStamp     = DateTime.Now;
            cq.Active        = true;
            context.TermoCennicQuoue.InsertOnSubmit(cq);


            context.SubmitChanges();

            PriceLabel1.Text     = "";
            BarcodeTextBox1.Text = "";


            PrintRightNow.Enabled = false;
            //PrintRightNow2.Enabled = false;
            AddToJournalButton1.Focus();

            PriceLabel1.Text = "Отправлено на печать!";
        }
Exemple #17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Dictionary <int, int> groupTemlates = new Dictionary <int, int>();


                context = new SaalutDataClasses1DataContext();

                if (Request.QueryString["ID"] == null)
                {
                    //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                    Response.Redirect("ByFind.aspx");
                }

                Int32.TryParse(Request.QueryString["ID"], out jourID);

                if (jourID == 0)
                {
                    //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                    Response.Redirect("ByFind.aspx");
                }


                if (Request.QueryString["WP"] != null)
                {
                    int tmpI = 0;
                    Int32.TryParse(Request.QueryString["WP"], out jourID);
                    if (tmpI == 1)
                    {
                        WhithoutPrice = true;
                    }
                }


                if (Request.QueryString["q"] != null)
                {
                    Int32.TryParse(Request.QueryString["q"], out qty);
                }

                if (Request.QueryString["f"] != null)
                {
                    Int32.TryParse(Request.QueryString["f"], out termPrinterID);
                }

                //if (Session["JourCart"] == null)
                //    //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                //    Response.Redirect("NewJours.aspx");

                if (termPrinterID == 0)
                {
                    // Ищем термо ценник для печати на принтере
                    var termCennic = (from c in context.ThermoLabels
                                      where c.FileLabelName.EndsWith(".slb")
                                      select c).FirstOrDefault();
                    if (termCennic == null)
                    {
                        Response.Redirect("ByFind.aspx");
                    }

                    var termPrnt = (from t in context.TermoPrinters
                                    where t.TermoPrinterPort == "lpt4"
                                    select t).FirstOrDefault();
                    if (termPrnt == null)
                    {
                        Response.Redirect("ByFind.aspx");
                    }

                    string dateForLabel = DateTime.Today.ToString("d");

                    var jLines = from j in context.PriceChangeLine
                                 where j.JournalID == jourID
                                 select j;
                    foreach (PriceChangeLine ln in jLines)
                    {
                        if (WhithoutPrice == true)
                        {
                            var prs = (from p in context.Prices
                                       where p.GoodID == ln.GoodID &&
                                       p.Active == true
                                       select p).FirstOrDefault();
                            if (prs == null)
                            {
                                continue;
                            }
                        }

                        TermLabelUtils utl = new TermLabelUtils();

                        JourCart cart = (JourCart)Session["JourCart"];
                        foreach (JourCartItem items in cart)
                        {
                            if (items.JourLineID == ln.ID)
                            {
                                string            proizvoditel = "";
                                PrintTemplateCart templCart    = (PrintTemplateCart)Session["PrintTemplateCart"];
                                foreach (PrintTemplateCartItem itemTempl in templCart)
                                {
                                    if (itemTempl.JourLineID == ln.ID)
                                    {
                                        proizvoditel = itemTempl.Proizvoditel;
                                        break;
                                    }
                                }

                                // входит в список распечатки.
                                int n = 0;
                                while (n < qty)
                                {
                                    utl.PrintTermoCennic(ln.GoodID.Value, termCennic.ID, 1, termPrnt.ID, dateForLabel, proizvoditel);
                                    n++;
                                }

                                break;
                            }
                        }
                    }
                }
                else // большой ценник
                {
                    // Ищем термо ценник для печати на принтере
                    var termCennic2 = (from c in context.ThermoLabels
                                       where c.FileLabelName.EndsWith(".blb") &&
                                       c.Active == true
                                       select c).FirstOrDefault();
                    var termCennic1 = (from c in context.ThermoLabels
                                       where c.FileLabelName.EndsWith(".slb") &&
                                       c.Active == true
                                       select c).FirstOrDefault();

                    var termPrnt = (from t in context.TermoPrinters
                                    where t.ID == termPrinterID &&
                                    t.Active == true
                                    select t).FirstOrDefault();
                    if (termPrnt == null)
                    {
                        Response.Redirect("ByFind.aspx");
                    }

                    string dateForLabel = DateTime.Today.ToString("d");

                    var jLines = from j in context.PriceChangeLine
                                 where j.JournalID == jourID
                                 select j;
                    foreach (PriceChangeLine ln in jLines)
                    {
                        if (WhithoutPrice == true)
                        {
                            var prs = (from p in context.Prices
                                       where p.GoodID == ln.GoodID &&
                                       p.Active == true
                                       select p).FirstOrDefault();
                            if (prs == null)
                            {
                                continue;
                            }
                        }

                        TermLabelUtils utl = new TermLabelUtils();

                        JourCart cart = (JourCart)Session["JourCart"];
                        foreach (JourCartItem items in cart)
                        {
                            if (items.JourLineID == ln.ID)
                            {
                                string            proizvoditel = "";
                                PrintTemplateCart templCart    = (PrintTemplateCart)Session["PrintTemplateCart"];
                                foreach (PrintTemplateCartItem itemTempl in templCart)
                                {
                                    if (itemTempl.JourLineID == ln.ID)
                                    {
                                        proizvoditel = itemTempl.Proizvoditel;
                                        break;
                                    }
                                }


                                // входит в список распечатки.
                                int n = 0;
                                while (n < qty)
                                {
                                    if (termPrnt.TermoPrinterPort == "lpt4")
                                    {
                                        utl.PrintTermoCennic(ln.GoodID.Value, termCennic1.ID, 1, termPrinterID, dateForLabel, proizvoditel);
                                    }
                                    else
                                    if (termPrnt.TermoPrinterPort == "lpt8")
                                    {
                                        utl.PrintTermoCennic(ln.GoodID.Value, termCennic2.ID, 1, termPrinterID, dateForLabel, proizvoditel);
                                    }
                                    n++;
                                }

                                break;
                            }
                        }
                    }
                } // большой ценник
            }
        }
        public void PrintAllQuoue()
        {
            // Get the physical path of the current application.
            string appPath         = HttpRuntime.AppDomainAppPath;
            string termLabelFolder = appPath + @"TRMLabels\";
            string termLabelExport = appPath + @"TRMExportCennic\";


            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }


            var store = (from s in context.StoreInfos
                         where s.Active == true
                         select s).FirstOrDefault();


            var setting = (from s in context.Settings
                           select s).FirstOrDefault();

            var cfps = (from c in context.TermoCennicQuoue
                        where c.Active == true &&
                        c.TimeStamp >= DateTime.Now.AddHours(-3)
                        select c);

            foreach (TermoCennicQuoue q in cfps)
            {
                var priceChangeJour = (from p in context.PriceChangeJours
                                       where p.ID == q.JournalID
                                       select p).FirstOrDefault();


                //Encoding enc = Encoding.GetEncoding(866);
                Encoding enc = Encoding.GetEncoding(1251);
                //Encoding enc = Encoding.GetEncoding(850);

                string filePath    = termLabelFolder + q.TermoCennic.FileLabelName;
                string toFileName  = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK").Replace(".", "").Replace(" ", "").Replace(":", "").Replace("-", "").Replace("T", "").Replace("+", "") + "_" + q.TermoCennic.FileLabelName;
                string toFilePath  = termLabelExport + toFileName;
                string batFilePath = termLabelExport + DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK").Replace(".", "").Replace(" ", "").Replace(":", "").Replace("-", "").Replace("T", "").Replace("+", "") + ".bat";



                // + цена по новому
                DataTable prices;

                MySqlConnection cnx = null;
                try
                {
                    cnx = new MySqlConnection(connStr);
                    MySqlDataAdapter adapter = new MySqlDataAdapter();

                    // Prices
                    string       cmdText = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ; select item, price, version, deleted from ukmserver.trm_in_pricelist_items where item = '" + q.Good.Articul + "' and pricelist_id = '" + store.PriceList_ID_UKM.ToString() + "'  and deleted = 0; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ; ";
                    MySqlCommand cmd     = new MySqlCommand(cmdText, cnx);
                    cmd.CommandTimeout = 30000;

                    // Create a fill a Dataset
                    DataSet ds5 = new DataSet();
                    adapter.SelectCommand = cmd;
                    adapter.Fill(ds5);

                    prices = ds5.Tables[0];
                }
                catch (MySqlException ex)
                {
                    return;
                }
                finally
                {
                    if (cnx != null)
                    {
                        cnx.Close();
                    }
                }

                // - цена по новому


                //var price = (from p in context.Prices
                //             where p.GoodID == good.ID
                //             && p.Active == true
                //             select p).FirstOrDefault();

                string priceVal = "нет цены";
                //var price = (from p in dataContext.Prices
                //             where p.GoodID == good.ID
                //             && p.Active == true
                //             select p).FirstOrDefault();
                //if (price != null)
                //{
                //    double priceFromDB = price.Price1.Value;

                //    if (template.EdinicZa100Gr != null)
                //    {
                //        if (template.EdinicZa100Gr.Value)
                //        {
                //            priceFromDB = priceFromDB / 10;
                //        }
                //    }
                //    priceVal = priceFromDB.ToString();
                //}

                // + новая цена
                decimal price = 0;
                if (prices != null)
                {
                    foreach (DataRow row in prices.Rows)
                    {
                        price = (decimal)row[1];
                    }
                }
                if (price != 0)
                {
                    priceVal = price.ToString();
                    if (Division == "RB")
                    {
                        int priceValZap = priceVal.IndexOf(",");
                        if (priceValZap != -1)
                        {
                            priceVal = priceVal.Substring(0, priceValZap);
                        }
                    }
                    else
                    if (Division == "RF")
                    {
                        int priceValZap = priceVal.IndexOf(",");
                        if (priceValZap != -1)
                        {
                            if ((priceValZap + 3) < priceVal.Length)
                            {
                                priceVal = priceVal.Substring(0, priceValZap + 3);
                            }
                        }
                    }
                }
                // - новая цена


                StringBuilder str = new StringBuilder();

                try
                {
                    using (StreamReader sr = new StreamReader(filePath, enc))
                    {
                        while (sr.Peek() >= 0)
                        {
                            string toStr = "";

                            toStr = sr.ReadLine();

                            // + goodName
                            if (toStr.Contains("%goodname"))
                            {
                                string        descr   = q.Good.Name;
                                StringBuilder strName = new StringBuilder();

                                descr = descr.Replace("\r\n", "\n");
                                descr = descr.Replace("\r", "\n");
                                descr = descr.Replace("\t", " ");

                                int length = descr.Length;
                                int from   = 0;

                                while (length >= q.TermoCennic.GoodNameVStroke) //количество символов в строке
                                {
                                    strName.Append(descr.Substring(from, q.TermoCennic.GoodNameVStroke.Value) + "\n");
                                    from   += q.TermoCennic.GoodNameVStroke.Value;
                                    length -= q.TermoCennic.GoodNameVStroke.Value;
                                }
                                if (length < q.TermoCennic.GoodNameVStroke.Value)
                                {
                                    strName.Append(descr.Substring(from, length));
                                }

                                string[] textParagraphs = strName.ToString().Split('\n');
                                int      i = 1;
                                foreach (string strText in textParagraphs.ToArray())
                                {
                                    using (StringFormat sf = new StringFormat())
                                    {
                                        //sf.Alignment = StringAlignment.Near;
                                        //sf.LineAlignment = StringAlignment.Near;
                                        //sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
                                        sf.FormatFlags = StringFormatFlags.NoWrap;

                                        toStr = toStr.Replace("%goodname" + i.ToString() + "%", strText.Trim());
                                    }
                                    i++;
                                }

                                if (toStr.Contains("%goodname"))
                                {
                                    toStr = toStr.Substring(0, toStr.IndexOf("%"));
                                }
                            }
                            // - goodName

                            // + goodContents
                            if (toStr.Contains("%contents") && q.Good.Contents != null)
                            {
                                string        descr   = q.Good.Contents;
                                StringBuilder strName = new StringBuilder();

                                descr = descr.Replace("\r\n", "\n");
                                descr = descr.Replace("\r", "\n");
                                descr = descr.Replace("\t", " ");

                                int length = descr.Length;
                                int from   = 0;

                                while (length >= q.TermoCennic.ContentsVStroke) //количество символов в строке
                                {
                                    strName.Append(descr.Substring(from, q.TermoCennic.ContentsVStroke.Value) + "\n");
                                    from   += q.TermoCennic.ContentsVStroke.Value;
                                    length -= q.TermoCennic.ContentsVStroke.Value;
                                }
                                if (length < q.TermoCennic.ContentsVStroke.Value)
                                {
                                    strName.Append(descr.Substring(from, length));
                                }

                                string[] textParagraphs = strName.ToString().Split('\n');
                                int      i = 1;
                                foreach (string strText in textParagraphs.ToArray())
                                {
                                    using (StringFormat sf = new StringFormat())
                                    {
                                        //sf.Alignment = StringAlignment.Near;
                                        //sf.LineAlignment = StringAlignment.Near;
                                        //sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
                                        sf.FormatFlags = StringFormatFlags.NoWrap;

                                        toStr = toStr.Replace("%contents" + i.ToString() + "%", strText.Trim());
                                    }
                                    i++;
                                }

                                if (toStr.Contains("%contents"))
                                {
                                    toStr = toStr.Substring(0, toStr.IndexOf("%"));
                                }
                            }
                            // - goodContents

                            toStr = toStr.Replace("%docdate%", DateTime.Now.ToString("dd.MM.yyyy"));
                            toStr = toStr.Replace("%article%", q.Good.Articul);
                            toStr = toStr.Replace("%barcode%", q.Good.Barcode);
                            toStr = toStr.Replace("%edinica%", q.Good.Edinic);
                            toStr = toStr.Replace("%producer%", q.Good.Producer + " " + q.Good.Country);

                            toStr = toStr.Replace("%company%", store.Company.ToString());
                            toStr = toStr.Replace("%address%", store.AddressFact.ToString());


                            string priceRub = "";
                            string priceKop = "";
                            if (Division == "RF")
                            {
                                int priceValZap = priceVal.IndexOf(",");
                                if (priceValZap != -1)
                                {
                                    priceRub = priceVal.Substring(0, priceValZap);
                                    if ((priceValZap + 3) <= priceVal.Length)
                                    {
                                        priceKop = priceVal.Substring(priceValZap + 1, 2);
                                    }
                                }
                                else
                                {
                                    priceValZap = priceVal.IndexOf(".");
                                    if (priceValZap != -1)
                                    {
                                        priceRub = priceVal.Substring(0, priceValZap);
                                        if ((priceValZap + 3) <= priceVal.Length)
                                        {
                                            priceKop = priceVal.Substring(priceValZap + 1, 2);
                                        }
                                    }
                                }
                            }


                            toStr = toStr.Replace("%pricerub%", priceRub);
                            toStr = toStr.Replace("%pricekop%", priceKop);



                            str.AppendLine(toStr);
                        }
                    }

                    string[] textParagraphsExport = str.ToString().Split('\n');

                    using (StreamWriter sr = new StreamWriter(toFilePath, false, enc, 512))
                    {
                        foreach (string strText in textParagraphsExport.ToArray())
                        {
                            using (StringFormat sf = new StringFormat())
                            {
                                //sf.Alignment = StringAlignment.Near;
                                //sf.LineAlignment = StringAlignment.Near;
                                //sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
                                sf.FormatFlags = StringFormatFlags.NoWrap;

                                sr.WriteLine(strText.Trim());
                            }
                        }

                        sr.Flush();
                        sr.Close();
                    }

                    // + bat file
                    using (StreamWriter sr = new StreamWriter(batFilePath, false, enc, 512))
                    {
                        if (priceChangeJour != null)
                        {
                            if (priceChangeJour.Order_no > 0)
                            {
                                var mobPr = (from m in context.MobileTermoPrinters
                                             where m.Num == priceChangeJour.Order_no
                                             select m).FirstOrDefault();
                                if (mobPr != null)
                                {
                                    sr.WriteLine(@"cd " + termLabelExport);
                                    sr.WriteLine(@"copy " + toFileName + " " + mobPr.NetPath + " /b");
                                }
                                else
                                {
                                    sr.WriteLine(@"cd " + termLabelExport);
                                    sr.WriteLine(@"copy " + toFileName + " " + setting.MobileTermoPrinterNetPath + " /b");
                                }
                            }
                            else
                            {
                                sr.WriteLine(@"cd " + termLabelExport);
                                sr.WriteLine(@"copy " + toFileName + " " + setting.MobileTermoPrinterNetPath + " /b");
                            }
                        }
                        else
                        {
                            sr.WriteLine(@"cd " + termLabelExport);
                            sr.WriteLine(@"copy " + toFileName + " " + setting.MobileTermoPrinterNetPath + " /b");
                        }


                        sr.Flush();
                        sr.Close();

                        //System.Diagnostics.Process proc = new System.Diagnostics.Process();
                        //proc.StartInfo.FileName = batFilePath;
                        //proc.StartInfo.RedirectStandardError = false;
                        //proc.StartInfo.RedirectStandardOutput = false;
                        //proc.StartInfo.UseShellExecute = false;
                        //proc.Start();
                        //proc.WaitForExit();

                        //Process proc = Process.Start("cmd.exe", @"/C " + batFilePath);
                    }
                    // - bat file


                    //if (File.Exists(toFilePath))
                    //    File.Delete(toFilePath);
                    //if (File.Exists(batFilePath))
                    //    File.Delete(batFilePath);
                }
                catch (Exception e)
                {
                    return;
                }


                q.Active = false;
                context.SubmitChanges();
            }

            ExecPrinting();
        }
        public string NewJourPrice_load()
        {
            string ret             = "";
            int    newPriceCounter = 0;

            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }

            // Del
            var ukmprices = from p in context.UKMPriceTbls
                            select p;

            context.UKMPriceTbls.DeleteAllOnSubmit(ukmprices);
            context.SubmitChanges();
            //-


            var store = (from s in context.StoreInfos
                         where s.Active == true
                         select s).FirstOrDefault();

            // + цена по новому
            DataTable prices;

            MySqlConnection cnx = null;

            try
            {
                cnx = new MySqlConnection(connStr);
                MySqlDataAdapter adapter = new MySqlDataAdapter();



                // Prices
                string       cmdText = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ; select item, price, version, deleted from ukmserver.trm_in_pricelist_items where pricelist_id = '" + store.PriceList_ID_UKM.ToString() + "'  and deleted = 0; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ; ";
                MySqlCommand cmd     = new MySqlCommand(cmdText, cnx);
                cmd.CommandTimeout = 30000;

                // Create a fill a Dataset
                DataSet ds5 = new DataSet();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds5);

                prices = ds5.Tables[0];

                if (prices != null)
                {
                    int y = 0;
                    foreach (DataRow row in prices.Rows)
                    {
                        string  artikul       = (string)row[0];
                        decimal price         = (decimal)row[1];
                        int     version_price = (int)row[2];
                        bool    delete_price  = (bool)row[3];


                        double newPrice = Double.Parse(price.ToString());


                        DateTime now = DateTime.Now;

                        // Price tbl
                        UKMPriceTbl npr = new UKMPriceTbl();
                        npr.Artikul   = artikul;
                        npr.PriceUKM  = newPrice;
                        npr.Version   = version_price;
                        npr.TimeStamp = now;
                        context.UKMPriceTbls.InsertOnSubmit(npr);
                        if (y == 100)
                        {
                            y = 0;
                            context.SubmitChanges();
                        }

                        newPriceCounter++;
                    }
                    context.SubmitChanges();
                }
                else
                {
                    return(ret += "Нет цен. Повторите позднее... ");
                }

                if (newPriceCounter != 0)
                {
                    ret += "Загружено из УКМ данных с количеством строк " + newPriceCounter.ToString() + ". ";
                }
            }
            catch (MySqlException ex)
            {
                return(ex.Message);
            }
            finally
            {
                if (cnx != null)
                {
                    cnx.Close();
                }
            }
            // - цена по новому


            return(ret);
        }
        public void ProcessRequest(HttpContext context)
        {
            string goodID = (context.Request.QueryString["GID"]).ToUpper();

            SaalutDataClasses1DataContext dataContext = new SaalutDataClasses1DataContext();

            int gID = 0;

            Int32.TryParse(goodID, out gID);


            var good = (from g in dataContext.Goods
                        where g.ID == gID
                        select g).FirstOrDefault();

            if (good == null)
            {
                return;
            }

            // settings
            var settings = (from s in dataContext.Settings
                            select s).FirstOrDefault();


            Unit a      = new Unit(settings.PrintTermoLabelShirinaMM.Value, UnitTypes.Mm);
            int  wImage = Int32.Parse(Math.Round(a.To(UnitTypes.Px).Value, 0).ToString()); //длинна картинки
            Unit b      = new Unit(settings.PrintTermoLabelVisotaMM.Value, UnitTypes.Mm);
            int  hImage = Int32.Parse(Math.Round(b.To(UnitTypes.Px).Value, 0).ToString()); //длинна картинки


            wImage = wImage * mapSize; // увеличим размерчик для улучшения качества
            hImage = hImage * mapSize;

            Bitmap   image = new Bitmap(wImage, hImage);
            Graphics graf  = Graphics.FromImage(image);

            SolidBrush whiteBrush = new SolidBrush(Color.White);
            SolidBrush blackBrush = new SolidBrush(Color.Black);

            graf.FillRectangle(whiteBrush, 0, 0, wImage, hImage);


            // Информация этикетки

            string        descr = good.Name + " Арт.:" + good.Articul;
            StringBuilder str   = new StringBuilder();

            descr = descr.Replace("\r\n", "\n");
            descr = descr.Replace("\r", "\n");
            descr = descr.Replace("\t", " ");

            int length = descr.Length;
            int from   = 0;

            while (length >= SimvolovVStroke) //количество символов в строке
            {
                str.Append(descr.Substring(from, SimvolovVStroke) + "\n");
                from   += SimvolovVStroke;
                length -= SimvolovVStroke;
            }
            if (length < SimvolovVStroke)
            {
                str.Append(descr.Substring(from, length));
            }

            string[] textParagraphs = str.ToString().Split('\n');


            Font fontGoodName = new Font(FontFamily.GenericSansSerif, fontWeight * mapSize, FontStyle.Regular);
            int  i            = 0;

            foreach (string strText in textParagraphs.ToArray())
            {
                using (StringFormat sf = new StringFormat())
                {
                    sf.Alignment     = StringAlignment.Near;
                    sf.LineAlignment = StringAlignment.Near;
                    sf.HotkeyPrefix  = System.Drawing.Text.HotkeyPrefix.None;
                    sf.FormatFlags   = StringFormatFlags.NoWrap;

                    int otstPx = 0;
                    if (i != 0)
                    {
                        Unit o = new Unit(otstupVMM, UnitTypes.Mm);
                        otstPx = Int32.Parse(Math.Round(o.To(UnitTypes.Px).Value, 0).ToString()); //длинна картинки
                    }
                    graf.DrawString(strText.Trim(), fontGoodName, blackBrush, GoodNameX * mapSize, (GoodNameY + (i * otstPx)) * mapSize, sf);
                }
                i++;
            }

            if (settings.PrintTermoLabelPrice.Value)
            {
                string priceVal = "нет цены";
                var    price    = (from p in dataContext.Prices
                                   where p.GoodID == good.ID &&
                                   p.Active == true
                                   select p).FirstOrDefault();
                if (price != null)
                {
                    priceVal = price.Price1.Value.ToString();
                }


                Font fontPriceRub = new Font(FontFamily.GenericSansSerif, fontWeight * mapSize, FontStyle.Regular);
                graf.DrawString(priceVal + " руб.", fontPriceRub, blackBrush, PriceRubX * mapSize, PriceRubY * mapSize);
            }

            //---


            Image img = image.GetThumbnailImage(wImage / mapSize, hImage / mapSize, null, (new System.IntPtr(0)));

            Graphics graf2 = Graphics.FromImage(img);

            string barcode = good.Barcode;

            if (barcode.Length == 13)
            {
                barcode = barcode.Substring(0, 12);
            }


            if (barcode.Length < 12)
            {
                int ii = 12 - barcode.Length;
                for (int i2 = 1; i2 <= ii; i2++)
                {
                    barcode += "0";
                }
            }

            BarcodeEAN13 encoderEAN13 = new BarcodeEAN13();
            Image        barcImg      = encoderEAN13.Encode(barcode);
            //
            Rectangle nr = new Rectangle(0, barcImg.Height / 2, barcImg.Width, barcImg.Height / 3);

            //graf2.DrawImage(barcImg, new Point(BarcodeX, BarcodeY));
            graf2.DrawImage(this.cropImage(barcImg, nr), new Point(BarcodeX, BarcodeY));

            MemoryStream memStream = new MemoryStream();

            context.Response.ContentType = "image/png";
            img.Save(memStream, ImageFormat.Png);

            memStream.WriteTo(context.Response.OutputStream);


            graf.Dispose();
            image.Dispose();
            barcImg.Dispose();
            img.Dispose();
        }
        protected void SubmitButton1_Click(object sender, EventArgs e)
        {
            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }


            string[] textParagraphs = txbMaters.Text.Split('\n');
            string[] newTP          = new string[textParagraphs.Length];
            string   outMaters      = "";

            int i = 0;

            foreach (string str in textParagraphs)
            {
                string strT = str.Replace("\r", "");
                newTP[i] = strT;
                i++;
            }

            outMaters += "'";
            i          = 1;
            foreach (string str in newTP)
            {
                outMaters += str;
                if (i != newTP.Count())
                {
                    outMaters += "','";
                }
                else
                {
                    outMaters += "'";
                }
                i++;
            }

            if (cbxGetData.Checked)
            {
                // загружаем данные из ЕРП
                LoadDataFromSAPERP(newTP);

                // загружаем из укм
                UKMSold_Info_load(outMaters);
            }


            //Connect to the database for Collections Table
            SqlConnection thisConnection = new SqlConnection(connStrSQL);

            //Create DataAdapter Object
            SqlDataAdapter thisAdapter = new SqlDataAdapter("  SELECT ROW_NUMBER() OVER (ORDER BY Artikul) as NUM, [Artikul]      ,[GoodName]  ,'1000' as Sklad     ,Sum([Sold]) as Qty  FROM [SaalutExpress].[dbo].[UKMSoldGoods]  where [KassaSmena] not in (SELECT [SMENA]  FROM [SaalutExpress].[dbo].[SAPOUT_SMENA]) group by [Artikul],[GoodName] ", thisConnection);

            // Create a fill a Dataset
            DataSet ds = new DataSet();

            thisAdapter.Fill(ds);


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



            DataRow[] result = ds.Tables[0].Select();
            foreach (DataRow row in result)
            {
                string artikul = row[1].ToString();
                string sklad   = row[3].ToString();

                var sapdata = (from s in context.SAPOUT_REST
                               where s.MATNR == artikul &&
                               s.LGORT == sklad
                               select s).FirstOrDefault();
                if (sapdata != null)
                {
                    double ukmqty = Double.Parse(row[4].ToString());
                    row[4] = sapdata.LABST - ukmqty;

                    row.EndEdit();
                    ds.Tables[0].AcceptChanges();

                    artikulsInSap.Add(artikul);
                }
            }

            string[] artikulsIn = artikulsInSap.ToArray();

            var sapdanns = from s in context.SAPOUT_REST
                           where (!artikulsIn.Contains(s.MATNR))
                           select s;

            i = 0;
            foreach (SAPOUT_REST so in sapdanns)
            {
                if (so.LGORT == "4000" && so.LABST == 0)
                {
                    continue;
                }

                DataRow workRow;
                workRow    = ds.Tables[0].NewRow();
                workRow[0] = i;
                workRow[1] = so.MATNR;
                workRow[2] = so.MAKTX;
                workRow[3] = so.LGORT;
                workRow[4] = so.LABST;
                ds.Tables[0].Rows.Add(workRow);
                workRow.EndEdit();
                ds.Tables[0].AcceptChanges();

                i++;
            }


            // счетчик
            i      = 1;
            result = ds.Tables[0].Select();
            foreach (DataRow row in result)
            {
                row[0] = i;

                row.EndEdit();
                ds.Tables[0].AcceptChanges();

                i++;
            }

            // выводим
            if (ds.Tables[0].Rows.Count != 0)
            {
                object objSumUKM;
                objSumUKM = ds.Tables[0].Compute("Sum(Qty)", "");


                GridView ReportGridView1 = new GridView();
                ReportGridView1.Width = new Unit(950);
                ReportGridView1.AutoGenerateColumns = false;

                BoundField fld0 = new System.Web.UI.WebControls.BoundField();
                fld0.HeaderText = "N";
                fld0.DataField  = "NUM";
                ReportGridView1.Columns.Add(fld0);

                BoundField fld3 = new System.Web.UI.WebControls.BoundField();
                fld3.HeaderText = "Арт.";
                fld3.DataField  = "Artikul";
                ReportGridView1.Columns.Add(fld3);


                BoundField fld4 = new System.Web.UI.WebControls.BoundField();
                fld4.HeaderText = "Наименование";
                fld4.DataField  = "GoodName";
                ReportGridView1.Columns.Add(fld4);

                BoundField fld5 = new System.Web.UI.WebControls.BoundField();
                fld5.HeaderText = "Склад";
                fld5.DataField  = "Sklad";
                ReportGridView1.Columns.Add(fld5);


                BoundField fld6 = new System.Web.UI.WebControls.BoundField();
                fld6.HeaderText       = "Остаток.";
                fld6.DataField        = "Qty";
                fld6.DataFormatString = "{0:F3}";
                ReportGridView1.Columns.Add(fld6);


                ReportGridView1.DataSource = ds.Tables[0];
                ReportGridView1.DataBind();
                ReportPlaceHolder1.Controls.Add(ReportGridView1);

                Label lblGroup = new Label();
                lblGroup.Text = "Итоги: " + objSumUKM.ToString() + ".";
                ReportPlaceHolder1.Controls.Add(lblGroup);
            }


            //Close Connection
            thisConnection.Close();

            Wizard1.ActiveStepIndex = 1;
        }
Exemple #22
0
        public void PrintTermoCennic_old(int goodID, int labelID, int qty, int printerID, string dateForLabel)
        {
            //string dateForLabel = "03.04.2012 08:00";

            // Get the physical path of the current application.
            string appPath         = HttpRuntime.AppDomainAppPath;
            string termLabelFolder = appPath + @"TRMLabels\";
            string termLabelExport = appPath + @"TRMExportCennic\";

            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }

            var settings = (from s in context.Settings
                            select s).FirstOrDefault();

            var storeInfo = (from s in context.StoreInfos
                             select s).FirstOrDefault();

            var good = (from g in context.Goods
                        where g.ID == goodID
                        select g).FirstOrDefault();

            if (good == null)
            {
                return;
            }

            var label = (from l in context.ThermoLabels
                         where l.ID == labelID
                         select l).FirstOrDefault();

            if (label == null)
            {
                return;
            }

            Encoding enc   = Encoding.GetEncoding(866);
            Encoding endTo = Encoding.GetEncoding(866);

            string filePath    = termLabelFolder + label.FileLabelName;
            string toFileName  = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK").Replace(".", "").Replace(" ", "").Replace(":", "").Replace("-", "").Replace("T", "").Replace("+", "") + "_" + label.FileLabelName;
            string toFilePath  = termLabelExport + toFileName;
            string batFilePath = termLabelExport + DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK").Replace(".", "").Replace(" ", "").Replace(":", "").Replace("-", "").Replace("T", "").Replace("+", "") + ".bat";


            StringBuilder str = new StringBuilder();

            try
            {
                using (StreamReader sr = new StreamReader(filePath, enc))
                {
                    while (sr.Peek() >= 0)
                    {
                        string toStr = "";

                        toStr = sr.ReadLine();
                        toStr = toStr.Replace("\r\n", "\n");
                        toStr = toStr.Replace("\r", "\n");
                        toStr = toStr.Replace("\t", " ");


                        // + goodName
                        if (toStr.Contains("%goodname"))
                        {
                            string        descr   = good.Descr;
                            StringBuilder strName = new StringBuilder();

                            descr = descr.Replace("\r\n", "\n");
                            descr = descr.Replace("\r", "\n");
                            descr = descr.Replace("\t", " ");

                            int length = descr.Length;
                            int from   = 0;

                            while (length >= label.GoodNameVStroke) //количество символов в строке
                            {
                                strName.Append(descr.Substring(from, label.GoodNameVStroke.Value) + "\n");
                                from   += label.GoodNameVStroke.Value;
                                length -= label.GoodNameVStroke.Value;
                            }
                            if (length < label.GoodNameVStroke.Value)
                            {
                                strName.Append(descr.Substring(from, length));
                            }

                            string[] textParagraphs = strName.ToString().Split('\n');
                            int      i = 1;
                            foreach (string strText in textParagraphs.ToArray())
                            {
                                using (StringFormat sf = new StringFormat())
                                {
                                    //sf.Alignment = StringAlignment.Near;
                                    //sf.LineAlignment = StringAlignment.Near;
                                    //sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
                                    sf.FormatFlags = StringFormatFlags.NoWrap;

                                    toStr = toStr.Replace("%goodname" + i.ToString() + "%", strText.Trim());
                                }
                                i++;
                            }

                            if (toStr.Contains("%goodname"))
                            {
                                toStr = toStr.Substring(0, toStr.IndexOf("%"));
                            }
                        }
                        // - goodName

                        // + goodContents
                        if (toStr.Contains("%contents") && good.Contents != null)
                        {
                            string        descr   = good.Contents;
                            StringBuilder strName = new StringBuilder();

                            descr = descr.Replace("\r\n", "\n");
                            descr = descr.Replace("\r", "\n");
                            descr = descr.Replace("\t", " ");

                            int length = descr.Length;
                            int from   = 0;

                            while (length >= label.ContentsVStroke) //количество символов в строке
                            {
                                strName.Append(descr.Substring(from, label.ContentsVStroke.Value) + "\n");
                                from   += label.ContentsVStroke.Value;
                                length -= label.ContentsVStroke.Value;
                            }
                            if (length < label.ContentsVStroke.Value)
                            {
                                strName.Append(descr.Substring(from, length));
                            }

                            string[] textParagraphs = strName.ToString().Split('\n');
                            int      i = 1;
                            foreach (string strText in textParagraphs.ToArray())
                            {
                                using (StringFormat sf = new StringFormat())
                                {
                                    //sf.Alignment = StringAlignment.Near;
                                    //sf.LineAlignment = StringAlignment.Near;
                                    //sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
                                    sf.FormatFlags = StringFormatFlags.NoWrap;

                                    toStr = toStr.Replace("%contents" + i.ToString() + "%", strText.Trim());
                                }
                                i++;
                            }

                            if (toStr.Contains("%contents"))
                            {
                                toStr = toStr.Substring(0, toStr.IndexOf("%"));
                            }
                        }
                        // - goodContents

                        toStr = toStr.Replace("%upakovshik%", "");


                        toStr = toStr.Replace("%docdate%", dateForLabel);
                        toStr = toStr.Replace("%article%", good.Articul);
                        toStr = toStr.Replace("%barcode%", good.Barcode);
                        toStr = toStr.Replace("%qty%", qty.ToString());

                        toStr = toStr.Replace("%edinica%", good.Edinic);
                        toStr = toStr.Replace("%producer%", good.Producer);

                        var price = (from p in context.Prices
                                     where p.GoodID == good.ID &&
                                     p.Active == true
                                     select p).FirstOrDefault();

                        toStr = toStr.Replace("%pricerub%", price.Price1.ToString());

                        DateTime valdays = DateTime.Today.AddDays(good.Exp_Qty.Value);

                        toStr = toStr.Replace("%validate%", valdays.ToString("d")); // Срок годности

                        toStr = toStr.Replace("%packsize%", "");                    // упаковка

                        toStr = toStr.Replace("%companylogo%", "1Y12000sp");        // 1Y1200000550380sp

                        toStr = toStr.Replace("%company%", storeInfo.Company);
                        toStr = toStr.Replace("%address%", storeInfo.AddressFact);


                        str.AppendLine(toStr);
                    }
                }

                string[] textParagraphsExport = str.ToString().Split('\n');

                using (StreamWriter sr = new StreamWriter(toFilePath, false, endTo, 512))
                {
                    foreach (string strText in textParagraphsExport.ToArray())
                    {
                        using (StringFormat sf = new StringFormat())
                        {
                            //sf.Alignment = StringAlignment.Near;
                            //sf.LineAlignment = StringAlignment.Near;
                            //sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
                            sf.FormatFlags = StringFormatFlags.NoWrap;

                            sr.WriteLine(strText.Trim());
                        }
                    }

                    sr.Flush();
                    sr.Close();
                }

                // + bat file
                using (StreamWriter sr = new StreamWriter(batFilePath, false, endTo, 512))
                {
                    var printer = (from p in context.TermoPrinters
                                   where p.ID == printerID
                                   select p).FirstOrDefault();
                    if (printer == null)
                    {
                        //sr.WriteLine(@"net use " + settings.TermoPrinterPort + ": /delete");
                        //sr.WriteLine(@"net use " + settings.TermoPrinterPort + ": " + settings.TermoPrinterNetPath + " /PERSISTENT:YES");
                        sr.WriteLine(@"cd " + termLabelExport);
                        sr.WriteLine(@"copy " + toFileName + " " + settings.TermoPrinterNetPath + " /b");
                    }
                    else
                    {
                        //sr.WriteLine(@"net use " + printer.TermoPrinterPort + ": /delete");
                        //sr.WriteLine(@"net use " + printer.TermoPrinterPort + ": " + printer.TermoPrinterNetPath + " /PERSISTENT:YES");
                        sr.WriteLine(@"cd " + termLabelExport);
                        sr.WriteLine(@"copy " + toFileName + " " + printer.TermoPrinterNetPath + " /b");
                    }


                    sr.Flush();
                    sr.Close();

                    //System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    //proc.StartInfo.FileName = batFilePath;
                    //proc.StartInfo.RedirectStandardError = false;
                    //proc.StartInfo.RedirectStandardOutput = false;
                    //proc.StartInfo.UseShellExecute = false;
                    //proc.Start();
                    //proc.WaitForExit();

                    //Process proc = Process.Start("cmd.exe", @"/C " + batFilePath);
                }
                // - bat file


                //if (File.Exists(toFilePath))
                //    File.Delete(toFilePath);
                //if (File.Exists(batFilePath))
                //    File.Delete(batFilePath);

                workTerm(); // запускаем на печать
            }
            catch (Exception e)
            {
                return;
            }
        }
        public string UKMSold_Info_load(string outMaters)
        {
            string ret             = "";
            int    newPriceCounter = 0;

            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }


            string txtDate = txbOnDate.Text;

            txtDate = txtDate.Substring(0, 4) + "-" + txtDate.Substring(4, 2) + "-" + txtDate.Substring(6, 2);


            // Del
            var ukmInfoDel = from p in context.UKMSoldGoods
                             select p;

            context.UKMSoldGoods.DeleteAllOnSubmit(ukmInfoDel);
            context.SubmitChanges();
            //-


            var store = (from s in context.StoreInfos
                         where s.Active == true
                         select s).FirstOrDefault();


            DataTable sales;

            MySqlConnection cnx = null;

            try
            {
                cnx = new MySqlConnection(connStr);
                MySqlDataAdapter adapter = new MySqlDataAdapter();


                //
                string       cmdText = " SELECT usr.name 'Casher', c.number 'POSN', c.cash_id 'CASH', so.id 'Smena', i.item 'Item', i.name 'Name', classif.id 'classif_id', classif.name 'classif', SUM(IF(h.type IN (0,5), 1, -1) * i.quantity) 'Qty', SUM(IF(h.type IN (0,5), 1, -1) * i.total + i.discount) 'Sum' FROM trm_in_pos c INNER JOIN trm_out_receipt_header h ON h.cash_id = c.cash_id INNER JOIN trm_out_receipt_item i ON i.cash_id = h.cash_id AND i.receipt_header = h.id  LEFT JOIN trm_out_receipt_item i2 ON (h.cash_id = i2.cash_id AND h.id = i2.receipt_header AND i2.link_item = i.id) INNER JOIN trm_out_receipt_footer f ON f.cash_id = h.cash_id AND f.id = h.id INNER JOIN trm_in_classif classif ON (i.classif = classif.id ) INNER JOIN trm_out_login lg ON (h.cash_id = lg.cash_id AND h.login = lg.id) INNER JOIN trm_in_users usr ON (c.store_id = usr.store_id AND lg.user_id = usr.id) INNER join trm_out_shift_open so on (so.id = h.shift_open AND so.cash_id = h.cash_id) WHERE i2.link_item IS NULL AND i.type = 0 AND h.type IN (0,5,1,4) AND f.result IN (0) AND i.item in (" + outMaters + ") AND so.date >= '" + txtDate + "'  GROUP BY h.shift_open, usr.name, i.item ORDER BY h.shift_open, usr.name, i.item;";
                MySqlCommand cmd     = new MySqlCommand(cmdText, cnx);
                cmd.CommandTimeout = 0;

                // Create a fill a Dataset
                DataSet ds = new DataSet();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds);

                sales = ds.Tables[0];

                if (sales != null)
                {
                    DateTime now = DateTime.Now;

                    int y = 0;
                    foreach (DataRow row in sales.Rows)
                    {
                        string casher    = (string)row[0];
                        string pos       = row[1].ToString();
                        string cash      = row[2].ToString();
                        string smena     = row[3].ToString();
                        string artikul   = row[4].ToString();
                        string name      = (string)row[5];
                        string classifid = row[6].ToString();
                        string classif   = row[7].ToString();

                        decimal qty  = (decimal)row[8];
                        double  nqty = Double.Parse(qty.ToString());

                        decimal summ  = (decimal)row[9];
                        double  nsumm = Double.Parse(summ.ToString());


                        UKMSoldGoods uk = new UKMSoldGoods();
                        uk.Casher      = casher;
                        uk.POSN        = pos;
                        uk.CASH        = cash;
                        uk.Smena       = smena;
                        uk.KassaSmena  = cash + "/" + smena;
                        uk.Artikul     = artikul;
                        uk.GoodName    = name;
                        uk.ClassifId   = classifid;
                        uk.ClassifName = classif;
                        uk.Sold        = nqty;
                        uk.Summ        = nsumm;

                        uk.TimeStamp = now;
                        context.UKMSoldGoods.InsertOnSubmit(uk);
                        if (y == 100)
                        {
                            y = 0;
                            context.SubmitChanges();
                        }

                        newPriceCounter++;
                    }
                    context.SubmitChanges();
                }
                else
                {
                    return(ret += "Нет продаж. Можно воспользоваться остатками из,,в САП или повторите позднее... ");
                }

                if (newPriceCounter != 0)
                {
                    ret += "Загружено из УКМ данных с количеством строк " + newPriceCounter.ToString() + ". ";
                }
            }
            catch (MySqlException ex)
            {
                return(ex.Message);
            }
            finally
            {
                if (cnx != null)
                {
                    cnx.Close();
                }
            }
            // -  по новому


            return(ret);
        }
Exemple #24
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            context = new SaalutDataClasses1DataContext();

            string ret = "";

            var store = (from s in context.StoreInfos
                         where s.Active == true
                         select s).FirstOrDefault();

            if (store == null)
            {
                return;
            }

            // Create a connection object and data adapter
            MySqlConnection cnx = null;

            try
            {
                cnx = new MySqlConnection(connStr);

                MySqlDataAdapter adapter = new MySqlDataAdapter();

                MySqlCommand cmd = new MySqlCommand("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;", cnx);
                cnx.Open();
                cmd.ExecuteNonQuery();



                //------------------------------------

                var goods = from g in context.Goods
                            select g;

                // items
                string cmdText = "select id, name, descr, measure, classif, version, deleted from ukmserver.trm_in_items where id in ('9001373','9001452','9001515','9002997','9002999','9003013','9003015','9003019','9003020','9003024','9003027','9003028','9003030','9003031','9003032','9003033','9003035','9003036','9003037','9003039','9003040','9003111','9003164','9003165','9003176','9003292','9003296','9003304','9003317','9003346','9003349','9003358','9003359') ";
                cmd = new MySqlCommand(cmdText, cnx);
                cmd.CommandTimeout = 30000;

                // Create a fill a Dataset
                DataSet ds1 = new DataSet();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds1);

                DataTable items = ds1.Tables[0];



                // Barcode
                cmdText            = "select id, item, version, deleted from ukmserver.trm_in_var ";
                cmd                = new MySqlCommand(cmdText, cnx);
                cmd.CommandTimeout = 30000;

                // Create a fill a Dataset
                DataSet ds2 = new DataSet();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds2);

                DataTable barcodes = ds2.Tables[0];


                // Assortment group items
                cmdText            = "select ag_id, var, plu, exp_date1, exp_date2, version, deleted from ukmserver.srv_assortment_group_items where store_id = '" + store.StoreID_UKM.ToString() + "' and deleted = 0 ";
                cmd                = new MySqlCommand(cmdText, cnx);
                cmd.CommandTimeout = 30000;

                // Create a fill a Dataset
                DataSet ds3 = new DataSet();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds3);

                DataTable assorts = ds3.Tables[0];


                // Structure
                cmdText            = "select id, country, structure, version, deleted, producer_marking from ukmserver.trm_in_item_cc ";
                cmd                = new MySqlCommand(cmdText, cnx);
                cmd.CommandTimeout = 30000;

                // Create a fill a Dataset
                DataSet ds4 = new DataSet();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds4);

                DataTable structures = ds4.Tables[0];


                // Prices
                cmdText            = "select item, price, version, deleted	from ukmserver.trm_in_pricelist_items where pricelist_id = '"+ store.PriceList_ID_UKM.ToString() + "'  and deleted = 0 ";
                cmd                = new MySqlCommand(cmdText, cnx);
                cmd.CommandTimeout = 30000;

                // Create a fill a Dataset
                DataSet ds5 = new DataSet();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds5);

                DataTable prices = ds5.Tables[0];


                // PrintTemplate good
                cmdText            = "select item_id, pricetag_id, version, deleted from ukmserver.srv_pricetags_item ";
                cmd                = new MySqlCommand(cmdText, cnx);
                cmd.CommandTimeout = 30000;

                // Create a fill a Dataset
                DataSet ds6 = new DataSet();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds6);

                DataTable printTemplGood = ds6.Tables[0];



                foreach (DataRow item in items.Rows)
                {
                    string id = item[0].ToString();

                    var good = (from g in goods
                                where g.Articul == id
                                select g).FirstOrDefault();
                    UKMDataBaseConnects utl = new UKMDataBaseConnects();
                    if (good == null)
                    {
                        // товара нету - создаем

                        utl.CreateNewGood(item, barcodes, assorts, structures, prices, printTemplGood);
                    }
                    else
                    {
                        utl.UpdateGood(good, item, barcodes, assorts, structures, prices, printTemplGood);
                    }
                }

                cmd = new MySqlCommand("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;", cnx);
                cmd.ExecuteNonQuery();
            }
            catch (MySqlException ex)
            {
                ret += "Error: " + ex.ToString();
            }
            finally
            {
                if (cnx != null)
                {
                    cnx.Close();
                }
            }

            return;
        }
Exemple #25
0
        public void PrintTermoCennic(int goodID, int labelID, int qty, int printerID, string dateForLabel, string proizvoditel)
        {
            //string dateForLabel = "03.04.2012 08:00";

            // Get the physical path of the current application.
            string appPath         = HttpRuntime.AppDomainAppPath;
            string termLabelFolder = appPath + @"TRMLabels\";
            string termLabelExport = appPath + @"TRMExportCennic\";

            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }

            var settings = (from s in context.Settings
                            select s).FirstOrDefault();

            var storeInfo = (from s in context.StoreInfos
                             select s).FirstOrDefault();

            var good = (from g in context.Goods
                        where g.ID == goodID
                        select g).FirstOrDefault();

            if (good == null)
            {
                return;
            }

            var label = (from l in context.ThermoLabels
                         where l.ID == labelID
                         select l).FirstOrDefault();

            if (label == null)
            {
                return;
            }

            Encoding enc   = Encoding.GetEncoding(866);
            Encoding endTo = Encoding.GetEncoding(866);

            string filePath    = termLabelFolder + label.FileLabelName;
            string toFileName  = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK").Replace(".", "").Replace(" ", "").Replace(":", "").Replace("-", "").Replace("T", "").Replace("+", "") + "_" + label.FileLabelName;
            string toFilePath  = termLabelExport + toFileName;
            string batFilePath = termLabelExport + DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK").Replace(".", "").Replace(" ", "").Replace(":", "").Replace("-", "").Replace("T", "").Replace("+", "") + ".bat";


            StringBuilder str = new StringBuilder();

            try
            {
                using (StreamReader sr = new StreamReader(filePath, enc))
                {
                    while (sr.Peek() >= 0)
                    {
                        string toStr = "";

                        toStr = sr.ReadLine();
                        toStr = toStr.Replace("\r\n", "\n");
                        toStr = toStr.Replace("\r", "\n");
                        toStr = toStr.Replace("\t", " ");


                        // + goodName
                        if (toStr.Contains("%goodname"))
                        {
                            string        descr   = good.Descr;
                            StringBuilder strName = new StringBuilder();

                            descr = descr.Replace("\r\n", "\n");
                            descr = descr.Replace("\r", "\n");
                            descr = descr.Replace("\t", " ");

                            int length = descr.Length;
                            int from   = 0;

                            while (length >= label.GoodNameVStroke) //количество символов в строке
                            {
                                strName.Append(descr.Substring(from, label.GoodNameVStroke.Value) + "\n");
                                from   += label.GoodNameVStroke.Value;
                                length -= label.GoodNameVStroke.Value;
                            }
                            if (length < label.GoodNameVStroke.Value)
                            {
                                strName.Append(descr.Substring(from, length));
                            }

                            string[] textParagraphs = strName.ToString().Split('\n');
                            int      i = 1;
                            foreach (string strText in textParagraphs.ToArray())
                            {
                                using (StringFormat sf = new StringFormat())
                                {
                                    //sf.Alignment = StringAlignment.Near;
                                    //sf.LineAlignment = StringAlignment.Near;
                                    //sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
                                    sf.FormatFlags = StringFormatFlags.NoWrap;

                                    toStr = toStr.Replace("%goodname" + i.ToString() + "%", strText.Trim());
                                }
                                i++;
                            }

                            if (toStr.Contains("%goodname"))
                            {
                                toStr = toStr.Substring(0, toStr.IndexOf("%"));
                            }
                        }
                        // - goodName

                        // + goodContents
                        if (toStr.Contains("%contents") && good.Contents != null)
                        {
                            string        descr   = good.Contents;
                            StringBuilder strName = new StringBuilder();

                            descr = descr.Replace("\r\n", "\n");
                            descr = descr.Replace("\r", "\n");
                            descr = descr.Replace("\t", " ");

                            int length = descr.Length;
                            int from   = 0;

                            while (length >= label.ContentsVStroke) //количество символов в строке
                            {
                                strName.Append(descr.Substring(from, label.ContentsVStroke.Value) + "\n");
                                from   += label.ContentsVStroke.Value;
                                length -= label.ContentsVStroke.Value;
                            }
                            if (length < label.ContentsVStroke.Value)
                            {
                                strName.Append(descr.Substring(from, length));
                            }

                            string[] textParagraphs = strName.ToString().Split('\n');
                            int      i = 1;
                            foreach (string strText in textParagraphs.ToArray())
                            {
                                using (StringFormat sf = new StringFormat())
                                {
                                    //sf.Alignment = StringAlignment.Near;
                                    //sf.LineAlignment = StringAlignment.Near;
                                    //sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
                                    sf.FormatFlags = StringFormatFlags.NoWrap;

                                    toStr = toStr.Replace("%contents" + i.ToString() + "%", strText.Trim());
                                }
                                i++;
                            }

                            if (toStr.Contains("%contents"))
                            {
                                toStr = toStr.Substring(0, toStr.IndexOf("%"));
                            }
                        }
                        // - goodContents

                        toStr = toStr.Replace("%upakovshik%", "");


                        toStr = toStr.Replace("%docdate%", dateForLabel);
                        toStr = toStr.Replace("%article%", good.Articul);
                        toStr = toStr.Replace("%barcode%", good.Barcode);
                        toStr = toStr.Replace("%qty%", qty.ToString());

                        toStr = toStr.Replace("%edinica%", good.Edinic);
                        toStr = toStr.Replace("%producer%", good.Producer);
                        toStr = toStr.Replace("%country%", proizvoditel);

                        // + цена по новому
                        DataTable prices;

                        MySqlConnection cnx = null;
                        try
                        {
                            cnx = new MySqlConnection(connStr);
                            MySqlDataAdapter adapter = new MySqlDataAdapter();

                            // Prices
                            string       cmdText = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ; select item, price, version, deleted from ukmserver.trm_in_pricelist_items where item = '" + good.Articul + "' and pricelist_id = '" + storeInfo.PriceList_ID_UKM.ToString() + "'  and deleted = 0; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ; ";
                            MySqlCommand cmd     = new MySqlCommand(cmdText, cnx);
                            cmd.CommandTimeout = 30000;

                            // Create a fill a Dataset
                            DataSet ds5 = new DataSet();
                            adapter.SelectCommand = cmd;
                            adapter.Fill(ds5);

                            prices = ds5.Tables[0];
                        }
                        catch (MySqlException ex)
                        {
                            return;
                        }
                        finally
                        {
                            if (cnx != null)
                            {
                                cnx.Close();
                            }
                        }

                        // - цена по новому



                        //var price = (from p in context.Prices
                        //             where p.GoodID == good.ID
                        //             && p.Active == true
                        //             select p).FirstOrDefault();

                        string priceVal = "нет цены";
                        //var price = (from p in dataContext.Prices
                        //             where p.GoodID == good.ID
                        //             && p.Active == true
                        //             select p).FirstOrDefault();
                        //if (price != null)
                        //{
                        //    double priceFromDB = price.Price1.Value;

                        //    if (template.EdinicZa100Gr != null)
                        //    {
                        //        if (template.EdinicZa100Gr.Value)
                        //        {
                        //            priceFromDB = priceFromDB / 10;
                        //        }
                        //    }
                        //    priceVal = priceFromDB.ToString();
                        //}

                        // + новая цена
                        decimal price = 0;
                        if (prices != null)
                        {
                            foreach (DataRow row in prices.Rows)
                            {
                                price = (decimal)row[1];
                            }
                        }
                        if (price != 0)
                        {
                            priceVal = price.ToString();
                            if (Division == "RB")
                            {
                                int priceValZap = priceVal.IndexOf(",");
                                if (priceValZap != -1)
                                {
                                    priceVal = priceVal.Substring(0, priceValZap);
                                }
                            }
                            else
                            if (Division == "RF")
                            {
                                int priceValZap = priceVal.IndexOf(",");
                                if (priceValZap != -1)
                                {
                                    if ((priceValZap + 3) < priceVal.Length)
                                    {
                                        priceVal = priceVal.Substring(0, priceValZap + 3);
                                    }
                                }
                            }
                        }
                        // - новая цена


                        toStr = toStr.Replace("%pricerub%", priceVal);

                        DateTime valdays = DateTime.Today.AddDays(good.Exp_Qty.Value);

                        toStr = toStr.Replace("%validate%", valdays.ToString("d")); // Срок годности

                        toStr = toStr.Replace("%packsize%", "");                    // упаковка

                        toStr = toStr.Replace("%companylogo%", "1Y12000sp");        // 1Y1200000550380sp

                        toStr = toStr.Replace("%company%", storeInfo.Company);
                        toStr = toStr.Replace("%address%", storeInfo.AddressFact);


                        str.AppendLine(toStr);
                    }
                }

                string[] textParagraphsExport = str.ToString().Split('\n');

                using (StreamWriter sr = new StreamWriter(toFilePath, false, endTo, 512))
                {
                    foreach (string strText in textParagraphsExport.ToArray())
                    {
                        using (StringFormat sf = new StringFormat())
                        {
                            //sf.Alignment = StringAlignment.Near;
                            //sf.LineAlignment = StringAlignment.Near;
                            //sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
                            sf.FormatFlags = StringFormatFlags.NoWrap;

                            sr.WriteLine(strText.Trim());
                        }
                    }

                    sr.Flush();
                    sr.Close();
                }

                // + bat file
                using (StreamWriter sr = new StreamWriter(batFilePath, false, endTo, 512))
                {
                    var printer = (from p in context.TermoPrinters
                                   where p.ID == printerID
                                   select p).FirstOrDefault();
                    if (printer == null)
                    {
                        //sr.WriteLine(@"net use " + settings.TermoPrinterPort + ": /delete");
                        //sr.WriteLine(@"net use " + settings.TermoPrinterPort + ": " + settings.TermoPrinterNetPath + " /PERSISTENT:YES");
                        sr.WriteLine(@"cd " + "C:\\inetpub\\wwwroot\\TRMExport\\");
                        sr.WriteLine(@"copy " + toFileName + " " + settings.TermoPrinterNetPath + " /b");
                    }
                    else
                    {
                        //sr.WriteLine(@"net use " + printer.TermoPrinterPort + ": /delete");
                        //sr.WriteLine(@"net use " + printer.TermoPrinterPort + ": " + printer.TermoPrinterNetPath + " /PERSISTENT:YES");
                        sr.WriteLine(@"cd " + "C:\\inetpub\\wwwroot\\TRMExport\\");
                        sr.WriteLine(@"copy " + toFileName + " " + printer.TermoPrinterNetPath + " /b");
                    }


                    sr.Flush();
                    sr.Close();

                    //System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    //proc.StartInfo.FileName = batFilePath;
                    //proc.StartInfo.RedirectStandardError = false;
                    //proc.StartInfo.RedirectStandardOutput = false;
                    //proc.StartInfo.UseShellExecute = false;
                    //proc.Start();
                    //proc.WaitForExit();

                    //Process proc = Process.Start("cmd.exe", @"/C " + batFilePath);
                }
                // - bat file


                //if (File.Exists(toFilePath))
                //    File.Delete(toFilePath);
                //if (File.Exists(batFilePath))
                //    File.Delete(batFilePath);

                workTerm(); // запускаем на печать
            }
            catch (Exception e)
            {
                return;
            }
        }
Exemple #26
0
        protected void Page_Load_old(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Dictionary <int, int> groupTemlates = new Dictionary <int, int>();


                context = new SaalutDataClasses1DataContext();

                if (Request.QueryString["ID"] == null)
                {
                    //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                    Response.Redirect("NewJours.aspx");
                }

                Int32.TryParse(Request.QueryString["ID"], out jourID);

                if (jourID == 0)
                {
                    //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                    Response.Redirect("NewJours.aspx");
                }


                if (Request.QueryString["WP"] != null)
                {
                    int tmpI = 0;
                    Int32.TryParse(Request.QueryString["WP"], out tmpI);
                    if (tmpI == 1)
                    {
                        WhithoutPrice = true;
                    }
                }


                //if (Session["JourCart"] == null)
                //    //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                //    Response.Redirect("NewJours.aspx");

                var jLines = from j in context.PriceChangeLine
                             where j.JournalID == jourID
                             select j;
                foreach (PriceChangeLine ln in jLines)
                {
                    if (WhithoutPrice == true)
                    {
                        var prs = (from p in context.Prices
                                   where p.GoodID == ln.GoodID &&
                                   p.Active == true
                                   select p).FirstOrDefault();
                        if (prs == null)
                        {
                            continue;
                        }
                    }

                    JourCart cart = (JourCart)Session["JourCart"];
                    foreach (JourCartItem items in cart)
                    {
                        if (items.JourLineID == ln.ID)
                        {
                            // входит в список распечатки.
                            groupTemlates.Add(ln.ID, FindTemplate(ln.ID));

                            break;
                        }
                    }
                }


                // Выбираем данные из УКМ по ценам и сохраняем их в таблицу
                var store = (from s in context.StoreInfos
                             where s.Active == true
                             select s).FirstOrDefault();
                if (store == null)
                {
                    return;
                }



                //------
                // выводим на экран с группировкой по типу ценника
                int currCountCennic = 0;
                foreach (var item in groupTemlates.OrderBy(key => key.Value))
                {
                    int templateIDInCart        = 0;
                    PrintTemplateCart templCart = (PrintTemplateCart)Session["PrintTemplateCart"];
                    foreach (PrintTemplateCartItem itemTempl in templCart)
                    {
                        if (itemTempl.JourLineID == item.Key)
                        {
                            templateIDInCart = itemTempl.TemplateID;

                            break;
                        }
                    }

                    Image img = new Image();
                    if (templateIDInCart == 0)
                    {
                        img.ImageUrl = "Services/Cennic.ashx?LID=" + item.Key.ToString() + "&TID=" + item.Value.ToString();
                    }
                    else
                    {
                        img.ImageUrl = "Services/Cennic.ashx?LID=" + item.Key.ToString() + "&TID=" + templateIDInCart.ToString();
                    }

                    CennicPlaceHolder1.Controls.Add(img);

                    currCountCennic++;
                }

                currCountCennic = 0;
                if (groupTemlates.Count == 0)
                {
                    var lines = from l in context.PriceChangeLine
                                where l.JournalID == jourID &&
                                l.Active == true
                                select l;

                    foreach (PriceChangeLine line in lines)
                    {
                        if (WhithoutPrice == true)
                        {
                            var prs = (from p in context.Prices
                                       where p.GoodID == line.GoodID &&
                                       p.Active == true
                                       select p).FirstOrDefault();
                            if (prs == null)
                            {
                                continue;
                            }
                        }


                        int templateIDInCart        = 0;
                        PrintTemplateCart templCart = (PrintTemplateCart)Session["PrintTemplateCart"];
                        foreach (PrintTemplateCartItem itemTempl in templCart)
                        {
                            if (itemTempl.JourLineID == line.GoodID)
                            {
                                templateIDInCart = itemTempl.TemplateID;

                                break;
                            }
                        }
                        Image img = new Image();
                        img.ImageUrl = "Services/Cennic.ashx?LID=" + line.ID.ToString() + "&TID=" + templateIDInCart.ToString();

                        CennicPlaceHolder1.Controls.Add(img);

                        currCountCennic++;
                    }
                }
            }
        }
Exemple #27
0
        protected void btnInitAkcionnieCeny_Click(object sender, EventArgs e)
        {
            string ret = "";


            SaalutDataClasses1DataContext context = new SaalutDataClasses1DataContext();

            //-------------------------------

            var delStoreInfo = (from d in context.StoreInfos
                                select d).FirstOrDefault();

            string jurCo = delStoreInfo.Company;
            string jurF  = delStoreInfo.AddressFact;

            context.StoreInfos.DeleteOnSubmit(delStoreInfo);
            context.SubmitChanges();

            UKMDataBaseConnects utl = new UKMDataBaseConnects();

            utl.InitialStoreInfoIns();

            var newStoreInfo = (from d in context.StoreInfos
                                select d).FirstOrDefault();

            newStoreInfo.Company     = jurCo;
            newStoreInfo.AddressFact = jurF;
            context.SubmitChanges();
            //---------------------------------

            var pricesAkcion = (from p in context.PricesAkcionnies
                                select p).FirstOrDefault();

            if (pricesAkcion != null)
            {
                return;
            }

            var store = (from s in context.StoreInfos
                         where s.Active == true
                         select s).FirstOrDefault();

            CommittableTransaction tx = new CommittableTransaction();

            // Create a connection object and data adapter
            MySqlConnection cnx = null;

            try
            {
                cnx = new MySqlConnection(connStr);

                MySqlDataAdapter adapter = new MySqlDataAdapter();

                // = делаем текущий прайс лист магазина


                // Выбираем магазин
                string       cmdText = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ; select item, price, version, deleted from ukmserver.trm_in_pricelist_items where pricelist_id = '" + store.ActPriceList_ID_UKM.ToString() + "'  and deleted = 0; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ; ";
                MySqlCommand cmd     = new MySqlCommand(cmdText, cnx);
                cmd.CommandTimeout = 30000;

                // Create a fill a Dataset
                DataSet ds = new DataSet();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds);

                DataTable pricesAkcionnie = ds.Tables[0];
                if (pricesAkcionnie != null)
                {
                    foreach (DataRow row1 in pricesAkcionnie.Rows)
                    {
                        string  artikulA       = (string)row1[0];
                        decimal priceA         = (decimal)row1[1];
                        int     version_priceA = (int)row1[2];
                        bool    delete_priceA  = (bool)row1[3];


                        double newPriceA = Double.Parse(priceA.ToString());

                        var good = (from g in context.Goods
                                    where g.Articul == artikulA
                                    select g).FirstOrDefault();

                        if (good == null)
                        {
                            continue;
                        }

                        //+
                        PricesAkcionnie npr1 = new PricesAkcionnie();
                        npr1.GoodID      = good.ID;
                        npr1.Price       = newPriceA;
                        npr1.Version_UKM = version_priceA;
                        npr1.TimeStamp   = DateTime.Now;
                        npr1.Active      = true;
                        context.PricesAkcionnies.InsertOnSubmit(npr1);
                        context.SubmitChanges();
                        //-
                    }
                }

                tx.Commit();
            }
            catch (MySqlException ex)
            {
                ret += "Error: " + ex.ToString();
                tx.Rollback();
            }
            finally
            {
                if (cnx != null)
                {
                    cnx.Close();
                }
            }

            return;
        }
        protected void FillControls()
        {
            if (context == null)
            {
                context = new SaalutDataClasses1DataContext();
            }

            Dictionary <string, string> groupsUp = new Dictionary <string, string>();

            MySqlConnection cnx = null;

            cnx = new MySqlConnection(connStr);

            string       cmdText = "select * from trm_in_classif where owner in (select id from trm_in_classif where owner = 0) order by name";
            MySqlCommand cmd     = new MySqlCommand(cmdText, cnx);

            cmd.CommandTimeout = 18000;

            MySqlDataAdapter adapter = new MySqlDataAdapter();

            // Create a fill a Dataset
            DataSet ds = new DataSet();

            adapter.SelectCommand = cmd;
            adapter.Fill(ds);

            if (ds.Tables[0].Rows.Count != 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string id = row.Field <string>("id");

                    string       cmdText2 = "select * from trm_in_classif where owner=" + id + "; ";
                    MySqlCommand cmd2     = new MySqlCommand(cmdText2, cnx);
                    // Create a fill a Dataset
                    DataSet ds2 = new DataSet();
                    adapter.SelectCommand = cmd2;
                    adapter.Fill(ds2);

                    if (ds2.Tables[0].Rows.Count != 0)
                    {
                        foreach (DataRow row2 in ds2.Tables[0].Rows)
                        {
                            string id2   = row2.Field <string>("id");
                            string name2 = row2.Field <string>("name");

                            string intGroupN = "";
                            if (id2 != "")
                            {
                                if (!groupsUp.TryGetValue(id2, out intGroupN))
                                {
                                    //var grpnfrr = (from g in context.Groups
                                    //               where g.GroupNum == id2
                                    //               select g).FirstOrDefault();

                                    groupsUp.Add(id2, name2);
                                }
                            }
                        }
                    }
                }
            }



            //-
            foreach (KeyValuePair <string, string> pair in groupsUp.OrderBy(key => key.Value))
            {
                ListItem itm = new ListItem();
                itm.Text  = pair.Value;
                itm.Value = pair.Key;
                SelectListBox1.Items.Add(itm);
            }
        }
Exemple #29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string Division = WebConfigurationManager.AppSettings["Division"];

            if (!IsPostBack)
            {
                Dictionary <int, int> groupTemlates = new Dictionary <int, int>();

                context = new SaalutDataClasses1DataContext();

                if (Request.QueryString["ID"] == null)
                {
                    //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                    Response.Redirect("NewJours.aspx");
                }

                Int32.TryParse(Request.QueryString["ID"], out jourID);

                if (jourID == 0)
                {
                    //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                    Response.Redirect("NewJours.aspx");
                }


                if (Request.QueryString["WP"] != null)
                {
                    int tmpI = 0;
                    Int32.TryParse(Request.QueryString["WP"], out tmpI);
                    if (tmpI == 1)
                    {
                        WhithoutPrice = true;
                    }
                }

                var store = (from s in context.StoreInfos
                             where s.Active == true
                             select s).FirstOrDefault();
                if (store == null)
                {
                    Response.Redirect("NewJours.aspx");
                }



                //if (Session["JourCart"] == null)
                //    //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                //    Response.Redirect("NewJours.aspx");

                var jLines = from j in context.PriceChangeLine
                             where j.JournalID == jourID
                             select j;
                foreach (PriceChangeLine ln in jLines)
                {
                    if (WhithoutPrice == true)
                    {
                        //var prs = (from p in context.Prices
                        //           where p.GoodID == ln.GoodID
                        //           && p.Active == true
                        //           select p).FirstOrDefault();
                        //if (prs == null)
                        //    continue;

                        decimal price = 0;

                        MySqlConnection cnx = null;
                        try
                        {
                            DataTable prices;

                            cnx = new MySqlConnection(connStr);
                            MySqlDataAdapter adapter = new MySqlDataAdapter();

                            // Prices
                            string       cmdText = "select item, price, version, deleted	from ukmserver.trm_in_pricelist_items where pricelist_id = '"+ store.PriceList_ID_UKM.ToString() + "' and item = '" + ln.Good.Articul.ToString() + "'  and deleted = 0 ";
                            MySqlCommand cmd     = new MySqlCommand(cmdText, cnx);
                            cmd.CommandTimeout = 30000;

                            // Create a fill a Dataset
                            DataSet ds5 = new DataSet();
                            adapter.SelectCommand = cmd;
                            adapter.Fill(ds5);

                            prices = ds5.Tables[0];

                            if (prices != null)
                            {
                                // select item, price, version, deleted	from ukmserver.trm_in_pricelist_items where pricelist_id = '" + store.PriceList_ID_UKM.ToString() + "' and deleted = 0
                                DataRow[] prsLsts = prices.Select("item = '" + ln.Good.Articul + "'");

                                foreach (DataRow row in prsLsts)
                                {
                                    price = (decimal)row[1];
                                }
                            }
                        }
                        catch (MySqlException ex)
                        {
                            Response.Redirect("ErrorPage.aspx");
                        }
                        finally
                        {
                            if (cnx != null)
                            {
                                cnx.Close();
                            }
                        }

                        if (price == 0)
                        {
                            continue;
                        }
                    } // if (WhithoutPrice == true)

                    JourCart cart = (JourCart)Session["JourCart"];
                    foreach (JourCartItem items in cart)
                    {
                        if (items.JourLineID == ln.ID)
                        {
                            // входит в список распечатки.
                            groupTemlates.Add(ln.ID, FindTemplate(ln.ID));

                            break;
                        }
                    }
                }


                //------
                // выводим на экран с группировкой по типу ценника
                int currCountCennic = 0;
                foreach (var item in groupTemlates.OrderBy(key => key.Value))
                {
                    string proizvoditel = "";
                    string goodName     = "";

                    int templateIDInCart        = 0;
                    PrintTemplateCart templCart = (PrintTemplateCart)Session["PrintTemplateCart"];
                    foreach (PrintTemplateCartItem itemTempl in templCart)
                    {
                        if (itemTempl.JourLineID == item.Key)
                        {
                            templateIDInCart = itemTempl.TemplateID;
                            proizvoditel     = itemTempl.Proizvoditel;
                            goodName         = itemTempl.GoodName;
                            break;
                        }
                    }

                    Image img = new Image();
                    if (templateIDInCart == 0)
                    {
                        img.ImageUrl = "Services/Cennic.ashx?LID=" + item.Key.ToString() + "&TID=" + item.Value.ToString() + "&PID=" + Server.UrlEncode(proizvoditel) + "&GNID=" + Server.UrlEncode(goodName);
                    }
                    else
                    {
                        img.ImageUrl = "Services/Cennic.ashx?LID=" + item.Key.ToString() + "&TID=" + templateIDInCart.ToString() + "&PID=" + Server.UrlEncode(proizvoditel) + "&GNID=" + Server.UrlEncode(goodName);
                    }

                    CennicPlaceHolder1.Controls.Add(img);

                    currCountCennic++;
                }

                currCountCennic = 0;
                if (groupTemlates.Count == 0)
                {
                    var lines = from l in context.PriceChangeLine
                                where l.JournalID == jourID &&
                                l.Active == true
                                select l;

                    foreach (PriceChangeLine line in lines)
                    {
                        if (WhithoutPrice == true)
                        {
                            //var prs = (from p in context.Prices
                            //           where p.GoodID == ln.GoodID
                            //           && p.Active == true
                            //           select p).FirstOrDefault();
                            //if (prs == null)
                            //    continue;

                            decimal price = 0;

                            MySqlConnection cnx = null;
                            try
                            {
                                DataTable prices;

                                cnx = new MySqlConnection(connStr);
                                MySqlDataAdapter adapter = new MySqlDataAdapter();

                                // Prices
                                string       cmdText = "select item, price, version, deleted	from ukmserver.trm_in_pricelist_items where pricelist_id = '"+ store.PriceList_ID_UKM.ToString() + "' and item = '" + line.Good.Articul.ToString() + "'  and deleted = 0 ";
                                MySqlCommand cmd     = new MySqlCommand(cmdText, cnx);
                                cmd.CommandTimeout = 30000;

                                // Create a fill a Dataset
                                DataSet ds5 = new DataSet();
                                adapter.SelectCommand = cmd;
                                adapter.Fill(ds5);

                                prices = ds5.Tables[0];
                                if (prices != null)
                                {
                                    // select item, price, version, deleted	from ukmserver.trm_in_pricelist_items where pricelist_id = '" + store.PriceList_ID_UKM.ToString() + "' and deleted = 0
                                    DataRow[] prsLsts = prices.Select("item = '" + line.Good.Articul + "'");

                                    foreach (DataRow row in prsLsts)
                                    {
                                        price = (decimal)row[1];
                                    }
                                }
                            }
                            catch (MySqlException ex)
                            {
                                Response.Redirect("ErrorPage.aspx");
                            }
                            finally
                            {
                                if (cnx != null)
                                {
                                    cnx.Close();
                                }
                            }

                            if (price == 0)
                            {
                                continue;
                            }
                        } // if (WhithoutPrice == true)

                        string proizvoditel = "";
                        string goodName     = "";

                        int templateIDInCart        = 0;
                        PrintTemplateCart templCart = (PrintTemplateCart)Session["PrintTemplateCart"];
                        foreach (PrintTemplateCartItem itemTempl in templCart)
                        {
                            if (itemTempl.JourLineID == line.GoodID)
                            {
                                templateIDInCart = itemTempl.TemplateID;
                                proizvoditel     = itemTempl.Proizvoditel;
                                goodName         = itemTempl.GoodName;
                                break;
                            }
                        }
                        Image img = new Image();
                        img.ImageUrl = "Services/Cennic.ashx?LID=" + line.ID.ToString() + "&TID=" + templateIDInCart.ToString() + "&PID=" + Server.UrlEncode(proizvoditel) + "&GNID=" + Server.UrlEncode(goodName);

                        CennicPlaceHolder1.Controls.Add(img);

                        currCountCennic++;
                    }
                }
            }
        }