Exemple #1
0
        private async void UpladFile_Click(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender;

            //button.Visibility = Visibility.Collapsed;
            UploadProgress.Visibility = Visibility.Visible;
            DirFileInfo.IsEnabled     = false;
            FileList.IsEnabled        = false;
            var            ftpItmListM    = (FtpListItemModel)button.DataContext;
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Multiselect = true;
            if (openFileDialog.ShowDialog(Window.GetWindow(this)) == true)
            {
                var list      = openFileDialog.FileNames;
                var ftpHelper = new FtpHelper();
                Progress <FtpProgress> progress = new Progress <FtpProgress>(p =>
                {
                    App.Current.Dispatcher.Invoke((Action) delegate
                    {
                        if (p.Progress == 100 && p.FileCount - 1 == p.FileIndex)
                        {
                            ftpHelper.Progress = 100;
                            //button.Visibility = Visibility.Visible;
                            UploadProgress.Visibility = Visibility.Collapsed;
                        }
                        else
                        {
                            ftpHelper.TransMessage        = $"Upload from {p.LocalPath} to {p.RemotePath}";
                            ftpHelper.Progress            = Math.Round(p.Progress, 1);
                            ftpHelper.FileCount           = p.FileCount;
                            ftpHelper.FileIndex           = p.FileIndex + 1;
                            ftpHelper.TransferSpeed       = p.TransferSpeed;
                            ftpHelper.EAT                 = p.ETA.ToString(@"hh\:mm\:ss", null);
                            ftpHelper.TransferredBytes    = p.TransferredBytes;
                            ftpHelper.TransferSpeedString = p.TransferSpeedToString();
                        }
                    });
                });
                UploadProgress.DataContext = ftpHelper;
                DirFileInfo.Visibility     = Visibility.Hidden;
                cancellationTokenSource    = new CancellationTokenSource();
                await ftpHelper.UploadFilesAsync(list, ftpItmListM.FullName, progress, cancellationTokenSource.Token);

                DirFileInfo.IsEnabled = true;
                FileList.IsEnabled    = true;
                var holeDamThing = (StartViewModel)FileList.DataContext;
                var path         = ftpItmListM.FullName;
                var dt           = await holeDamThing.FindItemByPathAsync(ftpItmListM.FullName);

                if (dt != null)
                {
                    //var dt2 = await holeDamThing.FindItemByPathAsync(dt.ParentPath);
                    //await holeDamThing.GetFtpChildItems(dt2);
                    await holeDamThing.GetFtpListItems(dt.Items, dt.FullName, true);
                }
            }
        }
Exemple #2
0
        private void btnUpdateEvent_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                MessageBox.Show("Naam mag niet leeg zijn");
                return;
            }

            if (dtpStartDate.Value >= dtpEndDate.Value)
            {
                MessageBox.Show("Einddatum moet later zijn dan de startdatum");
                return;
            }

            if (_ev != null)
            {
                var guestCount = LogicCollection.GuestLogic.GetGuestCountByEvent(_ev);
                if (numCapacity.Value < guestCount)
                {
                    MessageBox.Show("De capaciteit van evenement is minder dan het huidige aantal ingeschreven gasten");
                    return;
                }

                _ev.Name        = txtName.Text;
                _ev.Location    = txtLocation.Text;
                _ev.StartDate   = dtpStartDate.Value;
                _ev.EndDate     = dtpEndDate.Value;
                _ev.MaxCapacity = (int)numCapacity.Value;

                if (LogicCollection.EventLogic.UpdateEvent(_ev))
                {
                    OnEventSuccessfullyModified();
                }
                ;
            }
            else
            {
                _ev =
                    LogicCollection.EventLogic.AddEvent(new Event(0,
                                                                  txtName.Text,
                                                                  dtpStartDate.Value,
                                                                  dtpEndDate.Value,
                                                                  txtLocation.Text,
                                                                  maxCap: (int)numCapacity.Value
                                                                  ));

                if (_ev == null)
                {
                    MessageBox.Show("ERROR: Er is iets misgegaan.");
                    return;
                }

                FtpHelper.CreateDirectory(_ev.ID.ToString());
                OnEventSuccessfullyModified();
                RefreshUserControl();
                MessageBox.Show("Evenement succesvol aangemaakt!");
            }
        }
