Exemplo n.º 1
0
        // locks the server (async)
        private void LockServer(DelegateTransfer callback)
        {
            try
            {
                // create local lockfile
                if (!File.Exists(localPath + lockFile))
                {
                    File.Create(localPath + lockFile);
                }
            }
            catch (Exception e)
            {
                ErrorLog.Add(this, e.Message);
                callback(false);
                return;
            }

            // try to upload the lockfile
            TransferFile file = new TransferFile(lockFile);

            fileTransfer.UploadFileAsync(file, false, remotePath, localPath,
                                         delegate(FileTransferResult result)
            {
                serverLock = (result == FileTransferResult.Success);
                callback(serverLock);
            });
        }
Exemplo n.º 2
0
 private void Source_OnCommandOutput(IOutputCommand sender, object output)
 {
     if (output is string)
     {
         if (contents == null)
         {
             contents = new List <string>();
         }
         contents.Add(output as string);
     }
     else if (output is IDictionary <string, object> )
     {
         //Check for contents and create attachment
         var dic = output as IDictionary <string, object>;
         if (dic.ContainsKey("Contents"))
         {
             var content = (dic["Contents"] is List <string>) ? string.Join("\n", (dic["Contents"] as List <string>).ToArray()) : dic["Contents"] as string;
             var file    = new TransferFile();
             file.FileName     = FileName ?? GenerateFileName();
             file.Mimetype     = Mimetype ?? "text/plain";
             file.Data         = UTF8Encoding.UTF8.GetBytes(content);
             dic["Attachment"] = file;
             OnCommandOutput?.Invoke(this, dic);
         }
     }
 }
Exemplo n.º 3
0
        // downloads and handles the global config file from the ftp server
        private void Init()
        {
            connected = true;

            // set remote path (e.g. "ftp://www.example.com/myFolder")
            remotePath = new Uri(protocol + Settings.Path);

            // set credentials (username, password, passive mode)
            fileTransfer.Client.Credentials = new NetworkCredential(Settings.User, Settings.Password);
            fileTransfer.Client.UsePassive  = Settings.Passive;

            // download global config async
            TransferFile file = new TransferFile(globalConfig);

            fileTransfer.DownloadFileAsync(file, false, remotePath, localPath,
                                           // callback of the download
                                           delegate(FileTransferResult result)
            {
                if (exit)
                {
                    FireExit();
                }
                else
                {
                    // versions object handels global config file if download has been successful
                    if (result == FileTransferResult.Success)
                    {
                        versions.Load(localPath + globalConfig);
                    }

                    // fire some events
                    ResetInterface();
                }
            });
        }
Exemplo n.º 4
0
        // creates global config and uploads it (async)
        private void UploadGlobalConfig(DelegateTransfer callback)
        {
            // latest update = uploaded version
            versions.LatestUpdate = ulVersion;

            // if uploaded version is a full version
            if (ulFullVersion)
            {
                // latest version = uploaded version
                versions.LatestFullVersion = ulVersion;
            }

            // add uploaded version to version list
            versions.Add(ulVersion, ulFullVersion);

            // save global config to local temp folder
            versions.Save(localPath + globalConfig);

            var file = new TransferFile(globalConfig);

            // try to upload new global config
            fileTransfer.UploadFileAsync(file, false, remotePath, localPath,
                                         delegate(FileTransferResult result)
            {
                callback(result == FileTransferResult.Success);
            });
        }
Exemplo n.º 5
0
        public string Execute(params string[] parameters)
        {
            if (File == null)
            {
                if (contents == null)
                {
                    //Prepare file for download
                    File          = new TransferFile();
                    File.FileName = FileName ?? "test.txt";
                    File.Mimetype = Mimetype ?? "text/plain";
                    File.Data     = UTF8Encoding.UTF8.GetBytes("This is a test text file");
                    return("No file provided as input. Test file generated.");
                }
                else
                {
                    File          = new TransferFile();
                    File.FileName = FileName ?? GenerateFileName();
                    File.Mimetype = Mimetype ?? "text/plain";
                    File.Data     = UTF8Encoding.UTF8.GetBytes(string.Join("\n", contents.ToArray()));
                }
                OnCommandOutput?.Invoke(this, File);
            }

            return(null);
        }
