public void sendImage(Bitmap bitmap) { try { string fileName = createImageName() + ".jpg"; string imageFilePath = Application.StartupPath.ToString() + "/" + chat.ChatId + "/" + fileName; bitmap.Save(imageFilePath, System.Drawing.Imaging.ImageFormat.Jpeg); FtpUpload ftpUpload = new FtpUpload(imageFilePath, uploadURL + "/" + fileName); operatorServiceAgent.SendFile(fileName, chat.ChatId, "start"); string msg = string.Format("<span style=\"font-family: Arial;color:blue;font-weight: bold;font-size: 12px;\">{0} :</span><br/><span style=\"font-family: Arial;font-size: 12px;\"><img src='{1}' /></span><br />", operatorServiceAgent.CurrentOperator.NickName + " " + DateTime.Now.ToString("hh:mm:ss"), imageFilePath); chatMessageViewerControl1.AddText(msg); uploadTasks.Add(ftpUpload); ftpUpload.FileUploadProgress += new EventHandler <FileUploadProgressEventArgs>(ftpUpload_FileUploadProgress); ftpUpload.Start(); } catch (ExternalException eex) { Trace.WriteLine("sendImage ExternalException:" + eex.Message); chatMessageViewerControl1.AddInformation("网络出现问题,暂时无法获取及发送消息"); return; } catch (Exception ex) { Trace.WriteLine("sendImage exception:" + ex.Message); chatMessageViewerControl1.AddInformation("网络出现问题,暂时无法获取及发送消息"); return; } }
public static void MoveFile(FtpMove ftpMove) { var ftpConfigDownload = new FtpDownload(new FtpConfig(new Uri($"{ftpMove.FtpConfig.Uri}/{ftpMove.From}"), ftpMove.FtpConfig.Login, ftpMove.FtpConfig.Password), ftpMove.FileName); var downloadContet = DownloadFile(ftpConfigDownload); var ftpConfigMove = new FtpUpload(new FtpConfig(new Uri($"{ftpMove.FtpConfig.Uri}/{ftpMove.To}"), ftpMove.FtpConfig.Login, ftpMove.FtpConfig.Password), downloadContet, ftpMove.FileName); var ftpDelete = new FtpDelete(new FtpConfig(new Uri($"{ftpMove.FtpConfig.Uri}/{ftpMove.From}"), ftpMove.FtpConfig.Login, ftpMove.FtpConfig.Password), ftpMove.FileName); DeleteFile(ftpDelete); UploadFile(ftpConfigMove); }
public void FtpExecute() { ZipTest zip = new ZipTest(); zip.ZipExecute(); FtpUpload task = new FtpUpload(); task.BuildEngine = new MockBuild(); string testDir = TaskUtility.TestDirectory; task.LocalFile = Path.Combine(testDir, ZipTest.ZIP_FILE_NAME); task.RemoteUri = "ftp://localhost/MSBuild.Community.Tasks.zip"; Assert.IsTrue(task.Execute(), "Execute Failed"); }
/// <summary> /// Start image uploading process to FTP server. /// </summary> private void ftpUploadButton_Click(object sender, RoutedEventArgs e) { MainWindow mainWindow = Owner as MainWindow; ftpUploadButton.IsEnabled = false; ftpUploadCancelButton.IsEnabled = true; ftpUploadProgressBar.Value = 0; try { _ftpUpload = new FtpUpload(this); _ftpUpload.StatusChanged += new EventHandler <Vintasoft.WpfTwain.ImageUploading.Ftp.StatusChangedEventArgs>(_ftpUpload_StatusChanged); _ftpUpload.ProgressChanged += new EventHandler <Vintasoft.WpfTwain.ImageUploading.Ftp.ProgressChangedEventArgs>(_ftpUpload_ProgressChanged); _ftpUpload.Completed += new EventHandler <Vintasoft.WpfTwain.ImageUploading.Ftp.CompletedEventArgs>(_ftpUpload_Completed); _ftpUpload.Host = ftpServerTextBox.Text; int ftpServerPort = 21; try { ftpServerPort = int.Parse(ftpServerPortTextBox.Text); } catch { } _ftpUpload.Port = ftpServerPort; _ftpUpload.User = ftpUserTextBox.Text; _ftpUpload.Password = ftpPasswTextBox.Password; _ftpUpload.PassiveMode = (bool)flagPassModeCheckBox.IsChecked; _ftpUpload.Timeout = 5000; _ftpUpload.Path = ftpPathTextBox.Text; _ftpUpload.AddFile(ftpFileNameTextBox.Text, _acquiredImageToUpload.GetAsStream(GetImageFileFormat(ftpFileNameTextBox.Text))); _ftpUpload.PostData(); } catch (Exception ex) { MessageBox.Show(ex.Message, "FTP error", MessageBoxButton.OK, MessageBoxImage.Error); ftpUploadButton.IsEnabled = true; ftpUploadCancelButton.IsEnabled = false; } finally { ftpUploadProgressBar.Maximum = _ftpUpload.BytesTotal; } }
public static void UploadFile(FtpUpload ftpUpload) { FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create($"{ftpUpload.FtpConfig.Uri}/{ftpUpload.FileName}"); ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile; ftpWebRequest.UseBinary = true; ftpWebRequest.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested; ftpWebRequest.Credentials = new NetworkCredential(ftpUpload.FtpConfig.Login, ftpUpload.FtpConfig.Password); ftpWebRequest.ContentLength = ftpUpload.Content.Length; using (Stream stream = ftpWebRequest.GetRequestStream()) { stream.Write(ftpUpload.Content, 0, ftpUpload.Content.Length); stream.Close(); } }
/// <summary> /// 上传文件控件 /// </summary> /// <param name="fileFullPath">上传的文件全路径</param> /// <param name="saveURL">需要上传到Ftp目录URL</param> public FileUploadControl(string fileFullPath, string saveURL) { InitializeComponent(); this.lblSpeed.Text = "正在传输..."; this.fileFullPath = fileFullPath; this.fileName = fileFullPath.Substring(fileFullPath.LastIndexOf("\\") + 1); this.ftpURL = saveURL.EndsWith("/")? saveURL + fileName : saveURL + "/" + fileName; this.pictureBox1.Image = Common.GetFileIcon(fileFullPath).ToBitmap(); FileInfo fileInfo = new FileInfo(this.fileFullPath); fileSize = fileInfo.Length; progressBar1.Maximum = (int)fileSize; ftpUpload = new FtpUpload(this.fileFullPath, ftpURL); ftpUpload.FileUploadProgress += new EventHandler <FileUploadProgressEventArgs>(ftpUpload_FileUploadProgress); ftpUpload.Start(); }
private static System.Net.FtpWebRequest CreateFtpRequest(ColumnField field, string strFileName) { FtpUpload uploader = field.FtpUpload; string target = GetFtpUploadTarget(field, strFileName); System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.HttpWebRequest.Create(target); //request.Credentials = new System.Net.NetworkCredential(uploader.FtpUserName, uploader.FtpPassword); //request.Credentials = new System.Net.NetworkCredential(uploader.FtpUserName, uploader.GetDecryptedPassword(Map.GetConfigDatabase())); request.Credentials = GetFtpNetworkCredential(field); request.UsePassive = uploader.UsePassive; request.UseBinary = true; request.KeepAlive = false; return(request); }
public void UploadSingleFile() { // set up test environment string testFile = Path.Combine(TaskUtility.TestDirectory, "FtpUploadFile.txt"); string fileContent = "some stuff in this file"; File.WriteAllText(testFile, fileContent); MemoryStream ftpRequestStream = new MemoryStream(); // record expected operations var mockery = new MockRepository(); var ftpService = mockery.CreateMock <IFtpWebRequest>(); var ftpCreator = mockery.CreateMock <IFtpWebRequestCreator>(); FtpUpload task = new FtpUpload(ftpCreator); using (mockery.Record()) { ftpCreator.Create(new Uri("ftp://server.com/folder/FtpUploadFile.txt"), "STOR"); LastCall.Return(ftpService); ftpService.SetContentLength(23); ftpService.GetRequestStream(); LastCall.Return(ftpRequestStream); ftpService.GetStatusDescriptionAndCloseResponse(); LastCall.Return("okay"); } task.BuildEngine = _mockBuild; task.RemoteUri = "ftp://server.com/folder/"; task.LocalFile = testFile; bool result = task.Execute(); Assert.AreEqual(fileContent, GetString(ftpRequestStream)); mockery.VerifyAll(); }
public void Send() { if (this.path == null || this.path.Trim().Equals(string.Empty)) { this.Hint = "请指定上传的FTP目录!"; return; } if (this.fileName == null || this.fileName.Trim().Equals(string.Empty)) { this.Hint = "请选择一个文件!"; } else { string newName = System.IO.Path.GetFileName(this.fileName); FtpUpload ftpUpload = new FtpUpload(this.path, this.fileName, newName); if (this.userName != null && (!this.userName.Trim().Equals(string.Empty))) { ftpUpload.User = this.userName.Trim(); } if (this.pwd != null && (!this.pwd.Trim().Equals(string.Empty))) { ftpUpload.Pwd = this.pwd.Trim(); } try { ftpUpload.Upload(); } catch (Exception) { this.Hint = "文件上传失败,请检查FTP设置!"; return; } this.Hint = "文件上传成功!"; } }
public void UploadSingleFile() { // set up test environment string testFile = Path.Combine(TaskUtility.TestDirectory, "FtpUploadFile.txt"); string fileContent = "some stuff in this file"; File.WriteAllText(testFile, fileContent); MemoryStream ftpRequestStream = new MemoryStream(); // record expected operations var mockery = new MockRepository(); var ftpService = mockery.StrictMock<IFtpWebRequest>(); var ftpCreator = mockery.StrictMock<IFtpWebRequestCreator>(); FtpUpload task = new FtpUpload(ftpCreator); using (mockery.Record()) { ftpCreator.Create(new Uri("ftp://server.com/folder/FtpUploadFile.txt"), "STOR"); LastCall.Return(ftpService); ftpService.SetContentLength(23); ftpService.GetRequestStream(); LastCall.Return(ftpRequestStream); ftpService.GetStatusDescriptionAndCloseResponse(); LastCall.Return("okay"); } task.BuildEngine = _mockBuild; task.RemoteUri = "ftp://server.com/folder/"; task.LocalFile = testFile; bool result = task.Execute(); Assert.AreEqual(fileContent, GetString(ftpRequestStream)); mockery.VerifyAll(); }
public void UploadMultipleFilesInFolderStructure() { // set up test environment string testFile1 = Path.Combine(TaskUtility.TestDirectory, "file1.txt"); string testDir2 = Path.Combine(TaskUtility.TestDirectory, "testfolder"); string testFile2 = Path.Combine(testDir2, "file2.txt"); Directory.CreateDirectory(testDir2); File.WriteAllText(testFile1, "file number one"); File.WriteAllText(testFile2, "file number two"); MemoryStream file1Stream = new MemoryStream(); MemoryStream file2Stream = new MemoryStream(); // record expected operations var mockery = new MockRepository(); var ftpService = mockery.CreateMock<IFtpWebRequest>(); var ftpCreator = mockery.CreateMock<IFtpWebRequestCreator>(); FtpUpload task = new FtpUpload(ftpCreator); using (mockery.Record()) { // this call responds to the FtpUpload's request to list folders; return no folders. ftpCreator.Create(new Uri("ftp://server.com/folder/"), "NLST"); LastCall.Return(ftpService); ftpService.GetResponseStream(); LastCall.Return(new MemoryStream(new byte[0])); // this call should make the testfolder ftpCreator.Create(new Uri("ftp://server.com/folder/testfolder"), "MKD"); LastCall.Return(ftpService); ftpService.GetAndCloseResponse(); // now upload file1 ftpCreator.Create(new Uri("ftp://server.com/folder/file1.txt"), "STOR"); LastCall.Return(ftpService); ftpService.SetContentLength(15); ftpService.GetRequestStream(); LastCall.Return(file1Stream); ftpService.GetStatusDescriptionAndCloseResponse(); LastCall.Return("okay"); // now upload file2 ftpCreator.Create(new Uri("ftp://server.com/folder/testfolder/file2.txt"), "STOR"); LastCall.Return(ftpService); ftpService.SetContentLength(15); ftpService.GetRequestStream(); LastCall.Return(file2Stream); ftpService.GetStatusDescriptionAndCloseResponse(); LastCall.Return("okay"); } task.BuildEngine = _mockBuild; task.RemoteUri = "ftp://server.com/folder/"; task.LocalFiles = TaskUtility.StringArrayToItemArray(testFile1, testFile2); task.RemoteFiles = TaskUtility.StringArrayToItemArray("file1.txt", "testfolder\\file2.txt"); bool result = task.Execute(); Assert.AreEqual("file number one", GetString(file1Stream)); Assert.AreEqual("file number two", GetString(file2Stream)); mockery.VerifyAll(); }
public void UploadMultipleFilesInFolderStructure() { // set up test environment string testFile1 = Path.Combine(TaskUtility.TestDirectory, "file1.txt"); string testDir2 = Path.Combine(TaskUtility.TestDirectory, "testfolder"); string testFile2 = Path.Combine(testDir2, "file2.txt"); Directory.CreateDirectory(testDir2); File.WriteAllText(testFile1, "file number one"); File.WriteAllText(testFile2, "file number two"); MemoryStream file1Stream = new MemoryStream(); MemoryStream file2Stream = new MemoryStream(); // record expected operations var mockery = new MockRepository(); var ftpService = mockery.CreateMock <IFtpWebRequest>(); var ftpCreator = mockery.CreateMock <IFtpWebRequestCreator>(); FtpUpload task = new FtpUpload(ftpCreator); using (mockery.Record()) { // this call responds to the FtpUpload's request to list folders; return no folders. ftpCreator.Create(new Uri("ftp://server.com/folder/"), "NLST"); LastCall.Return(ftpService); ftpService.GetResponseStream(); LastCall.Return(new MemoryStream(new byte[0])); // this call should make the testfolder ftpCreator.Create(new Uri("ftp://server.com/folder/testfolder"), "MKD"); LastCall.Return(ftpService); ftpService.GetAndCloseResponse(); // now upload file1 ftpCreator.Create(new Uri("ftp://server.com/folder/file1.txt"), "STOR"); LastCall.Return(ftpService); ftpService.SetContentLength(15); ftpService.GetRequestStream(); LastCall.Return(file1Stream); ftpService.GetStatusDescriptionAndCloseResponse(); LastCall.Return("okay"); // now upload file2 ftpCreator.Create(new Uri("ftp://server.com/folder/testfolder/file2.txt"), "STOR"); LastCall.Return(ftpService); ftpService.SetContentLength(15); ftpService.GetRequestStream(); LastCall.Return(file2Stream); ftpService.GetStatusDescriptionAndCloseResponse(); LastCall.Return("okay"); } task.BuildEngine = _mockBuild; task.RemoteUri = "ftp://server.com/folder/"; task.LocalFiles = TaskUtility.StringArrayToItemArray(testFile1, testFile2); task.RemoteFiles = TaskUtility.StringArrayToItemArray("file1.txt", "testfolder\\file2.txt"); bool result = task.Execute(); Assert.AreEqual("file number one", GetString(file1Stream)); Assert.AreEqual("file number two", GetString(file2Stream)); mockery.VerifyAll(); }
public void OneKeySend() { if (this.SendList == null || this.SendList.Count == 0) { this.Hint = "请至少选择一个分发产品!"; return; } if (this.EmailOptions != null && this.EmailOptions.Count > 0) { this.Hint = "Email发送中..."; EmailSend email = new EmailSend(); email.EmailTo = new List <string>(); foreach (var item in this.EmailOptions) { if (item.IsSelected == true) { email.EmailTo.Add(item.Address.EmailName); } } email.Subject = ""; email.AttFileName = new List <string>(); foreach (var item in this.SendList) { email.AttFileName.Add(item); FileInfo fi = new FileInfo(item); if (fi.Extension.Equals(".doc") || fi.Extension.Equals(".docx")) { string name = Path.GetFileNameWithoutExtension(item); email.Subject = name; break; } email.Subject += new FileInfo(item).Name + " | "; } if (email.EmailTo.Count > 0) { email.Send(); } this.Hint = "Email发送完成!"; } if (this.NotesOptions != null && this.NotesOptions.Count > 0) { this.Hint = "Notes发送中..."; NotesSend notes = new NotesSend(); notes.MailTo = new List <string>(); foreach (var item in this.NotesOptions) { if (item.IsSelected == true) { notes.MailTo.Add(item.Address.NotesName); } } notes.Subject = ""; notes.AttFileName = new List <string>(); foreach (var item in this.SendList) { notes.AttFileName.Add(item); FileInfo fi = new FileInfo(item); if (fi.Extension.Equals(".doc") || fi.Extension.Equals(".docx")) { string name = Path.GetFileNameWithoutExtension(item); notes.Subject = name; break; } notes.Subject += new FileInfo(item).Name + " | "; } if (notes.MailTo.Count > 0) { notes.SendMail(); } this.Hint = "Notes发送完成!"; } if (this.ftpOptions != null && this.ftpOptions.Count > 0) { this.Hint = "FTP上传中..."; foreach (var op in this.ftpOptions) { if (op.IsSelected == true) { foreach (var file in this.SendList) { string newName = Path.GetFileName(new FileInfo(file).Name); FtpUpload ftpUpload = new FtpUpload(op.Address.FtpPath, file, newName); if (op.Address.FtpUserName != null && (!op.Address.FtpUserName.Trim().Equals(string.Empty))) { ftpUpload.User = op.Address.FtpUserName.Trim(); } if (op.Address.FtpPwd != null && (!op.Address.FtpPwd.Trim().Equals(string.Empty))) { ftpUpload.Pwd = op.Address.FtpPwd.Trim(); } try { ftpUpload.Upload(); } catch (Exception) { this.Hint = "FTP文件上传失败,请检查FTP设置!"; } } } } this.Hint = "FTP上传完成!"; } if (this.lanOptions != null && this.lanOptions.Count > 0) { this.Hint = "局域网上传中..."; foreach (var op in this.lanOptions) { if (op.IsSelected == true) { foreach (var file in this.SendList) { LanSend lanSend = new LanSend(file.Trim(), op.Address.LanPath.Trim()); if (op.Address.LanName != null && (!op.Address.LanName.Trim().Equals(string.Empty))) { lanSend.UserName = op.Address.LanName.Trim(); } if (op.Address.LanPwd != null && (!op.Address.LanPwd.Trim().Equals(string.Empty))) { lanSend.Pwd = op.Address.LanPwd.Trim(); } if (lanSend.SendFile() != true) { this.Hint = file + "上传失败!"; } } } } this.Hint = "局域网上传完成!"; this.Hint = "一键分发完成!"; } }
public Build() { // The configuration ("Debug", etc.) defaults to "Release". var configuration = Cake.Argument("configuration", "Release"); // Git .ignore file should ignore this folder. // Here, we name it "Releases" (default , it could be "Artefacts", "Publish" or anything else, // but "Releases" is by default ignored in https://github.com/github/gitignore/blob/master/VisualStudio.gitignore. var releasesDir = Cake.Directory("CodeCakeBuilder/Releases"); Task("Clean") .Does(() => { // Avoids cleaning CodeCakeBuilder itself! Cake.CleanDirectories("**/bin/" + configuration, d => !d.Path.Segments.Contains("CodeCakeBuilder")); Cake.CleanDirectories("**/obj/" + configuration, d => !d.Path.Segments.Contains("CodeCakeBuilder")); Cake.CleanDirectories(releasesDir); }); Task("Restore-NuGet-Packages") .Does(() => { Cake.Information("Restoring nuget packages for existing .sln files at the root level.", configuration); foreach (var sln in Cake.GetFiles("*.sln")) { Cake.NuGetRestore(sln); } }); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { Cake.Information("Building all existing .sln files at the root level with '{0}' configuration (excluding this builder application).", configuration); foreach (var sln in Cake.GetFiles("*.sln")) { using (var tempSln = Cake.CreateTemporarySolutionFile(sln)) { // Excludes "CodeCakeBuilder" itself from compilation! tempSln.ExcludeProjectsFromBuild("CodeCakeBuilder"); Cake.MSBuild(tempSln.FullPath, new MSBuildSettings() .SetConfiguration(configuration) .SetVerbosity(Verbosity.Minimal) .SetMaxCpuCount(1)); } } }); Task("CopyFiles") .IsDependentOn("Unit-Tests") .Does(() => { if (Cake.AppVeyor().IsRunningOnAppVeyor) { var path = "./Wander.Server/"; var files = Cake.GetFiles(path + "*"); string tmp = "./tmp"; if (!Directory.Exists(tmp)) { Directory.CreateDirectory(tmp); } else { Directory.Delete(tmp, true); Directory.CreateDirectory(tmp); } DirectoryPath path2 = new DirectoryPath(path); DirectoryPath d = new DirectoryPath(tmp + "/"); this.Cake.CopyDirectory(path2, d); Directory.Delete(tmp + "/Properties", true); Directory.Delete(tmp + "/obj", true); Directory.Delete(tmp + "/Model", true); Directory.Delete(tmp + "/Hubs", true); this.Cake.DeleteFiles(tmp + "/*.cs"); this.Cake.DeleteFiles(tmp + "/*.csproj"); } else { Cake.Information("Not running on appveyor, skipping..."); } }); Task("Package") .IsDependentOn("CopyFiles") .Does(() => { if (Cake.AppVeyor().IsRunningOnAppVeyor) { string pswd = Environment.GetEnvironmentVariable("FTP_PASSWORD"); if (pswd != null) { string output = "./output"; if (!Directory.Exists(output)) { Directory.CreateDirectory(output); } else { Directory.Delete(output, true); Directory.CreateDirectory(output); } string tmp = "./tmp"; Cake.Information("Zipping..."); Cake.Zip(tmp + "/", output + "/build.zip"); Cake.Information("Deploying"); FtpUpload ftp = new FtpUpload(@"ftp://labo.nightlydev.fr/", "administrateur", pswd, "z", tmp); ftp.Start(); Directory.Delete(tmp, true); Directory.Delete(output, true); } } else { Cake.Information("Not running on appveyor, skipping..."); } }); Task("DBSetup") .IsDependentOn("Build") .Does( () => { string db = Cake.InteractiveEnvironmentVariable("DB_CONNECTION_STRING"); if (Cake.AppVeyor().IsRunningOnAppVeyor) { db = @"Server=(local)\SQL2014;Database=master;User ID=sa;Password=Password12!"; } if (String.IsNullOrEmpty(db)) db = @"Data Source=(localdb)\ProjectsV12;Initial Catalog=WanderDB;Integrated Security=True;"; Cake.Information("Using database: {0}", db); SqlConnection conn = new SqlConnection(db); string filePath = "Docs/BDD/create.sql"; if (System.IO.File.Exists(filePath)) { string create = System.IO.File.ReadAllText(filePath); string[] commands = create.Split(new string[] { "GO" }, StringSplitOptions.None); IEnumerable<string> commandStrings = Regex.Split(create, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase); conn.Open(); foreach (string commandString in commandStrings) { if (commandString.Trim() != "") { using (var command = new SqlCommand(commandString, conn)) { command.ExecuteNonQuery(); } } } conn.Close(); } }); Task("Unit-Tests") .IsDependentOn("DBSetup") .Does(() => { Cake.MSTest("**/bin/" + configuration + "/*.Tests.dll"); }); Task("Default").IsDependentOn("Package"); }
private void btnUploadTest_Click(object sender, EventArgs e) { FtpUpload.UploadFiles("ftp://127.0.0.1/", "tester", "test123", new FileInfo("C:\\test1.txt")); }