Exemple #3
0
        public DisplayLabel()
        {
            FocusVisualStyle = null;
            Margin           = new Thickness(-4, -4, 0, -4);
            Padding          = new Thickness(0);

            FontSize = 12;

            MouseEnter += delegate {
                if (_dbSource != null)
                {
                    if (FtpHelper.HasBeenMapped())
                    {
                        ToolTip = DbPathLocator.DetectPath(_dbSource);
                    }
                    else
                    {
                        ToolTip = "Directory has not been mapped yet. Load the database first.";
                    }
                }

                if (ToolTip == null)
                {
                    ToolTip = "File not found. This database will be disabled.";
                }
            };

            SizeChanged += delegate {
                if (!_isLoaded)
                {
                    Grid    presenter = WpfUtilities.FindParentControl <Grid>(this);
                    TextBox box       = (TextBox)presenter.Children[2];

                    if (box.Text == "Visible")
                    {
                        Foreground = _stateBrush;
                    }
                    else
                    {
                        Foreground = _stateInactiveBrush;
                    }

                    box.TextChanged += delegate {
                        if (box.Text == "Visible")
                        {
                            Foreground = _stateBrush;
                        }
                        else
                        {
                            Foreground = _stateInactiveBrush;
                        }
                    };

                    _isLoaded = true;
                }
            };
        }
 public FtpRemoteFileSystem(RemoteSystemSetting setting)
 {
     _serverDetails = FtpHelper.ServerDetails
                          (setting.Host, setting.Port.ToString(), setting.UserName, setting.Type);
     FtpClient             = new FtpClient(setting.Host);
     FtpClient.Credentials = null;
     //FtpClient.Credentials = new System.Net.NetworkCredential(setting.UserName, setting.Password);
     FtpClient.Port = setting.Port;
 }
 private void Form1_Load(object sender, EventArgs e)
 {
     ftp = new FtpHelper(kd_ftp_uri, kd_ftp_username, kd_ftp_psd);
     if (ConfigurationManager.AppSettings["AutoRun"].ToString().Trim() == "Y")
     {
         AutoRun_Click(sender, e);
         this.Close();
     }
 }
Exemple #6
0
        public override void Execute(object parameter)
        {
            ReportSaveModel reprotConfig = NetworkingViewModel.ReportSaveModel;

            if (reprotConfig.ReportSaveType == "文件夹")
            {
                try
                {
                    string path = Path.Combine(reprotConfig.DirAddress, string.Format("test.{0}", reprotConfig.ImageExt));

                    var fs = new FileStream(path, FileMode.Create);
                    fs.Close();

                    File.Delete(path);
                }
                catch (IOException exception)
                {
                    //ioex.
                    MessageBox.Show(exception.Message);
                    return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                    return;
                }

                MessageBox.Show("文件地址测试成功");
            }
            else if (reprotConfig.ReportSaveType.ToUpper() == "FTP")
            {
                try
                {
                    string filePath = string.Format("Test{0}.{1}", DateTime.Now.ToString("HHmmss"),
                                                    reprotConfig.ImageExt);
                    var fs = new FileStream(filePath, FileMode.Create);
                    fs.Close();

                    var ftpHelper = new FtpHelper(reprotConfig.FtpAdresse, reprotConfig.FtpUser,
                                                  reprotConfig.FtpPassword, 21);
                    var currentDateTime = DateTime.Now.ToLongDateString();
                    ftpHelper.Upload(filePath, currentDateTime, filePath);

                    if (ftpHelper.Delete(currentDateTime + "\\" + filePath, "DELE"))
                    {
                        ftpHelper.Delete(currentDateTime, "RMD");

                        MessageBox.Show("Ftp地址及用户测试通过!");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                }
            }
        }
Exemple #7
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //获取Ftp文件夹列表
            List <string> ls = FtpHelper.GetRemoteFiles("ftp://" + FtpHelper.IP + "/");

            foreach (string item in ls)
            {
                comBox.Items.Add(Regex.Replace(item, @"^ftp://" + FtpHelper.IP + "/", ""));
            }
        }