Exemplo n.º 6
0
 private void DownloadButton_Click(object sender, RoutedEventArgs e)
 {
     if (SearchResaultListView.SelectedItem == null)
     {
         MessageBox.Show("You must choose a file", "Error");
     }
     else
     {
         var file = SearchResaultListView.SelectedItem as TransferFile;
         TempChoosedFile = file;
         _userLogic.RetrieveUserFilesLogic(MyUser);
         if (MyUser.OwnedFiles.Any(a => a.FileName.Equals(file?.FileName)))
         {
             MessageBox.Show("You already own that file", "Error");
         }
         else if (file.ResourcesNumber == 0)
         {
             MessageBox.Show("No resources for this file", "Error");
         }
         else
         {
             Task.Factory.StartNew((() =>
             {
                 _downloadLogic = new DownloadLogic(file.FileName, file.FileSize, downloadPath);
                 //_downloadLogic = new DownloadLogic(file.FileName, file.FileSize, "");
                 _downloadLogic.MyDownloadEvent += updateDownloadTransferListView;
                 _downloadLogic.Start();
             }));
         }
     }
 }
Exemplo n.º 7
0
 public string Execute(params string[] parameters)
 {
     if (File == null)
     {
         if (contents == null)
         {
             //Prepare file for download
             File          = new TransferFile();
             File.FileName = FileName ?? "test.txt";
             File.Mimetype = Mimetype ?? "text/plain";
             File.Data     = UTF8Encoding.UTF8.GetBytes("This is a test text file");
             return("No file provided as input. Test file generated.");
         }
         else
         {
             File          = new TransferFile();
             File.FileName = FileName ?? GenerateFileName();
             File.Mimetype = Mimetype ?? "text/plain";
             File.Data     = UTF8Encoding.UTF8.GetBytes(string.Join("\n", contents.ToArray()));
         }
     }
     if (ShouldZip)
     {
         //Zip file using https://stackoverflow.com/questions/681827/how-to-create-and-fill-a-zip-file-using-asp-net
         return("Zip functionality not yet included");
     }
     return("File returned as download");
 }
Exemplo n.º 8
0
 private void updateDownloadTransferListView(DownloadFileInfo info, bool isDone)
 {
     if (!isDone)
     {
         TransferFile newFile = new TransferFile();
         newFile = TempChoosedFile;
         Dispatcher.BeginInvoke(new Action(delegate()
         {
             newFile.Status = info.Status;
             FileTransferListView.Items.Add(newFile);
             FileTransferListView.Items.Refresh();
         }));
     }
     else
     {
         Dispatcher.BeginInvoke(new Action(delegate()
         {
             foreach (TransferFile line in FileTransferListView.Items)
             {
                 if (line.FileName.Equals(info.FileName))
                 {
                     line.Status = info.Status;
                     line.Time   = info.Time;
                     line.Kbps   = info.Kbps;
                     _userLogic.UpdateUserTransferFilesLogic(line.FileName, MyUser.UserName);
                     _fileLogic.CopyFileByPaths(line.FileName, downloadPath, uploadPath);
                 }
             }
             FileTransferListView.Items.Refresh();
         }));
     }
     TempChoosedFile = null;
 }
 private void Source_OnCommandOutput(IOutputCommand sender, object output)
 {
     if (output is TransferFile)
     {
         transferFile = output as TransferFile;
     }
 }
