public UploadPage()
 {
     first  = true;
     lim    = null;
     dbcon_ = DependencyService.Get <ISQLiteDb>().GetConnection();
     InitializeComponent();
 }
Example #2
0
        public SetupPage( )
        {
            first_ = true;
            InitializeComponent();

            imp_   = new LocalImpo();
            dbcon_ = DependencyService.Get <ISQLiteDb>().GetConnection();

            m_age.FormatString = "N";
            m_age.Culture      = new System.Globalization.CultureInfo("it-IT");

            m_server_picker.Items.Add("Facile - 01");
            m_server_picker.Items.Add("Facile - 02");
            m_server_picker.Items.Add("Facile - 03");

            for (var idx = 0; idx < RsaUtils.max_reg_data; idx++)
            {
                m_reg_picker.Items.Add(RsaUtils.GetRegistroFromOrdinal(idx));
            }

            m_copy_picker.Items.Add("A RICHIESTA");
            m_copy_picker.Items.Add("AUTOMATICA");
            m_copy_picker.Items.Add("NON STAMPARE");

            SetField();
        }
        async void OnAddClicked(object sender, System.EventArgs e)
        {
            var       app = (App)Application.Current;
            LocalImpo lim = null;

            //
            // Leggiamo le impostazioni
            //
            try
            {
                lim = await dbcon_.GetAsync <LocalImpo>(1);
            }
            catch
            {
                await DisplayAlert("Attenzione!", "Impostazioni locali non trovate!\nRiavviare l'App.", "OK");

                return;
            }

            if (lim.dep == 0)
            {
                await DisplayAlert("Attenzione!", "Deposito non impostato!\nEffettuare le impostazioni iniziali.", "OK");

                return;
            }


            try
            {
                var rig = new FatRow();
                rig.rig_tipo  = _parent.doc.fat_tipo;
                rig.rig_n_doc = _parent.doc.fat_n_doc;
                rig.rig_dep   = lim.dep;
                if (app.facile_db_impo != null)
                {
                    rig.rig_iva_inclusa = app.facile_db_impo.dit_iva_inc;
                }
                rig.rig_coef_mol  = 1;
                rig.rig_coef_mol2 = 1;
                var page = new DocumentRow(this, ref rig, -1, _parent.doc.fat_editable);
                await Navigation.PushModalAsync(page);
            }
            catch (Exception ex)
            {
                await DisplayAlert("Attenzione", "Errore : " + ex.Message, "OK");
            }
        }
        public DownloadImages(int start_index, int stop_index)
        {
            first_ = true;
            lim    = null;
            dbcon_ = DependencyService.Get <ISQLiteDb>().GetConnection();
            InitializeComponent();

            Random randomImages = new Random();

            if (Device.RuntimePlatform == Device.Android)
            {
                _max_download = randomImages.Next(400, 1000);
            }
            else
            {
                _max_download = randomImages.Next(250, 400);
            }
        }
Example #5
0
        protected override async void OnAppearing()
        {
            if (first_)
            {
                first_ = false;
                try
                {
                    imp_ = await dbcon_.GetAsync <LocalImpo>(1);
                }
                catch
                {
                    await DisplayAlert("Attenzione!", "Sto configurando il Database.\n\nAttendere qualche secondo e riprovare.", "OK");

                    await Navigation.PopAsync();

                    return;
                }
                SetField();
            }
            base.OnAppearing();
        }