Exemple #8
0
        private async void DownloadFolder_Click(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender;
            //button.Visibility = Visibility.Collapsed;

            var ftpItmListM    = (FtpListItemModel)button.DataContext;
            var openFileDialog = new System.Windows.Forms.FolderBrowserDialog();

            openFileDialog.ShowNewFolderButton = true;
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                UploadProgress.Visibility = Visibility.Visible;
                DirFileInfo.IsEnabled     = false;
                FileList.IsEnabled        = false;
                var path      = openFileDialog.SelectedPath;
                var ftpHelper = new FtpHelper();
                Progress <FtpProgress> progress = new Progress <FtpProgress>(p =>
                {
                    App.Current.Dispatcher.Invoke((Action) delegate
                    {
                        if (p.Progress == 100 && p.FileCount - 1 == p.FileIndex)
                        {
                            ftpHelper.Progress = 100;
                            //button.Visibility = Visibility.Visible;
                            UploadProgress.Visibility = Visibility.Collapsed;
                        }
                        else
                        {
                            ftpHelper.TransMessage        = $"Upload from {p.RemotePath} to {p.LocalPath}";
                            ftpHelper.Progress            = Math.Round(p.Progress, 1);
                            ftpHelper.FileCount           = p.FileCount;
                            ftpHelper.FileIndex           = p.FileIndex + 1;
                            ftpHelper.TransferSpeed       = p.TransferSpeed;
                            ftpHelper.EAT                 = p.ETA.ToString(@"hh\:mm\:ss", null);
                            ftpHelper.TransferredBytes    = p.TransferredBytes;
                            ftpHelper.TransferSpeedString = p.TransferSpeedToString();
                        }
                    });
                });
                UploadProgress.DataContext = ftpHelper;
                cancellationTokenSource    = new CancellationTokenSource();
                var res = await ftpHelper.DownloadDirectoryAsync(ftpItmListM.FullName, path, cancellationTokenSource.Token, progress, FtpFolderSyncMode.Mirror);

                //button.Visibility = Visibility.Visible;
                UploadProgress.Visibility = Visibility.Collapsed;
                DirFileInfo.IsEnabled     = true;
                FileList.IsEnabled        = true;
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    Arguments = path,
                    FileName  = "explorer.exe"
                };
                Process.Start(startInfo);
            }
        }
Exemple #9
0
        /// <summary>
        /// Reloads the database.
        /// </summary>
        /// <param name="progress">The progress object.</param>
        public void Reload(IProgress progress)
        {
            DbDebugHelper.OnUpdate("Reloading database...");
            OnPreviewReloaded();

            try {
                FtpHelper.SetupFileManager();
                Commands.ClearCommands();
                DbPathLocator.ClearStoredFiles();
                ResetAllSettings();

                var dbs = _dbs.Values.ToList();

                for (int i = 0; i < dbs.Count; i++)
                {
                    dbs[i].Clear();
                    DbDebugHelper.OnCleared(dbs[i].DbSource, null, dbs[i]);
                }

                DbDebugHelper.OnUpdate("All database tables have been cleared.");

                for (int i = 0; i < dbs.Count; i++)
                {
                    var db = dbs[i];

                    if (db.CanBeLoaded)
                    {
                        CLHelper.CStart(i);

                        db.LoadDb();

                        if (progress != null)
                        {
                            progress.Progress = (i + 1f) / dbs.Count * 100f;
                            //ErrorHandler.HandleException("Now at " + progress.Progress + "% done.");
                        }

                        CLHelper.CStopAndDisplay(db.DbSource.DisplayName, i);
                    }

                    if (progress != null)
                    {
                        AProgress.IsCancelling(progress);
                    }
                }

                ClearCommands();
            }
            finally {
                DbDebugHelper.OnUpdate("Database reloaded...");
            }

            OnReloaded();
            SdeEditor.Instance.Dispatch(p => p.OnSelectionChanged());
        }