Exemplo n.º 10
0
 private void Source_OnCommandOutput(IOutputCommand sender, object output)
 {
     if (output is IDictionary <string, object> )
     {
         var dic = output as IDictionary <string, object>;
         if (dic.ContainsKey("FromEmail"))
         {
             FromEmail = (string)dic["FromEmail"];
         }
         if (dic.ContainsKey("FromName"))
         {
             FromName = (string)dic["FromName"];
         }
         if (dic.ContainsKey("ToEmail"))
         {
             ToEmail = (string)dic["ToEmail"];
         }
         if (dic.ContainsKey("ToName"))
         {
             ToEmail = (string)dic["ToName"];
         }
         if (dic.ContainsKey("Attachment"))
         {
             _attachment = (TransferFile)dic["Attachement"];
         }
         if (dic.ContainsKey("Subject"))
         {
             Subject = (string)dic["Subject"];
         }
         if (dic.ContainsKey("Body"))
         {
             Body = (string)dic["Body"];
         }
     }
     else if (output is string)
     {
         if (string.IsNullOrEmpty(Subject))
         {
             Subject = output as string;
         }
         else if (string.IsNullOrEmpty(Body))
         {
             Body = output as string;
         }
     }
     else if (output is TransferFile)
     {
         _attachment = output as TransferFile;
     }
     SendEmail();
 }
Exemplo n.º 11
0
 private void AddFiles(DirectoryInfo directory, TransferDirectory userDirectory)
 {
     foreach (var file in directory.GetFiles())
     {
         var transferFile = new TransferFile
         {
             Name      = file.Name,
             FullName  = file.FullName,
             Size      = file.Length,
             Extension = file.Extension
         };
         userDirectory.Files.Add(transferFile);
     }
 }
Exemplo n.º 12
0
 private void AddFilesToTransfer(TransferDirectory transfer_directory, DirectoryModel directory_model)
 {
     foreach (var file in directory_model.Files)
     {
         TransferFile file_transfer = new TransferFile
         {
             Name      = file.Name,
             FullName  = file.FullName,
             Size      = file.Size,
             Extension = file.Extension
         };
         transfer_directory.Files.Add(file_transfer);
     }
 }
Exemplo n.º 13
0
 public string Execute(params string[] parameters)
 {
     if (HttpContext.Current.Request["filename"] != null && HttpContext.Current.Request["data"] != null)
     {
         //We have an uploaded file
         TransferFile tf = new TransferFile();
         tf.FileName = HttpContext.Current.Request["filename"];
         tf.Data     = Convert.FromBase64String(HttpContext.Current.Request["data"]);
         OnCommandOutput?.Invoke(this, tf);
         return("File uploaded successfully");
     }
     else
     {
         return("No file uploaded");
     }
 }
Exemplo n.º 14
0
        // downloads global config file and checks new version (async)
        private void DownloadGlobalConfig(DelegateTransfer callback)
        {
            TransferFile file = new TransferFile(globalConfig);

            // try to download global config file
            fileTransfer.DownloadFileAsync(file, false, remotePath, localPath,
                                           delegate(FileTransferResult result)
            {
                if (result == FileTransferResult.Success)
                {
                    versions.Load(localPath + globalConfig);
                }

                // check new version number
                callback(versions.CheckNewVersionNr(ulVersion));
            });
        }
        public string Execute(params string[] parameters)
        {
            MemoryStream ms = new MemoryStream(4000);

            _exporter.Export(ms, _contentList.Select(c => new ExportSource(c, (Recursive) ? ExportSource.RecursiveLevelInfinity : ExportSource.NonRecursive)).ToList());
            while (!_exporter.Status.IsDone)
            {
                Thread.Sleep(1000);
            }

            File          = new TransferFile();
            File.FileName = "Export.episerverdata";
            File.Mimetype = "application/octet-stream";
            File.Data     = ms.GetBuffer();

            return("Content exported");
        }
Exemplo n.º 16
0
        // checks if server is locked (async)
        private void CheckLock(DelegateTransfer callback)
        {
            TransferFile file = new TransferFile(lockFile);

            // try to download lock file
            fileTransfer.DownloadFileAsync(file, false, remotePath, localPath,
                                           delegate(FileTransferResult result)
            {
                if (!exit)
                {
                    callback(result == FileTransferResult.Failure);
                }
                else
                {
                    FireExit();
                }
            });
        }
