Esempio n. 1
0
 void DoCountLines()
 {
     string strDir = System.IO.Directory.GetCurrentDirectory();
     strDir += @"/Assets/Scripts";
     int iLengthOfRootPath = strDir.Length;
     ArrayList stats = new ArrayList();
     ProcessDirectory(stats, strDir);
     int iTotalNbLines = 0;
     foreach (File f in stats)
     {
         iTotalNbLines += f.nbLines;
     }
     strStats = new System.Text.StringBuilder();
     strStats.Append("Number of Files: " + stats.Count + "\n");
     strStats.Append("Number of Lines: " + iTotalNbLines + "\n");
     strStats.Append("================\n");
     CountEntry[] fileStats = new CountEntry[stats.Count];
     int i = 0;
     foreach (File f in stats)
     {
         CountEntry c = new CountEntry();
         c.name = f.name.Substring(iLengthOfRootPath + 1, f.name.Length - iLengthOfRootPath - 1);
         c.lines = System.Convert.ToInt32(f.nbLines);
         fileStats[i] = c;
         i++;
     }
     System.Array.Sort(fileStats, delegate (CountEntry c1, CountEntry c2) {
         return c1.lines.CompareTo(c2.lines);
     });
     foreach (CountEntry c in fileStats)
     {
         strStats.Append(c.name + " --> " + c.lines + "\n");
     }
 }
Esempio n. 2
0
        public LabelTemplate(Article art, CountEntry en)
        {
            InitializeComponent();
            labelBarcode.Text       = art.Itmref;
            labelBarcodeItmref.Text = art.Itmref;
            labelItmdes.Text        = art.Itmdes;

            labelNumber.Text = en.LabelNumber.ToString();
            labelDate.Text   = en.Time.ToLocalTime().ToShortDateString();
        }
Esempio n. 3
0
        private void dataGridViewCounts_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView g = sender as DataGridView;

            if (e.RowIndex >= 0 && g != null && g.Rows.Count >= e.RowIndex)
            {
                CountEntry en = g.Rows[e.RowIndex].DataBoundItem as CountEntry;
                if (en != null && !ModifiedEntries.Contains(en))
                {
                    ModifiedEntries.Add(en);
                }
            }
        }