Exemple #10
0
    public static bool Upload(string fileUrl, string folder)
    {
        if (File.Exists(fileUrl))
        {
            FtpHelper ftpClient = new FtpHelper();
            string    ftpUrl    = ftpClient.Hostname + folder + System.IO.Path.GetFileName(fileUrl);


            FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpUrl);
            ftp.Credentials = new NetworkCredential(ftpClient.Username, ftpClient.Password);

            ftp.KeepAlive = true;
            ftp.UseBinary = true;
            ftp.Timeout   = 3600000;
            ftp.KeepAlive = true;
            ftp.Method    = WebRequestMethods.Ftp.UploadFile;

            const int bufferLength = 102400;
            byte[]    buffer       = new byte[bufferLength];
            int       readBytes    = 0;

            //open file for reading
            using (FileStream fs = File.OpenRead(fileUrl))
            {
                //try
                {
                    //open request to send
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            readBytes = fs.Read(buffer, 0, bufferLength);
                            rs.Write(buffer, 0, readBytes);
                        } while (!(readBytes < bufferLength));
                        rs.Close();
                    }
                }
                //catch (Exception)
                {
                    //Optional Alert for Exeption To Application Layer
                    //throw (new ApplicationException("بارگذاری فایل با خطا  رو به رو شد"));
                }
                //finally
                {
                    //ensure file closed
                    //fs.Close();
                }
            }

            ftp = null;
            return(true);
        }
        return(false);
    }
Exemple #11
0
        public static void dt_Tick(object sender, EventArgs e)
        {
            // check flush
            FtpHelper ftp = new FtpHelper();
            bool      ok  = ftp.httpRequest("GET", "", PackageSubVM.Instance.requestResult) == "True";

            if (ok)
            {
                PackageSubVM.Instance.CheckFlushTimer.Dispose();
                MessageBox.Show("刷新成功!");
            }
        }
Exemple #12
0
 public QadInterface(string localRootPath, string localFromErp, string localToErp, string localBackup,
                     string ftpServer, string ftpPort, string ftpUser, string ftpPassword, string ftpRootPath, string ftpFromErp, string ftpToErp)
 {
     _localRootPath = localRootPath;
     _localFromErp  = localFromErp;
     _localToErp    = localToErp;
     _localBackup   = localBackup;
     _ftp           = new FtpHelper(ftpServer, ftpPort, ftpRootPath, ftpUser, ftpPassword);
     _ftpFromErp    = ftpFromErp;
     _ftpToErp      = ftpToErp;
     InitBgw();
 }
Exemple #13
0
 protected virtual string SaveUploadedFileToFtp(ColumnField field, string strFileName, string contentType, System.IO.Stream stream)
 {
     try
     {
         return(FtpHelper.SaveUploadedFileToFtp(field, strFileName));
     }
     catch (Exception exception)
     {
         Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, null);
         throw new Durados.DuradosException(Map.Database.Localizer.Translate("Operation failed" + ", " + exception.Message));
     }
 }
        public override void Start()
        {
            FtpHelper ftpHelperForWindows = new FtpHelper();
            var       fileInfo1           = ftpHelperForWindows.GetFileInfo("ftp://10.100.97.145:2101/VisualStudio2017_ProductLaunchPoster-1.png");

            DisplayMessage(JsonConvert.SerializeObject(fileInfo1));

            FtpHelper ftpHelperForUnix = new FtpHelper(user, pwd);
            var       fileInfo2        = ftpHelperForUnix.GetFileInfo(url);

            DisplayMessage(JsonConvert.SerializeObject(fileInfo2));
        }