Example #6
0
        protected override async void OnAppearing()
        {
            if (first_appearing_)
            {
                first_appearing_ = false;

                //DependencyService.Get<ISQLiteDb>().RemoveDB();
                var dbcon = DependencyService.Get <ISQLiteDb>().GetConnection();

                await dbcon.CreateTableAsync <FiltersDb>();

                await dbcon.CreateTableAsync <Ditte>();

                await dbcon.CreateTableAsync <Zone>();

                await dbcon.CreateTableAsync <Cateco>();

                await dbcon.CreateTableAsync <Pagamenti>();

                await dbcon.CreateTableAsync <Tabelle>();

                await dbcon.CreateTableAsync <Agenti>();

                await dbcon.CreateTableAsync <Misure>();

                await dbcon.CreateTableAsync <Clienti>();

                await dbcon.CreateTableAsync <Destinazioni>();

                await dbcon.CreateTableAsync <Scadenze>();

                await dbcon.CreateTableAsync <Codiva>();

                await dbcon.CreateTableAsync <Reparti>();

                await dbcon.CreateTableAsync <Catmerc>();

                await dbcon.CreateTableAsync <Fornitori>();

                await dbcon.CreateTableAsync <Depositi>();

                await dbcon.CreateTableAsync <Lotti>();

                await dbcon.CreateTableAsync <Artanag>();

                await dbcon.CreateTableAsync <Listini>();

                await dbcon.CreateTableAsync <Fatture>();

                await dbcon.CreateTableAsync <FatRow>();

                await dbcon.CreateTableAsync <Vettori>();

                await dbcon.CreateTableAsync <Banche>();

                await dbcon.CreateTableAsync <Canali>();

                await dbcon.CreateTableAsync <Stagioni>();

                await dbcon.CreateTableAsync <Marchi>();

                await dbcon.CreateTableAsync <Associazioni>();

                await dbcon.CreateTableAsync <Barcode>();

                await dbcon.CreateTableAsync <Trasporti>();

                await dbcon.CreateTableAsync <Agganci>();

                await dbcon.CreateTableAsync <Descrizioni>();

                await dbcon.CreateTableAsync <LocalImpo>();

                await dbcon.CreateTableAsync <ScaPagHead>();

                await dbcon.CreateTableAsync <ScaPagRow>();

                await dbcon.CreateTableAsync <Images>();

                await dbcon.CreateTableAsync <ArtCounter>();

                if (await dbcon.Table <LocalImpo>().CountAsync() == 0)
                {
                    var imp = new LocalImpo();
                    imp.id = 1;
                    await dbcon.InsertAsync(imp);
                }

                try
                {
                    var app     = (App)Application.Current;
                    var ditlist = await dbcon.QueryAsync <Ditte>("SELECT * FROM ditt2016 ORDER BY dit_codice LIMIT 1");

                    if (ditlist.Count == 0)
                    {
                        app.facile_db_impo = null;
                    }
                    else
                    {
                        app.facile_db_impo = ditlist[0];

                        //
                        // Conversione campi ditta
                        //
                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_sco) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_sco_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_sco = dit_reg_sco_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_sco_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_sco      = app.facile_db_impo.dit_reg_sco_free;
                            app.facile_db_impo.dit_reg_sco_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_car) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_car_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_car = dit_reg_car_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_car_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_car      = app.facile_db_impo.dit_reg_car_free;
                            app.facile_db_impo.dit_reg_car_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_fat) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_fat_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_fat = dit_reg_fat_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_fat_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_fat      = app.facile_db_impo.dit_reg_fat_free;
                            app.facile_db_impo.dit_reg_fat_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_ddt) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_ddt_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_ddt = dit_reg_ddt_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_ddt_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_ddt      = app.facile_db_impo.dit_reg_ddt_free;
                            app.facile_db_impo.dit_reg_ddt_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_bol) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_bol_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_bol = dit_reg_bol_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_bol_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_bol      = app.facile_db_impo.dit_reg_bol_free;
                            app.facile_db_impo.dit_reg_bol_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_buo) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_buo_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_buo = dit_reg_buo_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_buo_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_buo      = app.facile_db_impo.dit_reg_buo_free;
                            app.facile_db_impo.dit_reg_buo_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_acc) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_acc_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_acc = dit_reg_acc_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_acc_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_acc      = app.facile_db_impo.dit_reg_acc_free;
                            app.facile_db_impo.dit_reg_acc_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_ric) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_ric_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_ric = dit_reg_ric_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_ric_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_ric      = app.facile_db_impo.dit_reg_ric_free;
                            app.facile_db_impo.dit_reg_ric_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_ord) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_ord_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_ord = dit_reg_ord_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_ord_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_ord      = app.facile_db_impo.dit_reg_ord_free;
                            app.facile_db_impo.dit_reg_ord_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_pre) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_pre_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_pre = dit_reg_pre_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_pre_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_pre      = app.facile_db_impo.dit_reg_pre_free;
                            app.facile_db_impo.dit_reg_pre_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_ofo) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_ofo_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_ofo = dit_reg_ofo_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_ofo_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_ofo      = app.facile_db_impo.dit_reg_ofo_free;
                            app.facile_db_impo.dit_reg_ofo_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_auf) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_auf_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_auf = dit_reg_auf_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_auf_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_auf      = app.facile_db_impo.dit_reg_auf_free;
                            app.facile_db_impo.dit_reg_auf_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_fpf) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_fpf_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_fpf = dit_reg_fpf_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_fpf_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_fpf      = app.facile_db_impo.dit_reg_fpf_free;
                            app.facile_db_impo.dit_reg_fpf_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_oro) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_oro_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_oro = dit_reg_oro_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_oro_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_oro      = app.facile_db_impo.dit_reg_oro_free;
                            app.facile_db_impo.dit_reg_oro_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_fat_pa) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_fat_pa_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_fat_pa = dit_reg_fat_pa_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_fat_pa_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_fat_pa      = app.facile_db_impo.dit_reg_fat_pa_free;
                            app.facile_db_impo.dit_reg_fat_pa_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_cre_pa) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_cre_pa_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_cre_pa = dit_reg_cre_pa_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_cre_pa_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_cre_pa      = app.facile_db_impo.dit_reg_cre_pa_free;
                            app.facile_db_impo.dit_reg_cre_pa_free = string.Empty;
                        }

                        if (string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_ano) && !string.IsNullOrWhiteSpace(app.facile_db_impo.dit_reg_ano_free))
                        {
                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_ano = dit_reg_ano_free WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            await dbcon.ExecuteAsync($"UPDATE ditt2016 SET dit_reg_ano_free = '' WHERE dit_codice = {app.facile_db_impo.dit_codice}");

                            app.facile_db_impo.dit_reg_ano      = app.facile_db_impo.dit_reg_ano_free;
                            app.facile_db_impo.dit_reg_ano_free = string.Empty;
                        }

                        //
                        // Conversione Campi documenti
                        //
                        await dbcon.ExecuteAsync($"UPDATE fatture2 SET fat_registro = fat_registro_free WHERE TRIM(fat_registro) = '' AND TRIM(fat_registro_free) != ''");

                        await dbcon.ExecuteAsync($"UPDATE fatture2 SET fat_registro_free = '' WHERE TRIM(fat_registro_free) != ''");
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }
            }
            base.OnAppearing();
        }
        async void OnRecordStampa(object sender, System.EventArgs e)
        {
            bool      stprice  = true;
            LocalImpo imp      = null;
            short     num_copy = 1;
            short     max_copy = 1;
            bool      req_copy = false;

            m_stampa.IsEnabled = false;
            GetField();
            var animation = busyIndicator.AnimationType;

            busyIndicator.IsBusy        = true;
            busyIndicator.AnimationType = Syncfusion.SfBusyIndicator.XForms.AnimationTypes.Print;

            if (_parent.doc.fat_inte == 0L)
            {
                busyIndicator.IsBusy = true;
                m_cli_cod.Focus();
                m_stampa.IsEnabled = true;
                return;
            }

            //
            // Ricalcoliamo il documento
            //
            try
            {
                await _parent.doc.RecalcAsync();

                await _dbcon.UpdateAsync(_parent.doc);
            }
            catch (SQLiteException ex)
            {
                busyIndicator.IsBusy = true;
                await DisplayAlert("Attenzione!", ex.Message, "OK");

                m_stampa.IsEnabled = true;
                return;
            }
            catch (Exception ex)
            {
                busyIndicator.IsBusy = true;
                await DisplayAlert("Errore", ex.Message, "OK");

                m_stampa.IsEnabled = true;
                return;
            }

            //
            // Leggiamo le impostazioni della stampante
            //
            try
            {
                imp = await _dbcon.GetAsync <LocalImpo>(1);

                switch (imp.seconda_copia)
                {
                case 0:                           // A Rchiesta
                    max_copy = 2;
                    num_copy = 1;
                    req_copy = true;
                    break;

                case 1:                           // Stampa automatica
                    max_copy = 1;
                    num_copy = 2;
                    req_copy = false;
                    break;

                default:                          // Non Stampare la seconda copia
                    max_copy = 1;
                    num_copy = 1;
                    req_copy = false;
                    break;
                }
            }
            catch
            {
                await DisplayAlert("Attenzione!", "Impossibile leggere le impostazioni della stampante", "OK");

                busyIndicator.IsBusy = true;
                m_stampa.IsEnabled   = true;
                return;
            }
            if (string.IsNullOrWhiteSpace(imp.printer))
            {
                await DisplayAlert("Attenzione!", "Nessuna stampante configurata.", "OK");

                busyIndicator.IsBusy = true;
                m_stampa.IsEnabled   = true;
                return;
            }

            if (_parent.doc.fat_tipo == (short)DocTipo.TIPO_DDT)
            {
                stprice = await DisplayAlert("Facile", "Vuoi Stampare i Prezzi ?", "SI", "NO");

                await Task.Delay(100);
            }

            try
            {
                if (Device.RuntimePlatform == Device.iOS)
                {
                    for (var idx = 0; idx < max_copy; idx++)
                    {
                        if (idx != 0 && req_copy)
                        {
                            var test = await DisplayAlert("Attenzione...", "Vuoi stampare un'altra copia?", "Si", "No");

                            if (test == false)
                            {
                                break;
                            }
                            await Task.Delay(100);
                        }
                        var t = Task.Run(async() =>
                        {
                            var prn = new ZebraPrn(imp.printer);
                            await prn.PrintDoc(_parent.doc, stprice, num_copy);
                        });
                        t.Wait();
                    }
                }
                else if (Device.RuntimePlatform == Device.Android)
                {
                    var prn = new ZebraPrn(imp.printer);
                    for (var idx = 0; idx < max_copy; idx++)
                    {
                        if (idx != 0 && req_copy)
                        {
                            var test = await DisplayAlert("Attenzione...", "Vuoi stampare un'altra copia?", "Si", "No");

                            if (test == false)
                            {
                                break;
                            }
                            await Task.Delay(100);
                        }
                        await prn.PrintDoc(_parent.doc, stprice, num_copy);
                    }
                }
            }
            catch (ZebraExceptions ex)
            {
                await DisplayAlert("Errore", ex.Message, "ok");
            }
            catch (Exception ex)
            {
                await DisplayAlert("Errore", ex.Message, "ok");
            }

            busyIndicator.IsBusy        = false;
            busyIndicator.AnimationType = animation;
            m_stampa.IsEnabled          = true;
        }