Esempio n. 4
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            double v = -1;

            if (!Double.TryParse(textBoxCount.Text, out v))
            {
                MessageBox.Show("Introduza uma quantidade válida", "Valor inválido", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            int nextNumber = 0;

            foreach (CountEntry entry in CountEntries)
            {
                nextNumber = Math.Max(nextNumber, entry.LabelNumber);
            }
            nextNumber++;

            Location l = comboBoxLocations.SelectedItem as Location;


            CountEntry en = new CountEntry();

            en.Itmref      = SelectedArticle.Itmref;
            en.LabelNumber = nextNumber;
            en.Value       = v;
            en.Unit        = StockUnit;
            en.Time        = DateTime.UtcNow;
            en.IsDeleted   = false;

            if (l != null)
            {
                en.Location = l.Code;
                if (!Properties.Settings.Default.DefaultLocation.Equals(l.Code))
                {
                    Properties.Settings.Default.DefaultLocation = l.Code;
                    Properties.Settings.Default.Save();
                }
            }


            SqliteConnector db = SqliteConnector.SqliteDB;

            using (SQLiteConnection con = db.Connect())
            {
                bool retry = false;
                do
                {
                    retry = false;
                    SQLiteTransaction tr = null;
                    try
                    {
                        tr = con.BeginTransaction();
                        db.Insert(con, en, tr);
                        PrintLabel(SelectedArticle, en);
                        tr.Commit();
                        CountEntries.Add(en);
                    }
                    catch (Exception ex)
                    {
                        DialogResult res = MessageBox.Show(ex.Message, "Ocorreu um erro ao imprimir a etiqueta", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Exclamation);
                        if (res == DialogResult.Ignore)
                        {
                            tr.Commit();
                        }
                        else
                        {
                            if (tr != null)
                            {
                                tr.Rollback();
                            }
                        }
                        if (res == DialogResult.Retry)
                        {
                            retry = true;
                        }
                        if (res == DialogResult.Abort)
                        {
                            return;
                        }
                    }
                } while (retry);
            }



            double acc = 0;

            foreach (CountEntry entry in CountEntries)
            {
                acc += entry.Value;
            }

            SelectedArticle.CountedQuantity = acc;
            SelectedArticle.LabelCount      = CountEntries.Count;

            DialogResult = DialogResult.OK;
            Close();
        }
Esempio n. 5
0
        protected void zPrintLabel(Article art, CountEntry en)
        {
            /*
             * string printerName = "";
             * foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
             * {
             *  if (!string.IsNullOrEmpty(printer) && printer.Contains("TSC"))
             *      printerName = printer;
             * }
             */
            LabelTemplate tpl = new LabelTemplate(art, en);

            string size = String.Format("{0}x{1}(mm)", Settings.Default.PageWidth, Settings.Default.PageHeight);
            //in hundredths of an inch.
            int w   = (int)(Settings.Default.PageWidth / 0.254);
            int h   = (int)(Settings.Default.PageHeight / 0.254);
            int dpi = 203;

            tpl.Width  = (int)(Settings.Default.PageWidth * dpi / 25.4);
            tpl.Height = (int)(Settings.Default.PageHeight * dpi / 25.4);



            using (Bitmap scaled = new Bitmap(w * dpi / 100, h * dpi / 100))
            {
                using (Bitmap b = new Bitmap(tpl.Width, tpl.Height))
                {
                    b.SetResolution(dpi, dpi);
                    //tpl.Width = w;
                    //tpl.Height = h;
                    tpl.DrawToBitmap(b, new Rectangle(0, 0, b.Width, b.Height));
                    //tpl.CreateGraphics()
                    Graphics graph = Graphics.FromImage(scaled);
                    graph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
                    graph.SmoothingMode     = SmoothingMode.AntiAlias;

                    graph.InterpolationMode  = InterpolationMode.NearestNeighbor;
                    graph.CompositingQuality = CompositingQuality.HighQuality;
                    //graph.SmoothingMode = SmoothingMode.None;
                    graph.DrawImage(b, new Rectangle(0, 0, scaled.Width, scaled.Height));


                    b.Save("LBL.bmp");
                }



                LabelBitmap = scaled;


                using (PrintDocument doc = new PrintDocument())
                {
                    doc.PrinterSettings.PrinterName   = Settings.Default.PrinterName;
                    doc.DefaultPageSettings.Landscape = false;
                    doc.DefaultPageSettings.Color     = false;
                    doc.DefaultPageSettings.Margins   = new Margins(5, 5, 5, 5);
                    //make it a multiple of bitmap width

                    doc.DefaultPageSettings.PaperSize = new PaperSize(size, w, h);

                    //doc.PrintPage += Doc_PrintPage;

                    doc.PrintPage += delegate(object sender, PrintPageEventArgs e)
                    {
                        Font     font  = new Font("Codigo 128", 30, FontStyle.Regular, GraphicsUnit.Point);
                        Brush    solid = Brushes.Black;
                        Graphics g     = e.Graphics;
                        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
                        g.Clear(Color.White);

                        SizeF     dataSize = g.MeasureString(art.Itmref, font);
                        Rectangle area     = new Rectangle((int)(e.MarginBounds.Left + ((e.MarginBounds.Width - dataSize.Width) / 2.0)), e.MarginBounds.Top, e.MarginBounds.Width, 30);

                        g.DrawString(art.Itmref, font, solid, area);


                        font     = new Font("Calibri", 14, FontStyle.Regular, GraphicsUnit.Pixel);
                        dataSize = g.MeasureString(art.Itmref, font);
                        area     = new Rectangle((int)(e.MarginBounds.Left + ((e.MarginBounds.Width - dataSize.Width) / 2.0)), e.MarginBounds.Top + 30, e.MarginBounds.Width, 14);
                        g.DrawString(art.Itmref, font, solid, area);

                        font = new Font("Verdana", 10, FontStyle.Regular, GraphicsUnit.Pixel);
                        area = new Rectangle(e.MarginBounds.Left, e.MarginBounds.Top + 30 + 14 + 5, e.MarginBounds.Width, 22);
                        g.DrawString(art.Itmdes, font, solid, area);

                        font = new Font("Verdana", 8, FontStyle.Regular, GraphicsUnit.Pixel);
                        String footer = String.Format("{0}  {1}", en.LabelNumber, en.Time.ToShortDateString());
                        dataSize = g.MeasureString(footer, font);
                        area     = new Rectangle((int)(e.MarginBounds.Left + e.MarginBounds.Width - dataSize.Width + 0.5), e.MarginBounds.Top + e.MarginBounds.Bottom - 12 - 5, (int)(dataSize.Width + 0.5), 10);
                        g.DrawString(footer, font, solid, area);


                        g.Flush();

                        font.Dispose();
                        //g.Dispose();
                    };

                    doc.Print();
                }



                //b.Save("LBL.BMP");

                /*
                 * using (MagickImage image = new MagickImage(scaled))
                 * {
                 *  image.Format = MagickFormat.Pcx;
                 *  image.ColorType = ColorType.Bilevel;
                 *  //image.Write("LBL.PCX");
                 *
                 *  using(Bitmap t = image.ToBitmap())
                 *  {
                 *      t.Save("pcb.bmp");
                 *  }
                 *
                 * }
                 */
            }

            /*
             * TSCLIBResult = TSCLIB.openport(printerName);                                           //Open specified printer driver
             *
             * try
             * {
             *  TSCLIBResult = TSCLIB.setup("50", "25", "1", "12", "0", "3", "0");                      //Setup the media size and sensor type info
             *  //TSCLIBResult = TSCLIB.formfeed();
             *  TSCLIBResult = TSCLIB.clearbuffer();                                                    //Clear image buffer
             *
             *  //TSCLIBResult = TSCLIB.barcode("8", "8", "128", "48", "1", "0", "2", "2", en.Itmref);   //Drawing barcode
             *  //TSCLIBResult = TSCLIB.sendcommand("BARCODE 8,8,\"128M\",48,2,0,1,2,2,\""+en.Itmref+"\"");
             *
             *  //TSCLIBResult = TSCLIB.windowsfont(8, 80, 10, 0, 0, 0, "Verdana", art.Itmdes);           //Drawing printer font
             *
             *  TSCLIBResult = TSCLIB.downloadpcx("LBL.PCX", "LBL.PCX");                                         //Download PCX file into printer
             *  TSCLIBResult = TSCLIB.sendcommand("PUTPCX 0,0,\"LBL.PCX\"");                                //Drawing PCX graphic
             *
             *  TSCLIBResult = TSCLIB.printlabel("1", "1");                                                    //Print labels
             * }
             * finally
             * {
             *  TSCLIB.closeport();
             * }
             *
             */
        }
Esempio n. 6
0
        protected void PrintLabel(Article art, CountEntry en)
        {
            if (Settings.Default.PrinterNull.Equals(Settings.Default.PrinterName))
            {
                return;
            }

            string size = String.Format("{0}x{1}(mm)", Settings.Default.PageWidth, Settings.Default.PageHeight);
            //in hundredths of an inch.
            int w = (int)(Settings.Default.PageWidth / 0.254);
            int h = (int)(Settings.Default.PageHeight / 0.254);



            using (PrintDocument doc = new PrintDocument())
            {
                doc.PrinterSettings.PrinterName   = Settings.Default.PrinterName;
                doc.DefaultPageSettings.Landscape = false;
                doc.DefaultPageSettings.Color     = false;
                doc.DefaultPageSettings.PaperSize = new PaperSize(size, w, h);
                doc.DefaultPageSettings.Margins   = new Margins(5, 5, 5, 5);
                foreach (PrinterResolution r in doc.PrinterSettings.PrinterResolutions)
                {
                    if (r.Kind == PrinterResolutionKind.High)
                    {
                        doc.DefaultPageSettings.PrinterResolution = r;
                        break;
                    }
                }

                //make it a multiple of bitmap width

                doc.PrintPage += delegate(object sender, PrintPageEventArgs e)
                {
                    //Font font = new Font("Codigo 128", 30, FontStyle.Regular, GraphicsUnit.Point);
                    Brush    solid = Brushes.Black;
                    Graphics g     = e.Graphics;
                    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
                    g.Clear(Color.White);


                    float dphiX = g.DpiX / 100;
                    float dphiY = g.DpiY / 100;
                    g.PageScale = 1 / (2 * dphiX);

                    //Rectangle printArea = new Rectangle((int)(e.MarginBounds.Left * dphiX), (int)(e.MarginBounds.Top * dphiX), (int)(e.MarginBounds.Width * dphiX), (int)(30 * dphiY));
                    Rectangle printArea = new Rectangle((int)(e.MarginBounds.Left / g.PageScale), (int)(e.MarginBounds.Top / g.PageScale), (int)(e.MarginBounds.Width / g.PageScale), (int)(30 / g.PageScale));

                    switch (Settings.Default.Barcode)
                    {
                    case "Code39":
                        Barcodes.Barcode39 c39 = new Barcodes.Barcode39();
                        c39.MakeBarcodeImage(art.Itmref, g, printArea);
                        break;

                    default:
                        GenCode128.Code128Rendering.MakeBarcodeImage(art.Itmref, g, printArea);
                        break;
                    }

                    g.PageScale = 1;

                    Font      font     = new Font("Calibri", 12, FontStyle.Regular, GraphicsUnit.Pixel);
                    SizeF     dataSize = g.MeasureString(art.Itmref, font);
                    Rectangle area     = new Rectangle((int)(e.MarginBounds.Left + ((e.MarginBounds.Width - dataSize.Width) / 2.0)), e.MarginBounds.Top + 28, e.MarginBounds.Width, 12);
                    g.DrawString(art.Itmref, font, solid, area);

                    font = new Font("Verdana", 10, FontStyle.Regular, GraphicsUnit.Pixel);
                    area = new Rectangle(e.MarginBounds.Left, e.MarginBounds.Top + 28 + 12 + 3, e.MarginBounds.Width, 24);
                    g.DrawString(art.Itmdes, font, solid, area);

                    font = new Font("Verdana", 8, FontStyle.Regular, GraphicsUnit.Pixel);
                    String footer = String.Format("{0}  {1}", en.LabelNumber, en.Time.ToShortDateString());
                    dataSize = g.MeasureString(footer, font);
                    area     = new Rectangle((int)(e.MarginBounds.Left + e.MarginBounds.Width - dataSize.Width * 1.2 + 0.5), e.MarginBounds.Top + e.MarginBounds.Bottom - 12 - 5, (int)(dataSize.Width * 1.2 + 0.5), 10);
                    g.DrawString(footer, font, solid, area);


                    g.Flush();

                    font.Dispose();
                    //g.Dispose();
                };

                doc.Print();
            }
        }
Esempio n. 7
0
        private void backgroundWorkerSync_DoWork(object sender, DoWorkEventArgs e)
        {
#if DEBUG
            /*
             * string username = "******";
             * string key = "7a8d5b8e34fc8339f58cc2c8e8353e7f";
             * string baseURL = "http://192.168.0.77:8080/api.dev";
             */
            string username = "******";
            string key      = "a2292cc4096d84751539965522655cff";
            string baseURL  = "http://api.sotubo.pt";
#else
            string username = "******";
            string key      = "a2292cc4096d84751539965522655cff";
            string baseURL  = "http://api.sotubo.pt";
#endif
            WebClient cl = new WebClient();
            cl.Credentials = new NetworkCredential(username, key);
            cl.Encoding    = System.Text.Encoding.UTF8;
            cl.Headers[HttpRequestHeader.Authorization]  = string.Format("Basic {0}:{1}", username, key);
            cl.Headers[HttpRequestHeader.ContentType]    = "application/json;charset=utf-8";
            cl.Headers[HttpRequestHeader.Accept]         = "application / json, text / plain, */*";
            cl.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";


            //RestClient client = new RestClient();
            //client.BaseUrl = new Uri("http://api.sotubo.pt");
            //client.Authenticator = new HttpBasicAuthenticator("sig", "a2292cc4096d84751539965522655cff");
            //client.BaseUrl = new Uri("http://192.168.0.77:8080/api.dev");
            //client.Authenticator = new HttpBasicAuthenticator("ncs", "7a8d5b8e34fc8339f58cc2c8e8353e7f");


            int  campaign_id = -1;
            bool dirty       = false;
            while (!backgroundWorkerSync.CancellationPending && campaign_id < 0)
            {
                try
                {
                    string response = cl.DownloadString(baseURL + "/mrp/count");

                    //RestRequest request = new RestRequest(Method.POST);
                    //request.Resource = "mrp/count";
                    //IRestResponse response = client.Execute(request);
                    if (!string.IsNullOrEmpty(response))
                    {
                        JObject r = JObject.Parse(response);
                        if (r.ContainsKey("result") && r["result"].Value <Int32>() == 1)
                        {
                            JToken jdata = r["jdata"];
                            if (jdata != null)
                            {
                                campaign_id = jdata["id"].Value <Int32>();
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }


                int t = 60;
                while (t-- > 0 || backgroundWorkerSync.CancellationPending)
                {
                    Thread.Sleep(1000);
                }
            }


            SqliteConnector sqlite = DbConnection;

            if (!backgroundWorkerSync.CancellationPending)
            {
                try
                {
                    string response = cl.DownloadString(baseURL + "/mrp/count/locations");

                    //RestRequest request = new RestRequest(Method.POST);
                    //request.Resource = "mrp/count";
                    //IRestResponse response = client.Execute(request);
                    if (!string.IsNullOrEmpty(response))
                    {
                        JObject r = JObject.Parse(response);
                        if (r.ContainsKey("result") && r["result"].Value <Int32>() == 1)
                        {
                            JArray jdata = r["jdata"] as JArray;
                            if (jdata != null && jdata.Count > 0)
                            {
                                using (SQLiteConnection sqliteCon = sqlite.Connect())
                                {
                                    List <Location> existent = sqlite.GetLocations(sqliteCon);

                                    foreach (JObject loc in jdata)
                                    {
                                        string   code        = loc["code"].Value <string>();
                                        string   description = loc["description"].Value <string>();
                                        Location db          = null;
                                        for (int i = 0; i < existent.Count; i++)
                                        {
                                            if (existent[i].Code.Equals(code))
                                            {
                                                db = existent[i];
                                                break;
                                            }
                                        }

                                        if (db == null)
                                        {
                                            //new location record
                                            db             = new Data.Location();
                                            db.Code        = code;
                                            db.Description = description;
                                            sqlite.Insert(sqliteCon, db);
                                        }
                                        else
                                        {
                                            //exists, update it and remove it from existent list so we can later delete it
                                            bool changes = false;
                                            if (!db.Description.Equals(description))
                                            {
                                                db.Description = description;
                                                changes        = true;
                                            }

                                            if (changes)
                                            {
                                                sqlite.Update(sqliteCon, db);
                                            }

                                            existent.Remove(db);
                                        }
                                    }
                                    //the ones that remain in existent list are to be deleted
                                    foreach (Location l in existent)
                                    {
                                        sqlite.Delete(sqliteCon, l);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }


            while (!backgroundWorkerSync.CancellationPending)
            {
                dirty = false;
                try
                {
                    //sync upstream changes
                    long stamp = Properties.Settings.Default.SyncLastUpdate;
                    //RestRequest request = new RestRequest(Method.POST);
                    //request.Resource = string.Format("mrp/count/sync/{0}/{1}", campaign_id, stamp);

                    //IRestResponse response = client.Execute(request);
                    string response = cl.DownloadString(baseURL + string.Format("/mrp/count/sync/{0}/{1}", campaign_id, stamp));
                    if (!string.IsNullOrEmpty(response))
                    {
                        JObject r = JObject.Parse(response);
                        if (r.ContainsKey("result") && r["result"].Value <Int32>() == 1)
                        {
                            JArray jdata = r["jdata"] as JArray;
                            if (jdata != null && jdata.Count > 0)
                            {
                                using (SQLiteConnection sqliteCon = sqlite.Connect())
                                {
                                    foreach (JObject it in jdata)
                                    {
                                        string hash         = it["hash"].Value <string>();
                                        long   update_stamp = it["update"].Value <long>();
                                        if (update_stamp > stamp)
                                        {
                                            stamp = update_stamp;
                                        }

                                        CountEntry en = new CountEntry();
                                        en.Itmref = it["itmref"].Value <string>();
                                        //en.LabelNumber = nextNumber;
                                        en.Value = it["value"].Value <double>();
                                        en.Unit  = it["stu"].Value <string>();
                                        en.Hash  = it["hash"].Value <string>();

                                        long     unixTime = it["time"].Value <long>();
                                        DateTime epoch    = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                                        en.Time      = epoch.AddSeconds(unixTime);
                                        en.IsDeleted = it["deleted"].Value <int>() == 1;
                                        if (en.IsDeleted)
                                        {
                                            en.DeleteKey = DateTime.UtcNow.ToFileTimeUtc();
                                        }
                                        en.SyncCode = it["id"].Value <int>();
                                        en.Sync     = CountEntry.SyncStatus.POSTED;
                                        en.Location = it["location"].Value <string>();

                                        CountEntry ex = sqlite.GetCountEntryByHash(sqliteCon, hash);
                                        if (ex == null)
                                        {
                                            int nextNumber = 0;

                                            List <CountEntry> CountEntries = sqlite.GetCountEntries(sqliteCon, en.Itmref);
                                            nextNumber = CountEntries.Count + 1;
                                            foreach (CountEntry entry in CountEntries)
                                            {
                                                nextNumber = Math.Max(nextNumber, entry.LabelNumber + 1);
                                            }


                                            en.LabelNumber = nextNumber;
                                            sqlite.Insert(sqliteCon, en);
                                            dirty = true;
                                        }
                                        else
                                        {
                                            bool changes = false;
                                            if (!en.Itmref.Equals(ex.Itmref))
                                            {
                                                ex.Itmref = en.Itmref;
                                                changes   = true;
                                            }
                                            if (Math.Abs(en.Value - ex.Value) > 0.001)
                                            {
                                                ex.Value = en.Value;
                                                changes  = true;
                                            }
                                            if (!en.Unit.Equals(ex.Unit))
                                            {
                                                ex.Unit = en.Unit;
                                                changes = true;
                                            }
                                            if (!en.Hash.Equals(ex.Hash))
                                            {
                                                ex.Hash = en.Hash;
                                                changes = true;
                                            }
                                            if (Math.Abs((en.Time - ex.Time).TotalSeconds) > 1)
                                            {
                                                ex.Time = en.Time;
                                                changes = true;
                                            }
                                            if (!en.IsDeleted.Equals(ex.IsDeleted))
                                            {
                                                ex.IsDeleted = en.IsDeleted;
                                                changes      = true;
                                            }
                                            if (!en.SyncCode.Equals(ex.SyncCode))
                                            {
                                                ex.SyncCode = en.SyncCode;
                                                changes     = true;
                                            }
                                            if (!en.Location.Equals(ex.Location))
                                            {
                                                ex.Location = en.Location;
                                                changes     = true;
                                            }

                                            if (changes)
                                            {
                                                sqlite.Update(sqliteCon, ex);
                                                dirty = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (stamp > Properties.Settings.Default.SyncLastUpdate)
                    {
                        Properties.Settings.Default.SyncLastUpdate = stamp;
                        Properties.Settings.Default.Save();
                    }



                    //check for dirty records
                    List <CountEntry> hoes = null;

                    using (SQLiteConnection sqliteCon = sqlite.Connect())
                    {
                        hoes = sqlite.GetDirtyCountEntries(sqliteCon);
                    }
                    if (hoes != null && hoes.Count > 0)
                    {
                        //get current active session if any
                        //request = new RestRequest(Method.POST);
                        //request.Resource = "mrp/count";

                        //response = client.Execute(request);
                        response = cl.DownloadString(baseURL + "/mrp/count");

                        if (!string.IsNullOrEmpty(response))
                        {
                            JObject r = JObject.Parse(response);
                            if (r.ContainsKey("result") && r["result"].Value <Int32>() == 1)
                            {
                                JToken jdata = r["jdata"];
                                if (jdata != null)
                                {
                                    int campaing_id = jdata["id"].Value <Int32>();

                                    //commit changes

                                    foreach (CountEntry en in hoes)
                                    {
                                        Debug.Assert(en.Sync == CountEntry.SyncStatus.NEW);
                                        //we are assuming new to know wich ones to update on local DB

                                        if (en.IsDeleted && en.SyncCode > 0)
                                        {
                                            //delete operation
                                            //request = new RestRequest(Method.POST);
                                            //request.Resource = string.Format("mrp/count/delete/{0}/{1}", campaing_id, en.SyncCode);
                                            //response = client.Execute(request);
                                            response = cl.DownloadString(baseURL + string.Format("/mrp/count/delete/{0}/{1}", campaing_id, en.SyncCode));
                                            r        = JObject.Parse(response);
                                            if (r.ContainsKey("result") && r["result"].Value <Int32>() == 1)
                                            {
                                                en.Sync = CountEntry.SyncStatus.POSTED;
                                            }
                                        }
                                        if (!en.IsDeleted)
                                        {
                                            string url;
                                            //request = new RestRequest(Method.POST);
                                            if (en.SyncCode > 0)
                                            {
                                                //update
                                                //request.Resource = string.Format("mrp/count/update/{0}/{1}", campaing_id, en.SyncCode);
                                                url = baseURL + string.Format("/mrp/count/update/{0}/{1}", campaing_id, en.SyncCode);
                                            }
                                            else
                                            {
                                                //insert
                                                //request.Resource = string.Format("mrp/count/create/{0}/", campaing_id);
                                                url = baseURL + string.Format("/mrp/count/create/{0}", campaing_id);
                                            }

                                            Article a = null;
                                            using (SQLiteConnection sqliteCon = sqlite.Connect())
                                            {
                                                a = sqlite.GetItem(sqliteCon, en.Itmref);
                                            }

                                            JObject parameters = new JObject();
                                            parameters.Add("itmref", en.Itmref);
                                            parameters.Add("itmdes", a == null ? string.Empty : a.Itmdes);
                                            //parameters.Add("itmdes", string.Empty);
                                            parameters.Add("value", en.Value);
                                            parameters.Add("stu", en.Unit);
                                            parameters.Add("operator", "000");
                                            parameters.Add("hash", en.Hash);
                                            parameters.Add("location", en.Location);
                                            parameters.Add("location_data", string.Empty);

                                            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                                            parameters.Add("time", Convert.ToInt64((en.Time - epoch).TotalSeconds));

                                            //response = client.Execute(request);
                                            response = cl.UploadString(url, parameters.ToString());
                                            r        = JObject.Parse(response);
                                            //ignore result because we want to update local record anyway
                                            if (r.ContainsKey("result"))
                                            {
                                                jdata       = r["jdata"];
                                                en.Sync     = CountEntry.SyncStatus.POSTED;
                                                en.SyncCode = jdata["id"].Value <Int32>();
                                            }
                                        }
                                        else
                                        {
                                            en.Sync = CountEntry.SyncStatus.POSTED;
                                        }
                                    }

                                    //update local DB
                                    using (SQLiteConnection sqliteCon = sqlite.Connect())
                                    {
                                        foreach (CountEntry en in hoes)
                                        {
                                            if (en.Sync == CountEntry.SyncStatus.POSTED)
                                            {
                                                sqlite.Update(sqliteCon, en);
                                                dirty = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }


                int t = dirty ? 10 : 60;
                while (t-- > 0 || backgroundWorkerSync.CancellationPending)
                {
                    Thread.Sleep(1000);
                }
            }
        }
Esempio n. 8
0
        private void toolStripButtonImport_Click(object sender, EventArgs e)
        {
            if (openFileDialogImport.ShowDialog(this) == DialogResult.OK)
            {
                string[]          lines = File.ReadAllLines(openFileDialogImport.FileName);
                SqliteConnector   sqlite = DbConnection;
                SQLiteTransaction tr = null;
                int done = 0, total = lines.Length;
                ReportProgress(0, "A importar ficheiro de dados");

                using (SQLiteConnection sqliteCon = sqlite.Connect())
                {
                    try
                    {
                        tr = sqliteCon.BeginTransaction();
                        foreach (string l in lines)
                        {
                            string[] els = l.Split('\t', ';');
                            Debug.Assert(els.Length == 5);
                            if (els.Length != 5)
                            {
                                throw new ArgumentException("Formato de ficheiro invalido");
                            }
                            string   itmref = els[0];
                            string   itmdes = els[1];
                            double   qty    = double.Parse(els[2].Replace('.', ','));
                            string   stu    = els[3];
                            DateTime date   = DateTime.Parse(els[4]);



                            CountEntry en = new CountEntry();
                            en.Itmref = itmref;
                            en.Value  = qty;
                            en.Unit   = stu;
                            en.Time   = date;
                            en.Sync   = CountEntry.SyncStatus.NEW;

                            int nextNumber = 0;

                            List <CountEntry> CountEntries = sqlite.GetCountEntries(sqliteCon, en.Itmref);
                            nextNumber = CountEntries.Count + 1;
                            foreach (CountEntry entry in CountEntries)
                            {
                                nextNumber = Math.Max(nextNumber, entry.LabelNumber + 1);
                            }


                            en.LabelNumber = nextNumber;
                            sqlite.Insert(sqliteCon, en, tr);

                            done++;
                            int progress = (int)(100.0 * done / total);
                            ReportProgress(progress, string.Format("A inserir registo {0} de {1}", done, total));
                        }
                        tr.Commit();
                        ReportProgress(100, "Importacao concluida");
                    }
                    catch (Exception ex)
                    {
                        tr.Rollback();
                        ReportProgress(0, string.IsNullOrEmpty(ex.Message) ? "Erro ao importar ficheiro" : ex.Message);
                    }
                }
            }
        }