Exemple #15
0
 public static void UpdateStoredFiles()
 {
     foreach (var pair in _storedFiles)
     {
         if (FtpHelper.Exists(pair.Key))
         {
             if (FtpHelper.Delete(pair.Value))
             {
                 FtpHelper.Copy(pair.Key, pair.Value);
             }
         }
     }
 }
Exemple #16
0
        public ActionResult Upload()
        {
            string      ID   = Request["ID"];
            data_Entity data = new data_Entity();

            data = data_BLL.GetdataByID(ID);
            string fileName = data.dataName + ".txt";
            string filePath = Server.MapPath("/") + data.data_Position + "\\" + fileName;
            FTPInformation_Entity ftpinfo = new FTPInformation_Entity();

            ftpinfo = FTPInformation_BLL.GetFTPInfoByAgencyNo1(data.AgencyNo);
            FtpHelper ftp  = new FtpHelper(ftpinfo.FTPAddress, ftpinfo.FTPUsername, ftpinfo.FTPPassword);
            FileInfo  file = new FileInfo(filePath);
            bool      i    = ftp.Upload(file, fileName);

            if (i)
            {
                data.upload = "1";
                data_BLL.Updatedata(data);
                logs_Entity logs = new logs_Entity();
                logs.AgencyNo  = data.AgencyNo;
                logs.inputTime = DateTime.Now;
                logs.logName   = "上传密文:" + data.dataName;
                logs.log_No    = DateTime.Now.ToString("yyyyMMddhhmmss");
                logs.succeed   = "1";
                logs_BLL.Createlog(logs);

                var Person = new
                {
                    code = 0,                                       //0表示成功
                    msg  = "上传成功!",                                 //这个是失败返回的错误
                };
                return(Json(Person, JsonRequestBehavior.AllowGet)); //格式化为json
            }
            else
            {
                logs_Entity logs = new logs_Entity();
                logs.AgencyNo  = data.AgencyNo;
                logs.inputTime = DateTime.Now;
                logs.logName   = "上传密文:" + data.dataName;
                logs.log_No    = DateTime.Now.ToString("yyyyMMddhhmmss");
                logs.succeed   = "0";
                logs_BLL.Createlog(logs);
                var Person = new
                {
                    code = 1,                                       //0表示成功
                    msg  = "上传失败",                                  //这个是失败返回的错误
                };
                return(Json(Person, JsonRequestBehavior.AllowGet)); //格式化为json
            }
        }
        public MyBlogCommonResponse <List <object> > ImagePost(IFormCollection Files)
        {
            MyBlogCommonResponse <List <object> > response = new MyBlogCommonResponse <List <object> >();

            try
            {
                //var form = Request.Form;//直接从表单里面获取文件名不需要参数
                string ArticleType       = Files["ImageType"];
                var    form              = Files;//定义接收类型的参数
                IFormFileCollection cols = Request.Form.Files;
                if (cols == null || cols.Count == 0)
                {
                    response.code    = 200;
                    response.message = "没有上传文件";
                    return(response);
                }
                List <object> pathlist = new List <object>();
                //定义图片数组后缀格式
                string[] LimitPictureType = { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" };
                foreach (IFormFile file in cols)
                {
                    //获取图片后缀是否存在数组中
                    string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper();
                    if (string.IsNullOrEmpty(currentPictureExtension))
                    {
                        currentPictureExtension = "." + file.ContentType.Split('/').Last().ToUpper();
                    }
                    if (LimitPictureType.Contains(currentPictureExtension))
                    {
                        List <string> dicpathlist = new List <string>();
                        dicpathlist.Add(ArticleType);
                        dicpathlist.Add(DateTime.Now.ToString("yyyyMMdd"));
                        var filexhttppath = new FtpHelper().UploadFie(file, dicpathlist, DateTime.Now.ToString("yyyyMMddhhmmssfff") + currentPictureExtension.ToLower());
                        pathlist.Add(new { path = filexhttppath });
                    }
                    else
                    {
                        response.message = "存在不合法的图片格式;请替换"; response.code = 200;
                        return(response);
                    }
                }
                response.message = "上传成功"; response.success = true; response.data = pathlist;
                return(response);
            }
            catch (Exception ex)
            {
                response.code = 500; response.message = ex.Message.ToString();
                return(response);
            }
        }
Exemple #18
0
        public override void Start()
        {
            FtpHelper ftpHelper = new FtpHelper(user, pwd);

            try
            {
                ftpHelper.Rename(url, "asd");
                DisplayMessage("Remove file completed!");
            }
            catch (Exception exception)
            {
                DisplayMessage(exception.ToExceptionContent().ToString());
            }
        }
        public LineStreamReader(String path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
        {
            // Don't open a Stream before checking for invalid arguments,
            // or we'll create a FileStream on disk and we won't close it until
            // the finalizer runs, causing problems for applications.
            if (path == null || encoding == null)
            {
                throw new ArgumentNullException((path == null ? "path" : "encoding"));
            }

            Stream stream = FtpHelper.IsSystemFile(path) ? new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan) : FtpHelper.OpenRead(path);

            Init(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize);
        }
Exemple #20
0
 public void Execute(object parameter)
 {
     if (true || PackageSubVM.Instance.FlushCDNUrl != "")
     {
         FtpHelper ftp = new FtpHelper();
         PackageSubVM.Instance.requestResult = ftp.httpRequest("POST", PackageSubVM.Instance.FlushCDNUrl, "");
         //ftp.TencentCDNRequest("asldkfj");
     }
     else
     {
         string url = "http://push.dnion.com/cdnUrlPush.do?captcha=436bd644&type=0&url=http://shenqu.cdn.feiliu.com/update/";
         System.Diagnostics.Process.Start(url);
     }
 }
Exemple #21
0
        public override void Start()
        {
            FtpHelper ftpHelper = new FtpHelper();

            ftpHelper.Upload(@"E:\Downloads\CentOS EV.txt", "ftp://10.100.97.145:2101/CentOS EV.txt");
            DisplayMessage("Upload completed!");

            ftpHelper.UploadProgressChangedEvent = (object sender, UploadProgressChangedEventArgs e) =>
            {
                DisplayMessage($"ProgressPercentage: {e.ProgressPercentage}, TotalBytesToReceive: {e.TotalBytesToReceive}, TotalBytesToSend: {e.TotalBytesToSend}, BytesReceived: {e.BytesReceived}, BytesSent: {e.BytesSent}");
            };

            ftpHelper.UploadAsync(@"E:\Downloads\VisualStudio2017_ProductLaunchPoster-1.png", "ftp://10.100.97.145:2101/VisualStudio2017_ProductLaunchPoster-1.png");
        }
Exemple #22
0
 public static void DbDirectCopyWriter <TKey>(DbDebugItem <TKey> debug, AbstractDb <TKey> db)
 {
     try {
         if (debug.OldPath != debug.FilePath && !FtpHelper.SameFile(debug.OldPath, debug.FilePath))
         {
             // Test their modified date
             FtpHelper.Delete(debug.FilePath);
             FtpHelper.Copy(debug.OldPath, debug.FilePath);
         }
     }
     catch (Exception err) {
         debug.ReportException(err);
     }
 }
        public override void Start()
        {
            FtpHelper ftpHelperForWindows = new FtpHelper();

            //ftpHelperForWindows.Download("ftp://10.100.97.145:2101/setup.exe", @"E:\Downloads\setup.exe");
            //DisplayMessage("Download completed.");

            ftpHelperForWindows.DownloadProgressChangedEvent = (object sender, DownloadProgressChangedEventArgs e) =>
            {
                DisplayMessage($"BytesReceived: {e.BytesReceived}, ProgressPercentage: {e.ProgressPercentage}, TotalBytesToReceive: {e.TotalBytesToReceive}, UserState: {e.UserState}");
            };

            ftpHelperForWindows.DownloadAsync("ftp://10.100.97.145:2101/VisualStudio2017_ProductLaunchPoster-1.png", @"E:\Downloads\test.png");
        }
        public override void Start()
        {
            FtpHelper ftpHelper = new FtpHelper(user, pwd);

            try
            {
                ftpHelper.CreateDirectory(url);
                DisplayMessage("Create directory completed!");
            }
            catch (Exception exception)
            {
                DisplayMessage(exception.ToExceptionContent().ToString());
            }
        }
Exemple #25
0
        private async void Downloafile_Click(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender;
            //button.Visibility = Visibility.Collapsed;

            var ftpItmListM    = (FtpListItemModel)button.DataContext;
            var openFileDialog = new System.Windows.Forms.SaveFileDialog();

            openFileDialog.FileName = ftpItmListM.Name;
            openFileDialog.Filter   = "All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                UploadProgress.Visibility = Visibility.Visible;
                DirFileInfo.IsEnabled     = false;
                FileList.IsEnabled        = false;
                var path      = openFileDialog.FileName;
                var ftpHelper = new FtpHelper();
                Progress <FtpProgress> progress = new Progress <FtpProgress>(p =>
                {
                    App.Current.Dispatcher.Invoke((Action) delegate
                    {
                        if (p.Progress == 100)
                        {
                            ftpHelper.Progress = 100;
                            //button.Visibility = Visibility.Visible;
                            UploadProgress.Visibility = Visibility.Collapsed;
                        }
                        else
                        {
                            ftpHelper.TransMessage        = $"Upload from {p.LocalPath} to {p.RemotePath}";
                            ftpHelper.Progress            = Math.Round(p.Progress, 1);
                            ftpHelper.FileCount           = p.FileCount;
                            ftpHelper.FileIndex           = p.FileIndex + 1;
                            ftpHelper.TransferSpeed       = p.TransferSpeed;
                            ftpHelper.EAT                 = p.ETA.ToString(@"hh\:mm\:ss", null);
                            ftpHelper.TransferredBytes    = p.TransferredBytes;
                            ftpHelper.TransferSpeedString = p.TransferSpeedToString();
                        }
                    });
                });
                UploadProgress.DataContext = ftpHelper;
                cancellationTokenSource    = new CancellationTokenSource();
                var res = await ftpHelper.DownloadFileAsync(ftpItmListM.FullName, path, cancellationTokenSource.Token, progress);

                UploadProgress.Visibility = Visibility.Collapsed;
                DirFileInfo.IsEnabled     = true;
                FileList.IsEnabled        = true;
            }
        }