Exemplo n.º 17
0
        void ReplaceDb()
        {
            var pw = new BlowTrial.View.PleaseWait();

            pw.Show();
            string currentPath = TrialDataContext.GetDbPath();

            if (_repository != null)
            {
                _repository.Dispose();
                _repository = null;
            }
            System.IO.File.Move(currentPath, currentPath.InsertDateStampToFileName());
            TransferFile.AllowUpdate(_transferLog, fi =>
            {
                fi.MoveTo(currentPath);
            });
            pw.Close();
        }
Exemplo n.º 18
0
        public void UploadDicomFile()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "DICOM|*.dcm";
            dialog.Multiselect = false;
            if (dialog.ShowDialog() == true)
            {
                Stream stream = dialog.File.OpenRead();
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, (int) stream.Length);
                stream.Close();

                TransferFile transferFile = new TransferFile();
                transferFile.FileName = dialog.File.Name;
                transferFile.FileStream = bytes;

                _transferServiceClient.UploadCompleted += UploadDicomFileCompleted;
                _transferServiceClient.UploadAsync(transferFile);
            }
        }
Exemplo n.º 19
0
 public ActionResult CopyLocalToRemote(TransferFile transferFile)
 {
     try
     {
         string filename = Path.GetFileName(transferFile.SourcePath);
         EventLogWriter.SetEvent(LogEvents.StartTransferFile);
         EventLogWriter.SetEvent(LogEvents.TransferingFile);
         SftpClient client     = SFTPClientConnector.ConnectToRemote();
         var        fileStream = new FileStream(transferFile.SourcePath, FileMode.Open);
         client.UploadFile(fileStream, transferFile.DestinationPath + "/" + filename);
         fileStream.Dispose();
         client.Dispose();
         EventLogWriter.SetEvent(LogEvents.TransferCompleted);
         return(new HttpStatusCodeResult(HttpStatusCode.OK));
     }
     catch (Exception e)
     {
         return(HttpNotFound(e.Message));
     }
 }