Example #8
0
        async void OnAggiungiClicked(object sender, System.EventArgs e)
        {
            var       fat = new Fatture();
            LocalImpo lim = null;
            Agenti    age = null;

            SQLiteAsyncConnection dbcon_ = DependencyService.Get <ISQLiteDb>().GetConnection();

            busyIndicator.IsBusy = true;

            //
            // Leggiamo le impostazioni
            //
            try
            {
                lim = await dbcon_.GetAsync <LocalImpo>(1);
            }
            catch
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", "Impostazioni locali non trovate!\nRiavviare l'App.", "OK");

                return;
            }

            if (!lim.data_download)
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", "Dati non presenti sul dispositivo!\nPer procedere ĆØ necessario scaricare i dati dal server.", "OK");

                return;
            }
            if (string.IsNullOrWhiteSpace(lim.registro))
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", "Registro non impostato!\nPer inserire documenti ĆØ necessario fare le impostazioni iniziali.", "OK");

                return;
            }
            if (lim.age == 0)
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", "Agente non impostato!\nPer inserire documenti ĆØ necessario fare le impostazioni iniziali.", "OK");

                return;
            }
            if (lim.dep == 0)
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", "Deposito non impostato!\nPer inserire documenti ĆØ necessario fare le impostazioni iniziali.", "OK");

                return;
            }


            //
            // Leggiamo i dati dell' agente
            //
            try
            {
                age = await dbcon_.GetAsync <Agenti>(lim.age);
            }
            catch
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", "L' Agente impostato non ĆØ presente in archivio!", "OK");

                return;
            }

            bool nuova = true;

            //
            // Inizializziamo il documento
            //
            fat.fat_n_doc     = 1;
            fat.fat_tipo      = (short)tipo_;
            fat.fat_registro  = lim.registro;
            fat.fat_d_doc     = DateTime.Now;
            fat.fat_editable  = true;
            fat.fat_local_doc = true;
            fat.fat_age       = lim.age;

            try
            {
                fat.fat_n_doc = 1;
                var sql  = string.Format("SELECT * FROM fatture2 WHERE fat_tipo = {0} AND fat_n_doc > {1} AND fat_n_doc <= {2} ORDER BY fat_n_doc DESC LIMIT 1", (short)tipo_, RsaUtils.GetFirstRegNumber(lim.registro), RsaUtils.GetLastRegNumber(lim.registro));
                var list = await dbcon_.QueryAsync <Fatture>(sql);

                foreach (var doc in list)
                {
                    fat.fat_n_doc += doc.fat_n_doc;
                    break;
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Attenzione!", ex.Message, "OK");

                return;
            }
            var page = new DocumentiEdit(ref fat, ref nuova);
            await Navigation.PushAsync(page);

            busyIndicator.IsBusy = false;
        }
        private async Task Download()
        {
            int num_download = 0;

            //
            // Leggiamo le impostazioni
            //
            try
            {
                lim = await dbcon_.GetAsync <LocalImpo>(1);
            }
            catch
            {
                await DisplayAlert("Attenzione!", "Impostazioni locali non trovate!\nRiavviare l'App.", "OK");

                await Navigation.PopModalAsync();

                return;
            }

            if (string.IsNullOrWhiteSpace(lim.ftpServer))
            {
                await DisplayAlert("Attenzione!", "Server non impostato o non valido.", "OK");

                await Navigation.PopModalAsync();

                return;
            }
            if (string.IsNullOrWhiteSpace(lim.user))
            {
                await DisplayAlert("Attenzione!", "Utente non impostato o non valido.", "OK");

                await Navigation.PopModalAsync();

                return;
            }

            string password     = "";
            string remoteServer = "";

            if (lim.ftpServer == "Facile - 01")
            {
                remoteServer = "ftp://www.facile2013.it/images/";
            }

            if (lim.ftpServer == "Facile - 02")
            {
                remoteServer = "ftp://www.rsaweb.com/images/";
            }

            if (lim.ftpServer == "Facile - 03")
            {
                remoteServer = "ftp://www.facilecloud.com/images/";
            }

            if (remoteServer == "")
            {
                throw new Exception("Server non impostato o non valido");
            }

            if (lim.user != "demo2017")
            {
                password = $"$_{lim.user}_$";
            }
            else
            {
                password = lim.user;
            }

            try
            {
                IFolder rootFolder   = FileSystem.Current.LocalStorage;
                IFolder imagesFolder = await rootFolder.CreateFolderAsync("images", CreationCollisionOption.OpenIfExists);

                m_desc.Text = "Otteniamo la lista dei files... ";
                var ftp   = DependencyService.Get <IFtpWebRequest>();
                var files = await ftp.ListDirectory(lim.user, password, remoteServer);

                if (files != null && files.Count > 0)
                {
                    int  idx  = 0;
                    bool stop = false;

                    foreach (var file in files)
                    {
                        String remoteFile = remoteServer + file.Name;
                        String localFile  = imagesFolder.Path + "/" + file.Name;

                        if (stop)
                        {
                            break;
                        }

                        if (num_download > _max_download)
                        {
                            throw new RsaException(RsaException.ImagesMsg, RsaException.ImageErr);
                        }

                        bool skip = true;
                        var  x    = file.Name.LastIndexOf('.');

                        if (x >= 0)
                        {
                            var ext = file.Name.Substring(x);
                            if (ext.ToUpper() == ".JPG" || ext.ToUpper() == ".PNG" || ext.ToUpper() == ".PRN")
                            {
                                skip = false;
                            }

                            //
                            // Controllare qui se si vuole la presenza dell'articolo
                            //
                            if (ext.ToUpper() == ".JPG" || ext.ToUpper() == ".PNG")
                            {
                                x = file.Name.LastIndexOf('_');
                                if (x > 0)
                                {
                                    var code = file.Name.Substring(0, x).Trim().ToUpper();
                                    var sql  = string.Format("SELECT COUNT(*) FROM artanag WHERE ana_codice = {0}", code.SqlQuote(false));
                                    var rec  = await dbcon_.ExecuteScalarAsync <int>(sql);

                                    if (rec == 0)
                                    {
                                        skip = true;
                                    }
                                }

                                //
                                // Controlliamo il timestamp
                                //
                                if (!skip && file.LastUpdate.HasValue)
                                {
                                    try
                                    {
                                        var img = await dbcon_.GetAsync <Images>(file.Name.ToUpper());

                                        if (img.img_last_update.HasValue)
                                        {
                                            if (DateTime.Compare(file.LastUpdate.Value, img.img_last_update.Value) <= 0)
                                            {
                                                skip = true;
                                            }
                                        }
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                        }
                        idx++;

                        if (skip)
                        {
                            m_desc.Text = string.Format("Salto {0} di {1} - {2}", idx, files.Count, file.Name);
                        }
                        else
                        {
                            m_desc.Text = string.Format("Scarico {0} di {1} - {2}", idx, files.Count, file.Name);
                            var result = await ftp.DownloadFile(lim.user, password, remoteFile, localFile);

                            if (!result.StartsWith("2", StringComparison.CurrentCulture))
                            {
                                for (int retry = 0; retry < 5; retry++)
                                {
                                    result = await ftp.DownloadFile(lim.user, password, remoteFile, localFile);

                                    if (result.StartsWith("2", StringComparison.CurrentCulture))
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        if (idx == 4)
                                        {
                                            var str = "Impossibile scaricare il file : " + file.Name + "\n\nVuoi continuare?";
                                            stop = !(await DisplayAlert("Errore", str, "SI", "NO"));
                                        }
                                    }
                                }
                            }
                            num_download++;
                            Images image = new Images
                            {
                                img_name        = file.Name.ToUpper(),
                                img_last_update = file.LastUpdate
                            };
                            await dbcon_.InsertOrReplaceAsync(image);

                            m_image.Source = localFile;
                        }
                    }
                }
                m_desc.Text = "";
                await DisplayAlert("Facile", "Importazione dati conclusa!", "Ok");
            }
            catch (RsaException ex)
            {
                await DisplayAlert("Download Error", ex.Message, "OK");
            }
            catch (Exception ex)
            {
                await DisplayAlert("Download Error", ex.Message, "OK");
            }
            await Navigation.PopModalAsync();
        }
Example #10
0
        async void OnSalvaClicked(object sender, System.EventArgs e)
        {
            //if (await DisplayAlert("Attenzione", "Vuoi inviare un messaggio alla sede?", "Si", "No"))
            //{
            //	var recipients = new List<string>();
            //	recipients.Add("*****@*****.**");
            //	recipients.Add("*****@*****.**");


            //	try
            //	{
            //		var message = new EmailMessage
            //		{
            //			Subject = "Incasso",
            //			To = recipients,
            //			//Cc = ccRecipients,
            //			//Bcc = bccRecipients
            //		};

            //		message.BodyFormat = EmailBodyFormat.Html;

            //		message.Body = string.Format("<body><h1>Incasso</h1><p>Cliente {0}</p>", m_cli_des.Text);

            //		string str = "<table><tr><td>Data</td><td>Num. Doc.</td><td>Importo Doc</td><td>Importo Scadenza</td><td>Incasso</td></tr>";


            //		message.Body = message.Body + str + "</table></body>";

            //		await Email.ComposeAsync(message);
            //	}
            //	catch (FeatureNotSupportedException fbsEx)
            //	{
            //		await DisplayAlert("Attenzione", "Non supportato : " + fbsEx.Message, "OK");
            //	}
            //	catch (Exception ex)
            //	{
            //		await DisplayAlert("Attenzione", ex.Message, "OK");
            //	}

            //}
            //return;

            double incasso = 0.0;
            int    num_sca = 0;

            foreach (var item in dataGrid.View.Records)
            {
                var rowData = (IncassiInfo)item.Data;

                if (!rowData.sca_incasso.TestIfZero(2))
                {
                    incasso += rowData.sca_incasso;
                    num_sca++;
                }
            }
            if (num_sca == 0)
            {
                await DisplayAlert("Attenzione", "Non ĆØ stato inserito alcun importo da incassare!", "OK");

                return;
            }
            else
            {
                bool confirm = await DisplayAlert("Attenzione", "Confermi l'incasso di ā‚¬" + incasso + " ?", "Si", "No");

                if (!confirm)
                {
                    return;
                }
            }

            //
            // Leggiamo le impostazioni
            //
            var       app = (App)Application.Current;
            LocalImpo lim = null;

            try
            {
                lim = await _dbcon.GetAsync <LocalImpo>(1);
            }
            catch
            {
                await DisplayAlert("Attenzione!", "Impostazioni locali non trovate!\nRiavviare l'App.", "OK");

                return;
            }
            if (lim.age == 0)
            {
                await DisplayAlert("Attenzione!", "Codice Agente non impostato!\nEffettuare le impostazioni iniziali.", "OK");

                return;
            }

            //
            // Inseriamo la testata della distinta di Incasso
            //
            var dsp = new ScaPagHead
            {
                dsp_relaz       = 0,
                dsp_codice      = 0,
                dsp_clifor      = Convert.ToInt32(m_cli_cod.Text),
                dsp_data        = DateTime.Now,
                dsp_data_sel    = null,
                dsp_mas         = 0,
                dsp_con         = 0,
                dsp_sot         = 0,
                dsp_totale      = incasso,
                dsp_des_con     = "",
                dsp_mezzo       = 0,           // Cassa
                dsp_codass      = 0,
                dsp_oldass      = 0,
                dsp_pnota       = 0,
                dsp_dst         = string.IsNullOrWhiteSpace(m_dst_cod.Text) ? 0 : Convert.ToInt32(m_dst_cod.Text),
                dsp_abbuoni     = 0.0,
                dsp_age         = lim.age,
                dsp_sez         = 1,
                dsp_ass         = 0,
                dsp_sez_sca     = 0,
                dsp_nonconf     = 0,
                dsp_timeid      = DateTime.Now,
                dsp_codppc      = 0,
                dsp_parked      = 0,
                dsp_data_ass    = null,
                dsp_user        = "",
                dsp_last_update = DateTime.Now,
                dsp_immediato   = false,
                dsp_inviato     = false
            };

            try
            {
                await _dbcon.InsertAsync(dsp);
            }
            catch (Exception ex)
            {
                await DisplayAlert("Errore", "Impossibile inserire testata : " + ex.Message, "OK");

                return;
            }

            //
            // Inseriamo le righe incassate
            //
            int idx = 0;

            foreach (var item in dataGrid.View.Records)
            {
                idx++;
                var rowData = (IncassiInfo)item.Data;
                if (!rowData.sca_incasso.TestIfZero(2))
                {
                    try
                    {
                        var sca = await _dbcon.GetAsync <Scadenze>(rowData.sca_id);

                        var dsr = new ScaPagRow
                        {
                            dsr_id          = 0,
                            dsr_relaz       = dsp.dsp_relaz,
                            dsr_codice      = dsp.dsp_codice,
                            dsr_rel_sca     = sca.sca_relaz,
                            dsr_num_sca     = sca.sca_num,
                            dsr_data        = sca.sca_data,
                            dsr_old_num_doc = "",
                            dsr_d_doc       = sca.sca_data_fattura,
                            dsr_tot_doc     = sca.sca_tot_fat,
                            dsr_importo     = sca.sca_importo,
                            dsr_paginc      = rowData.sca_incasso,
                            dsr_idx         = idx,
                            dsr_sez         = sca.sca_sez,
                            dsr_user        = "",
                            dsr_last_update = DateTime.Now,
                            dsr_num_doc     = sca.sca_fattura
                        };

                        try
                        {
                            await _dbcon.InsertAsync(dsr);

                            var resto = sca.sca_importo - rowData.sca_incasso;
                            if (!resto.TestIfZero(2))
                            {
                                try
                                {
                                    sca.sca_importo = rowData.sca_incasso;
                                    sca.sca_pagato  = 1;
                                    sca.sca_cont    = 1;
                                    await _dbcon.UpdateAsync(sca);

                                    sca.sca_id  = 0;
                                    sca.sca_num = 1 + await _dbcon.ExecuteScalarAsync <int>("SELECT MAX(sca_num) FROM scadenze WHERE sca_relaz = 0");

                                    sca.sca_pagato  = 0;
                                    sca.sca_cont    = 0;
                                    sca.sca_importo = resto;
                                    sca.sca_locked  = 1;
                                    await _dbcon.InsertAsync(sca);
                                }
                                catch (Exception ex)
                                {
                                    await DisplayAlert("Errore", "Impossibile aggiornare la scadenza : " + ex.Message, "OK");
                                }
                            }
                            else
                            {
                                try
                                {
                                    sca.sca_pagato = 1;
                                    sca.sca_cont   = 1;
                                    await _dbcon.UpdateAsync(sca);
                                }
                                catch (Exception ex)
                                {
                                    await DisplayAlert("Errore", "Impossibile aggiornare la scadenza : " + ex.Message, "OK");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            await DisplayAlert("Errore", "Impossibile inserire riga : " + ex.Message, "OK");
                        }
                    }
                    catch
                    {
                        await DisplayAlert("Attenzione!", "Scadenza non trovata in archivio!", "OK");
                    }
                }
            }


            m_cli_cod.Text = "";
            m_cli_des.Text = "";

            m_dst_cod.Text       = "";
            m_dst_des.Text       = "";
            dataGrid.ItemsSource = null;

            m_search_cli.Focus();
        }
        private async Task Upload()
        {
            int cli_rec = 0;
            int dst_rec = 0;
            int rig_rec = 0;

            //
            // Leggiamo le impostazioni
            //
            try
            {
                lim = await dbcon_.GetAsync <LocalImpo>(1);
            }
            catch
            {
                await DisplayAlert("Attenzione!", "Impostazioni locali non trovate!\nRiavviare l'App.", "OK");

                await Navigation.PopModalAsync();

                return;
            }

            if (string.IsNullOrWhiteSpace(lim.ftpServer))
            {
                await DisplayAlert("Attenzione!", "Server non impostato o non valido.", "OK");

                await Navigation.PopModalAsync();

                return;
            }
            if (string.IsNullOrWhiteSpace(lim.user))
            {
                await DisplayAlert("Attenzione!", "Utente non impostato o non valido.", "OK");

                await Navigation.PopModalAsync();

                return;
            }
            if (lim.age == 0)
            {
                await DisplayAlert("Attenzione!", "Agente non impostato o non valido.", "OK");

                await Navigation.PopModalAsync();

                return;
            }

            busyIndicator.IsBusy        = true;
            busyIndicator.AnimationType = AnimationTypes.Ball;
            busyIndicator.Title         = "Estrazione Documenti";

            var docList = new List <Documento>();


            m_doc_ext.Source = "ic_hourglass_full_white.png";
            m_rig_ext.Source = "ic_hourglass_full_white.png";
            m_cli_ext.Source = "ic_hourglass_full_white.png";
            m_dst_ext.Source = "ic_hourglass_full_white.png";


            m_doc.FontSize  = m_doc.FontSize + 3;
            m_doc.TextColor = Color.Red;

            var sql     = "SELECT * FROM fatture2 WHERE fat_local_doc = 1";
            var fatList = await dbcon_.QueryAsync <Fatture>(sql);

            if (fatList.Count == 0)
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", "Non ci sono documenti da inviare alla sede.", "OK");

                await Navigation.PopModalAsync();

                return;
            }

            m_doc_rec.Text  = $"{fatList.Count}";
            m_doc.FontSize  = m_doc.FontSize - 3;
            m_doc.TextColor = Color.White;

            busyIndicator.AnimationType = AnimationTypes.Gear;
            busyIndicator.Title         = "Estrazione Dati Documenti";
            foreach (var fat in fatList)
            {
                var doc = new Documento();
                doc.documento = fat;

                //
                // Inseriamo i dati del cliente
                //
                m_cli.FontSize  = m_cli.FontSize + 3;
                m_cli.TextColor = Color.Red;
                try
                {
                    cli_rec++;
                    doc.cliente = await dbcon_.GetAsync <Clienti>(fat.fat_inte);
                }
                catch
                {
                    throw new RsaException(RsaException.NotFoundMsg, RsaException.NotFoundErr);
                }
                m_cli_rec.Text  = $"{cli_rec}";
                m_cli.FontSize  = m_cli.FontSize - 3;
                m_cli.TextColor = Color.White;


                //
                // Inseriamo i dati del destinatario
                //
                if (fat.fat_dest != 0)
                {
                    m_dst.FontSize  = m_dst.FontSize + 3;
                    m_dst.TextColor = Color.Red;

                    try
                    {
                        dst_rec++;
                        doc.destinazione = await dbcon_.GetAsync <Destinazioni>(fat.fat_dest);
                    }
                    catch
                    {
                        throw new RsaException(RsaException.NotFoundMsg, RsaException.NotFoundErr);
                    }
                    m_dst.FontSize  = m_dst.FontSize - 3;
                    m_dst.TextColor = Color.White;
                }
                m_dst_rec.Text = $"{dst_rec}";

                //
                // Inseriamo le righe dei documenti
                //
                m_rig.FontSize  = m_rig.FontSize + 3;
                m_rig.TextColor = Color.Red;

                sql       = string.Format("SELECT * from fatrow2 WHERE rig_tipo = {0} AND rig_n_doc = {1} ORDER BY rig_tipo, rig_n_doc, rig_d_ins, rig_t_ins", fat.fat_tipo, fat.fat_n_doc);
                doc.righe = await dbcon_.QueryAsync <FatRow>(sql);

                m_rig.FontSize  = m_rig.FontSize - 3;
                m_rig.TextColor = Color.White;

                rig_rec       += doc.righe.Count;
                m_rig_rec.Text = $"{rig_rec}";

                if (doc.righe.Count == 0)
                {
                    sql = "";
                    busyIndicator.IsBusy = true;
                    switch (fat.fat_tipo)
                    {
                    case (short)DocTipo.TIPO_FAT:
                        sql = string.Format("La fattura N. {0}/{1} non contiene righe!\n\nVuoi continuare?", RsaUtils.GetShowedNumDoc(fat.fat_n_doc), fat.fat_registro);
                        break;

                    case (short)DocTipo.TIPO_DDT:
                        sql = string.Format("Il DDT N. {0}/{1} non contiene righe!\n\nVuoi continuare?", RsaUtils.GetShowedNumDoc(fat.fat_n_doc), fat.fat_registro);
                        break;

                    case (short)DocTipo.TIPO_ORD:
                        sql = string.Format("L' Ordine N. {0}/{1} non contiene righe!\n\nVuoi continuare?", RsaUtils.GetShowedNumDoc(fat.fat_n_doc), fat.fat_registro);
                        break;

                    default:
                        sql = string.Format("Il Documento N. {0}/{1} (Tipo - {2}) non contiene righe!\n\nVuoi continuare?", RsaUtils.GetShowedNumDoc(fat.fat_n_doc), fat.fat_registro, fat.fat_tipo);
                        break;
                    }
                    var test = await DisplayAlert("Attenzone", sql, "SI", "NO");

                    if (!test)
                    {
                        await Navigation.PopModalAsync();

                        return;
                    }
                }

                //
                // Aggiungiamo il documento alla lista di quelli esportati
                //
                docList.Add(doc);
            }
            m_doc_ext.Source = "ic_storage_black.png";
            m_rig_ext.Source = "ic_storage_black.png";
            m_cli_ext.Source = "ic_storage_black.png";
            m_dst_ext.Source = "ic_storage_black.png";

            //
            // Creiamo il file
            //
            m_doc_json.Source = "ic_hourglass_full_white.png";
            m_rig_json.Source = "ic_hourglass_full_white.png";
            m_cli_json.Source = "ic_hourglass_full_white.png";
            m_dst_json.Source = "ic_hourglass_full_white.png";

            busyIndicator.AnimationType = AnimationTypes.DoubleCircle;
            busyIndicator.Title         = "Serializzazione";

            //sql = JsonConvert.SerializeObject(docList, Formatting.Indented);

            IFolder rootFolder = FileSystem.Current.LocalStorage;
            String  localJson  = rootFolder.Path + "/" + "DOCUMENTI" + ".JSON";

            IFile json_file = await rootFolder.CreateFileAsync(localJson, CreationCollisionOption.ReplaceExisting);

            await json_file.WriteAllTextAsync(JsonConvert.SerializeObject(docList, Formatting.Indented));

            m_doc_json.Source = "ic_code_black.png";
            m_rig_json.Source = "ic_code_black.png";
            m_cli_json.Source = "ic_code_black.png";
            m_dst_json.Source = "ic_code_black.png";

            m_doc_upload.Source = "ic_file_download_black.png";
            m_rig_upload.Source = "ic_file_download_black.png";
            m_cli_upload.Source = "ic_file_download_black.png";
            m_dst_upload.Source = "ic_file_download_black.png";

            //
            // Trasmettiamo il file
            //
            busyIndicator.AnimationType = AnimationTypes.Globe;
            busyIndicator.Title         = "Trasmissione";

            string password     = "";
            string remoteServer = "";

            if (lim.ftpServer == "Facile - 01")
            {
                remoteServer = "ftp://www.facile2013.it";
            }

            if (lim.ftpServer == "Facile - 02")
            {
                remoteServer = "ftp://www.rsaweb.com";
            }

            if (lim.ftpServer == "Facile - 03")
            {
                remoteServer = "ftp://www.facilecloud.com";
            }

            if (remoteServer == "")
            {
                throw new Exception("Server non impostato o non valido");
            }

            if (lim.user != "demo2017")
            {
                password = $"$_{lim.user}_$";
            }
            else
            {
                password = lim.user;
            }

            var remotePath = $"/{lim.age}/out";

            m_doc_upload.Source = "ic_hourglass_full_white.png";
            m_rig_upload.Source = "ic_hourglass_full_white.png";
            m_cli_upload.Source = "ic_hourglass_full_white.png";
            m_dst_upload.Source = "ic_hourglass_full_white.png";

            var    ftp    = DependencyService.Get <IFtpWebRequest>();
            string result = await ftp.UploadFile(remoteServer, localJson, lim.user, password, remotePath);

            busyIndicator.IsBusy = false;
            if (result.StartsWith("2", StringComparison.CurrentCulture))
            {
                m_doc_upload.Source = "ic_cloud_black.png";
                m_rig_upload.Source = "ic_cloud_black.png";
                m_cli_upload.Source = "ic_cloud_black.png";
                m_dst_upload.Source = "ic_cloud_black.png";


                m_doc.TextColor = Color.Black;
                m_rig.TextColor = Color.Black;
                m_cli.TextColor = Color.Black;
                m_dst.TextColor = Color.Black;

                //
                // Marchiamo i documenti come non piĆ¹ editabili
                //
                foreach (var fat in fatList)
                {
                    fat.fat_editable = false;
                }
                await dbcon_.UpdateAllAsync(fatList);
                await DisplayAlert("Facile", "Invio documenti concluso con successo!", "OK");
            }
            else if (result.StartsWith("530", StringComparison.CurrentCulture))
            {
                await DisplayAlert("Facile", "Parametri di Login non validi!\nVerificare il nome utente configurato.", "OK");
            }
            else if (result.StartsWith("System.Net.WebException", StringComparison.CurrentCulture))
            {
                await DisplayAlert("Facile", result, "OK");
            }
            else
            {
                await DisplayAlert("Facile", "Impossibile caricare il file sul server!", "OK");
            }

            //
            // Rimuoviamo il file
            //
            await json_file.DeleteAsync();

            await Navigation.PopModalAsync();
        }
        private async Task Download()
        {
            busyIndicator.IsBusy = true;

            //
            // Leggiamo le impostazioni
            //
            try
            {
                lim = await dbcon_.GetAsync <LocalImpo>(1);
            }
            catch
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", "Impostazioni locali non trovate!\nRiavviare l'App.", "OK");

                await Navigation.PopModalAsync();

                return;
            }

            try
            {
                lim.data_download = false;
                await dbcon_.UpdateAsync(lim);
            }
            catch (Exception ex)
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", ex.Message, "OK");

                await Navigation.PopModalAsync();

                return;
            }

            if (string.IsNullOrWhiteSpace(lim.ftpServer))
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", "Server non impostato o non valido.", "OK");

                await Navigation.PopModalAsync();

                return;
            }
            if (string.IsNullOrWhiteSpace(lim.user))
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", "Utente non impostato o non valido.", "OK");

                await Navigation.PopModalAsync();

                return;
            }
            if (lim.age == 0)
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Attenzione!", "Agente non impostato o non valido.", "OK");

                await Navigation.PopModalAsync();

                return;
            }

            List <Fatture> docList = null;
            List <FatRow>  rigList = null;

            try
            {
                busyIndicator.Title = "Effettuo Backup...";

                IFolder rootFolder = FileSystem.Current.LocalStorage;
                String  docJson    = rootFolder.Path + "/" + "DOCBACKUP" + ".JSON";
                String  rigJson    = rootFolder.Path + "/" + "RIGBACKUP" + ".JSON";

                //
                // Leggiamo i dati se esistono i file di backup su disco
                //
                ExistenceCheckResult doc_exist = await rootFolder.CheckExistsAsync(docJson);

                ExistenceCheckResult rig_exist = await rootFolder.CheckExistsAsync(rigJson);

                if (doc_exist == ExistenceCheckResult.FileExists)
                {
                    IFile file = await rootFolder.CreateFileAsync(docJson, CreationCollisionOption.OpenIfExists);

                    string str = await file.ReadAllTextAsync();

                    var settings = new JsonSerializerSettings();
                    settings.DateFormatString  = "dd/MM/yyyy HH:mm:ss";
                    settings.NullValueHandling = NullValueHandling.Ignore;

                    docList = JsonConvert.DeserializeObject <List <Fatture> >(str, settings);
                }

                if (rig_exist == ExistenceCheckResult.FileExists)
                {
                    IFile file = await rootFolder.CreateFileAsync(rigJson, CreationCollisionOption.OpenIfExists);

                    string str = await file.ReadAllTextAsync();

                    var settings = new JsonSerializerSettings();
                    settings.DateFormatString  = "dd/MM/yyyy HH:mm:ss";
                    settings.NullValueHandling = NullValueHandling.Ignore;

                    rigList = JsonConvert.DeserializeObject <List <FatRow> >(str, settings);
                }

                if (docList == null)
                {
                    docList = new List <Fatture>();
                }
                if (rigList == null)
                {
                    rigList = new List <FatRow>();
                }

                //
                // Estraiamo i documenti e rimuoviamo i duplicati
                //
                var sql       = "SELECT * FROM fatture2 WHERE fat_local_doc = 1";
                var documenti = await dbcon_.QueryAsync <Fatture>(sql);

                if (docList.Count > 0)
                {
                    for (int idx = 0; idx < documenti.Count; idx++)
                    {
                        for (int idy = 0; idy < docList.Count; idy++)
                        {
                            if (documenti[idx].fat_tipo == docList[idy].fat_tipo && documenti[idx].fat_n_doc == docList[idy].fat_n_doc)
                            {
                                for (int idz = 0; idz < rigList.Count; idz++)
                                {
                                    if (rigList[idz].rig_tipo == docList[idy].fat_tipo && rigList[idz].rig_n_doc == docList[idy].fat_n_doc)
                                    {
                                        rigList.RemoveAt(idz);
                                        idz--;
                                    }
                                }
                                docList.RemoveAt(idy);
                                idy--;
                            }
                        }
                    }
                }
                docList.AddRange(documenti);

                //
                // Estraiamo le righe dei documenti
                //
                foreach (var doc in docList)
                {
                    sql = $"SELECT * from fatrow2 WHERE rig_tipo = {doc.fat_tipo} AND rig_n_doc = {doc.fat_n_doc} ORDER BY rig_tipo, rig_n_doc, rig_d_ins, rig_t_ins";
                    var righe = await dbcon_.QueryAsync <FatRow>(sql);

                    rigList.AddRange(righe);
                }

                //
                // Salviamo i dati
                //
                IFile doc_file = await rootFolder.CreateFileAsync(docJson, CreationCollisionOption.ReplaceExisting);

                await doc_file.WriteAllTextAsync(JsonConvert.SerializeObject(docList, Formatting.Indented));

                IFile rig_file = await rootFolder.CreateFileAsync(rigJson, CreationCollisionOption.ReplaceExisting);

                await rig_file.WriteAllTextAsync(JsonConvert.SerializeObject(rigList, Formatting.Indented));

                busyIndicator.Title = "Scarico Dati...";

                await ImportTableAsync <Ditte>("ditt2016", m_dit_download, m_dit_unzip, m_dit_json, m_dit_load, m_dit, m_dit_rec);
                await ImportTableAsync <Zone>("zone", m_zon_download, m_zon_unzip, m_zon_json, m_zon_load, m_zon, m_zon_rec);
                await ImportTableAsync <Cateco>("cateco", m_eco_download, m_eco_unzip, m_eco_json, m_eco_load, m_eco, m_eco_rec);
                await ImportTableAsync <Pagamenti>("pagament", m_pag_download, m_pag_unzip, m_pag_json, m_pag_load, m_pag, m_pag_rec);
                await ImportTableAsync <Tabelle>("tabelle", m_tab_download, m_tab_unzip, m_tab_json, m_tab_load, m_tab, m_tab_rec);
                await ImportTableAsync <Agenti>("agenti1", m_age_download, m_age_unzip, m_age_json, m_age_load, m_age, m_age_rec);
                await ImportTableAsync <Misure>("misure", m_mis_download, m_mis_unzip, m_mis_json, m_mis_load, m_mis, m_mis_rec);
                await ImportTableAsync <Clienti>("clienti1", m_cli_download, m_cli_unzip, m_cli_json, m_cli_load, m_cli, m_cli_rec);
                await ImportTableAsync <Destinazioni>("destina1", m_dst_download, m_dst_unzip, m_dst_json, m_dst_load, m_dst, m_dst_rec);
                await ImportTableAsync <Scadenze>("scadenze", m_sca_download, m_sca_unzip, m_sca_json, m_sca_load, m_sca, m_sca_rec);
                await ImportTableAsync <Codiva>("codiva", m_iva_download, m_iva_unzip, m_iva_json, m_iva_load, m_iva, m_iva_rec);
                await ImportTableAsync <Reparti>("reparti", m_rep_download, m_rep_unzip, m_rep_json, m_rep_load, m_rep, m_rep_rec);
                await ImportTableAsync <Catmerc>("catmerc1", m_mer_download, m_mer_unzip, m_mer_json, m_mer_load, m_mer, m_mer_rec);
                await ImportTableAsync <Fornitori>("fornito1", m_for_download, m_for_unzip, m_for_json, m_for_load, m_for, m_for_rec);
                await ImportTableAsync <Depositi>("depositi", m_dep_download, m_dep_unzip, m_dep_json, m_dep_load, m_dep, m_dep_rec);
                await ImportTableAsync <Lotti>("lotti1", m_lot_download, m_lot_unzip, m_lot_json, m_lot_load, m_lot, m_lot_rec);
                await ImportTableAsync <Artanag>("artanag", m_ana_download, m_ana_unzip, m_ana_json, m_ana_load, m_ana, m_ana_rec);
                await ImportTableAsync <Listini>("listini1", m_lis_download, m_lis_unzip, m_lis_json, m_lis_load, m_lis, m_lis_rec);
                await ImportTableAsync <Fatture>("fatture2", m_fat_download, m_fat_unzip, m_fat_json, m_fat_load, m_fat, m_fat_rec);
                await ImportTableAsync <FatRow>("fatrow2", m_row_download, m_row_unzip, m_row_json, m_row_load, m_row, m_row_rec);
                await ImportTableAsync <Vettori>("vettori1", m_vet_download, m_vet_unzip, m_vet_json, m_vet_load, m_vet, m_vet_rec);
                await ImportTableAsync <Banche>("banche1", m_ban_download, m_ban_unzip, m_ban_json, m_ban_load, m_ban, m_ban_rec);
                await ImportTableAsync <Canali>("canali", m_can_download, m_can_unzip, m_can_json, m_can_load, m_can, m_can_rec);
                await ImportTableAsync <Stagioni>("stagioni", m_sta_download, m_sta_unzip, m_sta_json, m_sta_load, m_sta, m_sta_rec);
                await ImportTableAsync <Marchi>("marchi", m_mar_download, m_mar_unzip, m_mar_json, m_mar_load, m_mar, m_mar_rec);
                await ImportTableAsync <Associazioni>("associaz", m_asg_download, m_asg_unzip, m_asg_json, m_asg_load, m_asg, m_asg_rec);
                await ImportTableAsync <Barcode>("barcode", m_bar_download, m_bar_unzip, m_bar_json, m_bar_load, m_bar, m_bar_rec);
                await ImportTableAsync <Trasporti>("trasport", m_tra_download, m_tra_unzip, m_tra_json, m_tra_load, m_tra, m_tra_rec);
                await ImportTableAsync <Agganci>("agganci1", m_agg_download, m_agg_unzip, m_agg_json, m_agg_load, m_agg, m_agg_rec);
                await ImportTableAsync <Descrizioni>("descriz1", m_des_download, m_des_unzip, m_des_json, m_des_load, m_des, m_des_rec);
                await ImportTableAsync <ArtCounter>("artcount", m_aco_download, m_aco_unzip, m_aco_json, m_aco_load, m_aco, m_aco_rec);

                busyIndicator.Title = "Ripristino Backup...";

                //
                // Verifichiamo l'esistenza dei dati di backup
                //
                for (int idx = 0; idx < docList.Count; idx++)
                {
                    docList[idx].fat_id = 0;
                    sql = $"SELECT COUNT(*) FROM fatture2 WHERE fat_tipo = {docList[idx].fat_tipo} AND fat_n_doc = {docList[idx].fat_n_doc}";
                    var num = await dbcon_.ExecuteScalarAsync <int>(sql);

                    if (num > 0)
                    {
                        for (int idy = 0; idy < rigList.Count; idy++)
                        {
                            if (rigList[idy].rig_tipo == docList[idx].fat_tipo && rigList[idy].rig_n_doc == docList[idx].fat_n_doc)
                            {
                                rigList.RemoveAt(idy);
                                idy--;
                            }
                        }
                        docList.RemoveAt(idx);
                        idx--;
                    }
                }
                for (int idx = 0; idx < rigList.Count; idx++)
                {
                    rigList[idx].rig_id = 0;
                }

                //
                // Inseriamo i dati nel database
                //
                if (docList.Count > 0)
                {
                    await dbcon_.InsertAllAsync(docList);
                }
                if (rigList.Count > 0)
                {
                    await dbcon_.InsertAllAsync(rigList);
                }

                //
                // Marchiamo le Scadenze Pagate e Incassate
                //
                busyIndicator.Title = "Controllo Scadenze...";
                try
                {
                    int numrec  = 0;
                    var dsrList = await dbcon_.QueryAsync <ScadenzeSinc>("SELECT dsr_rel_sca, dsr_num_sca, dsr_paginc FROM scapagro");

                    busyIndicator.Title = "Controllo Scadenze 0/" + dsrList.Count;
                    foreach (var dsr in dsrList)
                    {
                        numrec++;
                        try
                        {
                            var scaList = await dbcon_.QueryAsync <Scadenze>("SELECT * FROM scadenze WHERE sca_relaz = ? AND sca_num = ? LIMIT 1", dsr.dsr_rel_sca, dsr.dsr_num_sca);

                            if (scaList.Count > 0)
                            {
                                var resto = scaList[0].sca_importo - dsr.dsr_paginc;
                                if (!resto.TestIfZero(2))
                                {
                                    try
                                    {
                                        scaList[0].sca_importo = dsr.dsr_paginc;
                                        scaList[0].sca_pagato  = 1;
                                        scaList[0].sca_cont    = 1;
                                        await dbcon_.UpdateAsync(scaList[0]);

                                        scaList[0].sca_id  = 0;
                                        scaList[0].sca_num = 1 + await dbcon_.ExecuteScalarAsync <int>("SELECT MAX(sca_num) FROM scadenze WHERE sca_relaz = 0");

                                        scaList[0].sca_pagato  = 0;
                                        scaList[0].sca_cont    = 0;
                                        scaList[0].sca_importo = resto;
                                        scaList[0].sca_locked  = 1;
                                        await dbcon_.InsertAsync(scaList[0]);
                                    }
                                    catch (Exception ex)
                                    {
                                        await DisplayAlert("Errore", "Impossibile aggiornare la scadenza : " + ex.Message, "OK");
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        scaList[0].sca_pagato = 1;
                                        scaList[0].sca_cont   = 1;
                                        await dbcon_.UpdateAsync(scaList[0]);
                                    }
                                    catch (Exception ex)
                                    {
                                        await DisplayAlert("Errore", "Impossibile aggiornare la scadenza : " + ex.Message, "OK");
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e.Message);
                        }
                        busyIndicator.Title = "Controllo Scadenze " + numrec + "/" + dsrList.Count;
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                    busyIndicator.IsBusy = false;
                    await DisplayAlert("Attenzione!", "Sincronizzazione Scadenze Fallita", "OK");

                    await Navigation.PopModalAsync();

                    return;
                }
                //
                // Fine Marcatura scadenze
                //

                try
                {
                    var app     = (App)Application.Current;
                    var ditlist = await dbcon_.QueryAsync <Ditte>("SELECT * FROM ditt2016 ORDER BY dit_codice LIMIT 1");

                    if (ditlist.Count == 0)
                    {
                        app.facile_db_impo = null;
                    }
                    else
                    {
                        app.facile_db_impo = ditlist[0];
                    }

                    //
                    // Conversione Campi documenti
                    //
                    await dbcon_.ExecuteAsync($"UPDATE fatture2 SET fat_registro = fat_registro_free WHERE TRIM(fat_registro) = '' AND TRIM(fat_registro_free) != ''");

                    await dbcon_.ExecuteAsync($"UPDATE fatture2 SET fat_registro_free = '' WHERE TRIM(fat_registro_free) != ''");

                    //
                    // Eliminazione documenti con data esterna all'esercizio corrente
                    //
                    if (app.facile_db_impo != null)
                    {
                        try
                        {
                            DateTime d1      = new DateTime(app.facile_db_impo.dit_anno, 1, 1);
                            DateTime d2      = new DateTime(app.facile_db_impo.dit_anno, 12, 31);
                            var      doclist = await dbcon_.QueryAsync <Fatture>($"SELECT * FROM fatture2 WHERE fat_d_doc NOT BETWEEN {d1.Ticks} AND {d2.Ticks}");

                            if (doclist != null)
                            {
                                foreach (var doc in doclist)
                                {
                                    await dbcon_.ExecuteAsync($"DELETE FROM fatrow2 WHERE rig_tipo = {doc.fat_tipo} AND rig_n_doc = {doc.fat_n_doc}");
                                }
                                await dbcon_.ExecuteAsync($"DELETE FROM fatture2 WHERE WHERE fat_d_doc NOT BETWEEN {d1.Ticks} AND {d2.Ticks}");
                            }
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e.Message);
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                    busyIndicator.IsBusy = false;
                    await DisplayAlert("Attenzione!", "Nessuna Ditta Trovata in Archivio", "OK");

                    await Navigation.PopModalAsync();

                    return;
                }

                //
                // Confermiamo la riuscita
                //
                lim.data_download = true;
                await dbcon_.UpdateAsync(lim);

                //
                // Rimuoviamo i files di backup
                //
                await doc_file.DeleteAsync();

                await rig_file.DeleteAsync();

                busyIndicator.IsBusy = false;
                await DisplayAlert("Facile", "Importazione dati conclusa regolarmente!", "Ok");
            }
            catch (Exception ex)
            {
                busyIndicator.IsBusy = false;
                await DisplayAlert("Download Error", ex.Message, "OK");
            }
            await Navigation.PopModalAsync();
        }