Exemple #26
0
        private void s(object arg)
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 1000;

            // int find_id=(int)arg;
            // ftpItem item = ftpItems.Find(finditem=>{
            //     if (finditem.ID == find_id)
            //     {
            //         return true;
            //     }
            //     return false;
            //});

            ftpItem item = (ftpItem)arg;

            FtpHelper ftp = null;

            System.Uri compal_ftp_uri      = new Uri("ftp://" + item.ADDRESS + ":21");
            string     compal_ftp_username = item.USERNAME;
            string     compal_ftp_psd      = item.PSWD;

            ftp = new FtpHelper(compal_ftp_uri, compal_ftp_username, compal_ftp_psd);

            timer.Elapsed += (sender, args) =>
            {
                System.Timers.Timer t = (System.Timers.Timer)sender;//当前的计时器
                //进入先关闭
                t.Stop();
                i++;
                this.txt_templetename.Text = i.ToString();
                if (!item.Statusflag)//标志是否关闭
                {
                    t.Stop();
                    Thread.CurrentThread.Abort();//结束当前进程
                    //从list中移除关闭的
                    ftpItems.Remove(item);
                }
                else
                {
                    //调用ftp程式
                    getFtpFile(item, ftp);
                }

                //结束再打开
                t.Start();
            };
            timer.Start();
        }