Exemplo n.º 20
0
        public void UploadNoDicomFile()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Graphics Interchange Format (*.gif)|*.gif|Bitmap (*.bmp)|*.bmp|Portable Network Graphics (*.png)|*.png|Tagged Image File Format (*.tiff)|*.tiff|JPEG|*.jpeg;*.jfif;*.jpg;*.jpe";
            dialog.Multiselect = false;
            if (dialog.ShowDialog() == true)
            {
                Stream stream = dialog.File.OpenRead();
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, (int)stream.Length);
                stream.Close();

                TransferFile transferFile = new TransferFile();
                transferFile.FileName = dialog.File.Name;
                transferFile.FileStream = bytes;

                _transferServiceClient.UploadCompleted += UploadNoDicomFileCompleted;
                _transferServiceClient.UploadAsync(transferFile);
            }
        }
 void Save(object o)
 {
     TransferFile.RequestUpdate(new TransferLog(Path.Combine(SelectedSite.Directory, _logFileName)), SelectedSite.Models.First().DuplicateIdCheck, CreateFileForTransfer, 200, OnFinishedTransfer);
     MessageBox.Show("A request to update has been sent. The time taken to acknowledge such a request will depend on whether the trial site has their BLOW-trial application running, and how often the application is backing up to the cloud. You will be notified when the update is occuring. Please do not close or log out until this notification has occured.");
     OnRequestClose();
 }
        public TransferFile ExecuteCommand(string command, string session)
        {
            bool executeasync = false;

            CleanUp();
            if (command.ToLower().StartsWith("start "))
            {
                executeasync = true;
                command      = command.Substring(6);
            }
            var commands = command.Split('|').Where(p => p != "").ToArray();
            List <ExecutableCommand> ecommands = new List <ExecutableCommand>();

            foreach (var cmds in commands)
            {
                ExecutableCommand ecmd = new ExecutableCommand();

                var parts = SplitArguments(cmds).Where(p => p != "").ToArray(); //TODO: Better arguments handling (support quotes)
                ecmd.Parameters = parts.Skip(1).ToArray();
                //Support piping

                if (Commands.ContainsKey(parts.First().ToLower()))
                {
                    var cmdd = Commands[parts.First().ToLower()];

                    //Create command object
                    var cmd = cmdd.CreateNew <IConsoleCommand>();
                    ecmd.Command = cmd;
                    //Map parameters

                    for (int i = 1; i < parts.Length; i += 2)
                    {
                        if (parts[i].StartsWith("-"))
                        {
                            try
                            {
                                //Parameter
                                if (cmdd.Parameters.ContainsKey(parts[i].ToLower().TrimStart('-')))
                                {
                                    var pi = cmdd.Parameters[parts[i].ToLower().TrimStart('-')];
                                    if (pi.PropertyType == typeof(string))
                                    {
                                        pi.SetValue(cmd, parts[i + 1]); //TODO: Support other types than string
                                    }
                                    else if (pi.PropertyType == typeof(bool))
                                    {
                                        pi.SetValue(cmd, bool.Parse(parts[i + 1]));
                                    }
                                    else if (pi.PropertyType == typeof(int))
                                    {
                                        pi.SetValue(cmd, int.Parse(parts[i + 1]));
                                    }
                                    else if (pi.PropertyType.IsEnum)
                                    {
                                        pi.SetValue(cmd, Enum.Parse(pi.PropertyType, parts[i + 1], true));
                                    }
                                }
                                else
                                {
                                    AddLogToSession(session, new CommandLog("System", "Unrecognized parameter"));
                                }
                            } catch (Exception exc)
                            {
                                AddLogToSession(session, new CommandLog("System", $"Error in parameters for {cmdd}: {exc.Message}"));
                            }
                        }
                        else
                        {
                            //Log.Add("Unknown parameter: " + parts[i]);
                        }
                    }
                }
                else
                {
                    AddLogToSession(session, new CommandLog("System", $"Unknown Command: {parts.First()}"));
                }

                if (ecmd.Command is IConsoleOutputCommand)
                {
                    ((IConsoleOutputCommand)ecmd.Command).OutputToConsole += new OutputToConsoleHandler((c, s) => { if (s != null)
                                                                                                                    {
                                                                                                                        AddLogToSession(session, new CommandLog(c.GetType().Name, s));
                                                                                                                    }
                                                                                                        });
                }
                if (ecmd.Command is ILogAwareCommand)
                {
                    ((ILogAwareCommand)ecmd.Command).Log = NewSession(session);
                }

                if (ecmd.Command is IInputCommand && ecommands.Any() && (ecommands.Last().Command is IOutputCommand))
                {
                    (ecmd.Command as IInputCommand).Initialize(ecommands.Last().Command as IOutputCommand, ecmd.Parameters);
                }

                if (ecommands.Count > 0 && !(ecmd.Command is IInputCommand))
                {
                    AddLogToSession(session, new CommandLog("System", "You cannot pipe content to that command"));
                    return(null);
                }
                else if (commands.Length > 1 && ecommands.Count == 0 && !(ecmd.Command is IOutputCommand))
                {
                    AddLogToSession(session, new CommandLog("System", "You cannot pipe content from that command"));
                    return(null);
                }
                ecommands.Add(ecmd);
            }

            TransferFile df = null;
            //Execute

            Action ExecuteCommands = () => {
                foreach (var ec in ecommands)
                {
                    try
                    {
                        var exec = ec.Command.Execute(ec.Parameters);
                        if (!string.IsNullOrEmpty(exec))
                        {
                            AddLogToSession(session, new CommandLog(ec.Command.GetType().Name, exec));
                        }
                        if (ec.Command is IReturnsFile)
                        {
                            df = (ec.Command as IReturnsFile).File;
                        }
                    }
                    catch (Exception exc)
                    {
                        AddLogToSession(session, new CommandLog(ec.Command.GetType().Name, exc.Message));
                        //TODO: Logging?
                    }
                }
            };

            if (executeasync)
            {
                //Queue task
                AddLogToSession(session, new CommandLog("System", "Starting Task"));
                System.Threading.Tasks.Task t = System.Threading.Tasks.Task.Run(ExecuteCommands);
                Tasks.Add(t);
            }
            else
            {
                ExecuteCommands();
            }

            return(df);
        }