Ejemplo n.º 1
0
        public async static Task <bool> UploadFiles(Boolean UploadPrompt = true, Boolean AllLogs = true)
        {
            Global global = FormsApp.config.Global;

            // Path where the file should be saved once downloaded (locally)
            string path = (AllLogs) ? Mobile.LogPath : Mobile.LogUserPath;

            // Only upload if there are files available
            List <FileInfo> filesToUpload = LogFilesToUpload(path);

            var upload = false;

            if (filesToUpload.Count > 0)
            {
                upload = true;
            }

            if (UploadPrompt &&
                filesToUpload.Count > 0)
            {
                upload = await Application.Current.MainPage.DisplayAlert(
                    "Pending log files",
                    "Do you want to Upload them?",
                    "Ok", "Cancel");
            }
            //          else upload = false;


            if (!upload)
            {
                return(false);
            }

            // The FTP credentiales are not present in Global.xml
            if (!global.IsFtpUploadSet)
            {
                await Errors.ShowAlert(new FtpCredentialsMissingException());

                return(false);
            }

            // Has the devices internet connection
            if (!Mobile.IsNetAvailable())
            {
                await Errors.ShowAlert(new NoInternetException());

                return(false);
            }

            // Cancel action
            bool cancelled = false;

            System.Action OnCancel = () =>
            {
                cancelled = true;
            };

            TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool> ();

            Device.BeginInvokeOnMainThread(async() =>
            {
                // Progress bar
                using (Acr.UserDialogs.IProgressDialog progress = UserDialogs.Instance.Progress("Uploading", OnCancel, "Cancel"))
                {
                    // Is necessary for appear the progress bar right now
                    await Task.Delay(10);

                    NumFilesUploaded = 0;

                    SftpClient sftp = null;

                    try
                    {
                        string remotePath = global.ftpRemotePath;
                        using (sftp = new SftpClient(global.ftpRemoteHost, 22, global.ftpUserName, global.ftpPassword))
                        {
                            sftp.Connect();

                            // If not exist create the remote path from global.xml
                            if (!sftp.Exists(remotePath))
                            {
                                sftp.CreateDirectory(remotePath);
                            }

                            using (MD5 md5Hash = MD5.Create())
                            {
                                byte[] md5Local;
                                byte[] md5Remote;
                                foreach (FileInfo file in filesToUpload)
                                {
                                    if (cancelled)
                                    {
                                        throw new Exception();
                                    }

                                    // Is necessary for update the progress bar
                                    await Task.Delay(10);

                                    // Upload local file to the FTP server
                                    using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open))
                                    {
                                        // Folder path
                                        remotePath = Path.Combine(global.ftpRemotePath, file.Directory.Name); // Logs + User folder

                                        if (!sftp.Exists(remotePath))
                                        {
                                            sftp.CreateDirectory(remotePath);
                                        }

                                        // File path
                                        string sTick = DateTime.Now.Ticks.ToString();
                                        string sName = file.Name.Substring(0, 10) + "-" + sTick + "Log.xml";
                                        remotePath   = Path.Combine(remotePath, sName);

                                        sftp.UploadFile(fileStream, remotePath, null);
                                    }

                                    // Compare local and remote files
                                    using (StreamReader stream = new StreamReader(file.FullName))
                                        md5Local = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(stream.ReadToEnd()));

                                    md5Remote = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(sftp.ReadAllText(remotePath)));

                                    // If both files are equal, move local file to backup folder
                                    if (Enumerable.SequenceEqual(md5Local, md5Remote))
                                    {
                                        // Only create backup file ( "moving" log to backup folder ) in interactive mode
                                        if (!Data.Get.IsFromScripting)
                                        {
                                            string url_to_copy = Mobile.LogUserBackupPath;// Path.Combine ( file.Directory.FullName, Mobile.PATH_BACKUP );
                                            if (!Directory.Exists(url_to_copy))
                                            {
                                                Directory.CreateDirectory(url_to_copy);
                                            }

                                            File.Copy(file.FullName, Path.Combine(url_to_copy, file.Name), true);
                                        }
                                        File.Delete(file.FullName);

                                        NumFilesUploaded += 1;

                                        progress.PercentComplete = ( int )(NumFilesUploaded * 100 / filesToUpload.Count);

                                        Utils.Print("- " + file.Directory.Name + " uploaded");
                                    }
                                }
                            }

                            sftp.Disconnect();
                        }
                    }
                    catch (Exception e)
                    {
                        // Catch all exceptions and then always show the number of
                        // files uploaded using the exception FtpUpdateLogsException
                    }
                    finally
                    {
                        if (sftp != null)
                        {
                            sftp.Dispose();
                        }

                        sftp = null;

                        // Is necessary for appear the progress full ( 100% )
                        await Task.Delay(10);

                        tcs.SetResult(NumFilesUploaded == filesToUpload.Count);
                    }
                }
            });

            bool result = await tcs.Task; // Wait for upload completion

            // Finish ok if all files have been uploaded
            if (result)
            {
                return(true);
            }

            if (!cancelled)
            {
                await Errors.ShowAlert(new FtpUpdateLogsException ( NumFilesUploaded + "/" + filesToUpload.Count ));
            }
            else
            {
                await PageLinker.ShowAlert("Uploading canceled", "Only uploaded " + NumFilesUploaded + " / " + filesToUpload.Count + " log files");
            }

            return(false);
        }
Ejemplo n.º 2
0
 /// <summary> Constructor. </summary>
 /// <exception cref="ArgumentNullException"> Thrown when one or more required arguments are null. </exception>
 /// <param name="abstractedDialog"> The abstracted dialog. </param>
 public ProgressDialog(AcrDialogs.IProgressDialog abstractedDialog)
 {
     _abstractedDialog = abstractedDialog ?? throw new ArgumentNullException(nameof(abstractedDialog));
 }