Exemple #27
0
        public void WriteFile(string path)
        {
            StringBuilder builder = new StringBuilder();

            string[] array = ToArray();

            for (int index = 0; index < array.Length; index++)
            {
                string line = array[index];
                builder.Append(line);
                builder.Append(_newLine);
            }

            FtpHelper.WriteAllText(path, builder.ToString());
        }
        private List <indexStockInfo> getDocumentFromFtp(string index)
        {
            FtpHelper             ftp  = new FtpHelper("192.168.38.213", "index", "dfzq1234");
            List <indexStockInfo> list = new List <indexStockInfo>();

            string[] indexStr = index.Split('.');
            string   todayStr = date.Year.ToString();
            string   filename = getFileName(index, date, "weightnextday", "xls");
            string   original = "\\hs300\\" + filename;
            string   target   = "E:\\result\\stockBonusEstimate\\" + filename;

            ftp.Download(original, target);
            var set = DataTableExtension.getDataSetFromXLS(target);

            foreach (DataTable dt in set.Tables)
            {
                int num = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    num = num + 1;
                    //去除表头
                    if (num <= 1)
                    {
                        continue;
                    }
                    indexStockInfo info    = new indexStockInfo();
                    string         code    = Convert.ToString(dr[4]);
                    string         market  = Convert.ToString(dr[7]);
                    string         secName = Convert.ToString(dr[5]);
                    if (market == "Shanghai")
                    {
                        code = code + ".SH";
                    }
                    else
                    {
                        code = code + ".SZ";
                    }
                    double close  = Convert.ToDouble(dr[12]);
                    double weight = Convert.ToDouble(dr[16]);
                    info.code    = code;
                    info.secName = secName;
                    info.close   = close;
                    info.weight  = weight;
                    list.Add(info);
                }
            }
            return(list);
        }
Exemple #29
0
        /// <summary>
        /// Saves the database.
        /// </summary>
        /// <param name="ap">The progress object.</param>
        /// <param name="progress"> </param>
        public virtual void Save(AsyncOperation ap, IProgress progress)
        {
            string     dbPath     = GrfPath.GetDirectoryName(ProjectConfiguration.DatabasePath);
            string     subPath    = ProjectConfiguration.DatabasePath.Replace(dbPath, "").TrimStart('\\', '/');
            ServerType serverType = DbPathLocator.GetServerType();

            DbDebugHelper.OnUpdate("Saving tables.");

            MetaGrf.Clear();

            try {
                BackupEngine.Instance.Start(ProjectConfiguration.DatabasePath);

                var dbs = _dbs.Values.ToList();

                FtpHelper.SetupFileManager();

                for (int i = 0; i < dbs.Count; i++)
                {
                    var db = dbs[i];
                    db.WriteDb(dbPath, subPath, serverType);

                    if (progress != null)
                    {
                        progress.Progress = AProgress.LimitProgress((i + 1f) / dbs.Count * 100f);
                    }
                }

                foreach (var db in dbs)
                {
                    db.SaveCommandIndex();
                }

                Commands.SaveCommandIndex();
            }
            catch (Exception err) {
                ErrorHandler.HandleException(err);
            }
            finally {
                if (ap != null && progress != null)
                {
                    progress.Progress = ap.ProgressBar.GetIntermediateState("Backup manager");
                }

                BackupEngine.Instance.Stop();
                DbDebugHelper.OnUpdate("Finished saving tables.");
            }
        }
Exemple #30
0
        public override void Start()
        {
            //FtpHelper ftpHelperForWindows = new FtpHelper();

            //foreach (string line in ftpHelperForWindows.ListDetails("ftp://10.100.97.145:2101/"))
            //{
            //    DisplayMessage(line);
            //}

            FtpHelper ftpHelperForUnix = new FtpHelper(user, pwd);

            foreach (string line in ftpHelperForUnix.ListDetails(url))
            {
                DisplayMessage(line);
            }
        }