public void UploadDocs() { using (var ftp = new FtpConnection("ftp.thewizards.be", "thewizards.be", "eroU0Ioti")) { ftp.Open(); /* Open the FTP connection */ ftp.Login(); /* Login using previously provided credentials */ var docFiles = getDocFilesEnumerable("Gameplay") .Union(getDocFilesEnumerable("NewModules")) //.Union(getDocFilesEnumerable("ApplicationLogic")) //.Union(getDocFilesEnumerable("DirectX11")) .Union(getDocFilesEnumerable("Common.Core")) .Union(getDocFilesEnumerable("Networking")) //.Union(getDocFilesEnumerable("DocumentationHelper")) //.Union(getDocFilesEnumerable("Tools")) ; try { string uploadRoot = "/wiki/data/pages/source"; //uploadBuildFolder(ftp, docFiles, uploadRoot); } catch (FtpException e) { File.AppendAllText("log.txt", e.ToString()); Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message)); } } }
/// <summary> /// method to upload the contents of a file from a remote URI /// </summary> /// <param name="ftpUri"></param> /// <param name="user"></param> /// <param name="pass"></param> /// <returns></returns> public void PostFileToSite(string fileName) { try { using (FtpLib.FtpConnection ftp = new FtpLib.FtpConnection(_ftpSite.Site, _ftpSite.Username, _ftpSite.Password)) { try { ftp.Open(); /* Open the FTP connection */ ftp.Login(); /* Login using previously provided credentials */ //ftp.SetCurrentDirectory(m_FTPServerDirectory); /* change current directory */ ftp.PutFile(fileName); } catch (FtpLib.FtpException e) { LogIt("FtpMgr::PostFileToSite():FtpExceptionCaught: " + e.Message); LogIt(e.StackTrace); } } } catch (FtpLib.FtpException e) { LogIt("FtpMgr::PostFileToSite():FtpExceptionCaught: " + e.Message); LogIt(e.StackTrace); } }
/// <summary> /// method to upload the contents of a file from a remote URI /// </summary> /// <param name="ftpUri"></param> /// <param name="user"></param> /// <param name="pass"></param> /// <returns></returns> public void PostFileToSite(string fileName) { try { using (FtpLib.FtpConnection ftp = new FtpLib.FtpConnection(_ftpSite.Site, _ftpSite.Username, _ftpSite.Password)) { try { ftp.Open(); /* Open the FTP connection */ ftp.Login(); /* Login using previously provided credentials */ //ftp.SetCurrentDirectory(m_FTPServerDirectory); /* change current directory */ ftp.PutFile(fileName); } catch (FtpLib.FtpException e) { LogIt("FtpMgr::PostFileToSite():FtpExceptionCaught: " + e.Message); LogIt(e.StackTrace); } } } catch (FtpLib.FtpException e) { LogIt("FtpMgr::PostFileToSite():FtpExceptionCaught: " + e.Message); LogIt(e.StackTrace); } }
/// <summary> /// main method used to process the files every configurable interval /// </summary> public void ProcessFileControlThread() { string theFileToGrab = String.Empty; // main processing thread while (true) { try { using (FtpLib.FtpConnection ftp = new FtpLib.FtpConnection(m_FTPFolder, m_FTPUserName, m_FTPPwd)) { try { ftp.Open(); /* Open the FTP connection */ ftp.Login(); /* Login using previously provided credentials */ ftp.SetCurrentDirectory(m_FTPServerDirectory); /* change current directory */ FtpLib.FtpFileInfo[] flist = ftp.GetFiles(); foreach (FtpLib.FtpFileInfo fi in flist) { if (!_dbMgr.CheckDbBeforeDownloadingFile(fi.Name)) { try { string fil = m_FTPServerDirectory + fi.Name; if (ftp.FileExists(fil)) /* check that a file exists */ { ftp.GetFile(fil, m_FtpFileToLocation + fi.Name, false); FileWriter.Instance.WriteToLogFile("FtpHandler::ProcessFileControlThread:DownloadedFile" + fi.Name); // update the db so we do not download again _dbMgr.UpdateFtpFileNameInDb(fi.Name); } } catch (SystemException se) { FileWriter.Instance.WriteToLogFile("FtpHandler::ProcessControlThread:EXCEPTIONCAUGHT(Open/Login/Directory)::" + se.Message); FileWriter.Instance.WriteToLogFile(se.StackTrace); } } } } catch (SystemException se) { FileWriter.Instance.WriteToLogFile("FtpHandler::ProcessFileControlThread:EXCEPTIONCAUGHT::" + se.Message); } } } catch (SystemException se) { FileWriter.Instance.WriteToLogFile("FtpHandler::ProcessFileControlThread:EXCEPTIONCAUGHT::TryingToConnect" + se.Message); } // wait for the next interval to ftp the next file over System.Threading.Thread.Sleep(m_runIntervalInSeconds); } // while(true) } //ProcessFileControlThread
public static bool DeleteImage(string imgName) { try { FtpConnection conn = new FtpConnection(ftpServer, 21, ftpUser, ftpPassword); conn.Open(); conn.Login(); conn.SetCurrentDirectory("/ion"); conn.RemoveFile(imgName + ".jpg"); return true; } catch { return false; } }
/// <param name="imgPath">Calea catre poza de le computer.</param> /// <param name="newName">Numele imaginii de pe server.</param> public static bool UploadImage(string imgPath, string newName) { try { FtpConnection conn = new FtpConnection(ftpServer, 21, ftpUser, ftpPassword); conn.Open(); conn.Login(); conn.SetCurrentDirectory("/ion"); conn.PutFile(imgPath, newName + ".jpg"); return true; } catch { return false; } }
/// <summary> /// Sterge o imagine de pe contul FTP. /// </summary> /// <param name="imgName">Numele imaginii de pe contul FTP.</param> /// <returns>True, daca s-a sters si False daca a aparut o eroare.</returns> public static bool DeleteImage(string imgName) { try { FtpConnection conn = new FtpConnection(Globals.FTP_SERVER, 21, Globals.FTP_USER, Globals.FTP_PASSWORD); conn.Open(); conn.Login(); conn.SetCurrentDirectory("/public_html/CompanyWorkManagement/"); conn.RemoveFile(imgName + ".jpg"); return true; } catch { return false; } }
public void test() { if (Directory.Exists(workingDirectory)) { Directory.Delete(workingDirectory, true); Directory.CreateDirectory(workingDirectory); } else { Directory.CreateDirectory(workingDirectory); } using (ftp = new FtpConnection(txtServername.Text,21, txtUsername.Text, txtPassword.Text)) { ftp.Open(); /* Open the FTP connection */ ftp.Login(); /* Login using previously provided credentials */ if (ftp.DirectoryExists(txtRootDir.Text)) /* check that a directory exists */ { ftp.SetCurrentDirectory(txtRootDir.Text); /* change current directory */ } // StreamReader reader = new StreamReader(txtBrowse.Text); try { string line = string.Empty; FtpDirectoryInfo info = ftp.GetCurrentDirectoryInfo(); fileInfos = info.GetFiles(); foreach (FtpFileInfo item in fileInfos) { //ftp.GetFile(item.Name, Directory.GetCurrentDirectory() + @"\Output\" + line + @"\item.Name", false); ListboxItem listBoxItem = new ListboxItem(); listBoxItem.fileName = item.Name; listBoxItem.filePath = txtRootDir.Text + item.Name; lstFiles.Items.Add(listBoxItem); } //ftp.SetCurrentDirectory(@"/loth2/itsred/caixa/3.1.22.PROD"); ftp.SetLocalDirectory(workingDirectory); ftp.GetFile(fileInfos[1].Name,false); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { ftp.Close(); } } }
public void Test() { using (var ftp = new FtpConnection("172.19.1.54", "", "")) { ftp.Open(); /* Open the FTP connection */ ftp.Login(); /* Login using previously provided credentials */ //if (ftp.DirectoryExists("SupportTicketAttachments")) /* check that a directory exists */ // ftp.SetCurrentDirectory("SupportTicketAttachments"); /* change current directory */ //if (ftp.FileExists("20111124_121722_campaign-manager.png")) /* check that a file exists */ ftp.GetFile("SupportTicketAttachments/20111124_121722_campaign-manager.png", @"D:\XariosWebData\Tickets\_Temp\20111124_121722_campaign-manager.png", false); /* download /incoming/file.txt as file.txt to current executing directory, overwrite if it exists */ //ftp.SetCurrentDirectory("monkeys2"); //ftp.PutFile(@"D:\XariosWebData\Tickets\_Temp\20111124_121722_campaign-manager.png"); //ftp.Close(); //do some processing /*try { ftp.SetCurrentDirectory("/outgoing"); ftp.PutFile(@"c:\localfile.txt", "file.txt"); // upload c:\localfile.txt to the current ftp directory as file.txt } catch (FtpException e) { Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message)); } foreach (var dir in ftp.GetDirectories("/incoming/processed")) { Console.WriteLine(dir.Name); Console.WriteLine(dir.CreationTime); foreach (var file in dir.GetFiles()) { Console.WriteLine(file.Name); Console.WriteLine(file.LastAccessTime); } }*/ } }
public FileFilter CopyFromFtp(FtpDirectory ftpDir, string destinationDirectory) { using (FtpConnection ftpConnection = new FtpConnection(ftpDir.Host, ftpDir.Port, ftpDir.Username, ftpDir.Password)) { ftpConnection.Open(); ftpConnection.Login(); foreach (string ftpPath in GetFtpFilesAndFolders(ftpDir.BaseDirectory, ftpConnection)) { if (ftpConnection.DirectoryExists(ftpPath)) { var combinedPath = Path.Combine(destinationDirectory, PathWithoutBaseDirectory(ftpPath, ftpDir.BaseDirectory).TrimStart('/')); if (!Directory.Exists(combinedPath)) { Directory.CreateDirectory(combinedPath); } } else { if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } var combinedPath = Path.Combine(destinationDirectory, PathWithoutBaseDirectory(ftpPath, ftpDir.BaseDirectory).TrimStart('/')); var newPath = Path.GetDirectoryName(combinedPath); if (!Directory.Exists(newPath)) { Directory.CreateDirectory(newPath); } ftpConnection.GetFile(ftpPath, combinedPath, false); } } ftpConnection.Close(); } return this; }
private void btnEdit_Click(object sender, EventArgs e) { try { using (ftp = new FtpConnection(txtServername.Text, 21, txtUsername.Text, txtPassword.Text)) { ftp.Open(); /* Open the FTP connection */ ftp.Login(); if (ftp.DirectoryExists(txtRootDir.Text)) /* check that a directory exists */ { ftp.SetCurrentDirectory(txtRootDir.Text); /* change current directory */ } ListboxItem selectedItem = lstFiles.SelectedItem as ListboxItem; ftp.SetLocalDirectory(workingDirectory); ftp.GetFile(selectedItem.fileName,false); StreamReader reader = new StreamReader(workingDirectory + @"\" + selectedItem.fileName,Encoding.Default); txtFileContent.Text = reader.ReadToEnd().Replace("\n","\r\n"); } ftp.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); ftp.Close(); } }
public FileFilter CopyToFtp(string sourceDirectory, FtpDirectory ftpDir) { using (FtpConnection ftpConnection = new FtpConnection(ftpDir.Host, ftpDir.Port, ftpDir.Username, ftpDir.Password)) { ftpConnection.Open(); ftpConnection.Login(); foreach (WrappedFileSystemInfo fileSystemInfo in GetFilesAndFolders(sourceDirectory)) { if (fileSystemInfo is WrappedDirectoryInfo) { var combinedPath = Path.Combine(ftpDir.BaseDirectory, fileSystemInfo.PathWithoutBaseDirectory); if (!ftpConnection.DirectoryExists(combinedPath)) ftpConnection.CreateDirectory(combinedPath); } else { if (!ftpConnection.DirectoryExists(ftpDir.BaseDirectory)) { ftpConnection.CreateDirectory(ftpDir.BaseDirectory); } var combinedPath = Path.Combine(ftpDir.BaseDirectory, fileSystemInfo.PathWithoutBaseDirectory); var newPath = Path.GetDirectoryName(combinedPath); if (!ftpConnection.DirectoryExists(newPath)) { ftpConnection.CreateDirectory(newPath); } ftpConnection.SetCurrentDirectory(newPath); ftpConnection.PutFile(fileSystemInfo.FullName); } } } return this; }
public void PublishToGitFTP(DeploymentModel model) { if (model.AzureDeployment) { var remoteProcess = Process.Start("\"" + gitLocation + "\"", " --git-dir=\"" + fullRepoPath + "\" remote add blog " + model.AzureRepo); if (remoteProcess != null) remoteProcess.WaitForExit(); var pushProcess = Process.Start("\"" + gitLocation + "\"", " --git-dir=\"" + fullRepoPath + "\" push -f blog master"); if (pushProcess != null) pushProcess.WaitForExit(); } else { using (ftp = new FtpConnection(model.FTPServer, model.FTPUsername, model.FTPPassword)) { try { ftp.Open(); ftp.Login(); if (!string.IsNullOrWhiteSpace(model.FTPPath)) { if (!ftp.DirectoryExists(model.FTPPath)) { ftp.CreateDirectory(model.FTPPath); } ftp.SetCurrentDirectory(model.FTPPath); } FtpBlogFiles(snowPublishPath, model.FTPPath); } catch (Exception ex) { } } } }
public void DeleteFromFtp(FtpDirectory ftpDir) { using (FtpConnection ftpConnection = new FtpConnection(ftpDir.Host, ftpDir.Port, ftpDir.Username, ftpDir.Password)) { ftpConnection.Open(); ftpConnection.Login(); var paths = GetFtpFilesAndFolders(ftpDir.BaseDirectory, ftpConnection); paths.Reverse(); foreach (var path in paths) { var fullPath = ftpDir.BaseDirectory + path; if (ftpConnection.DirectoryExists(fullPath)) RemoveDirectoryEvenIfNotEmpty(ftpConnection, fullPath); else { ftpConnection.RemoveFile(fullPath); } } ftpConnection.Close(); } }
private string CopyComparisonScript(string refHost, string refEnv) { string remoteScriptName = string.Empty; FtpConnection connection = new FtpConnection(refHost, "mxftp", "mxftp"); string localFileName = Path.GetTempFileName(); CommonUtils.WriteFile(localFileName, ComparisonScript); try { try { connection.Open(); //bgDoServerWork.ReportProgress(5, "Validating Results..."); } catch (Exception ex) { CommonUtils.ShowError(ex.Message, ex); } connection.Login(); connection.SetCurrentDirectory(refEnv); //Path.GetTempFileName remoteScriptName = Path.GetFileName(localFileName); connection.PutFile(localFileName); connection.RenameFile(remoteScriptName, Path.GetFileNameWithoutExtension(remoteScriptName) + ".sh"); //connection.SendCommand("chmod 777 " + Path.GetFileNameWithoutExtension(remoteScriptName) + ".sh"); remoteScriptName = Path.GetFileNameWithoutExtension(remoteScriptName) + ".sh"; } finally { connection.Close(); connection.Dispose(); } return remoteScriptName; }
private void StartComparison(string inputEnv, string inputHost, string refEnv, string refHost, string compareScriptLocation, out DataTable resultsTable) { resultsTable = new DataTable(); string scriptHost = "dell014srv"; bgDoServerWork.ReportProgress(5, "Validating environments..."); if (LOCAL_TA_USAGE || IsValidToBeginDiff(inputEnv, inputHost, refEnv, refHost, compareScriptLocation, scriptHost)) { bgDoServerWork.ReportProgress(5, "Connecting to Hosts..."); if (bgDoServerWork.CancellationPending) { WorkerWasCancelled = true; return; } //CopyComparisonScript(refHost, refEnv); SshStream ssh = new SshStream(scriptHost, "autoengine", ""); //Set the end of response matcher character string response = string.Empty; try { ssh.Prompt = "\\$"; //Remove terminal emulation characters ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel //tmReturn.Start(); //Remove terminal emulation characters ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel ssh.Write("cd " + compareScriptLocation); //Reading from the SSH channel response = ssh.ReadResponse(); } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } string comparisonFolderName = DateTime.Now.Ticks.ToString(); string comparisonFileName = comparisonFolderName + "comparison.log"; if (bgDoServerWork.CancellationPending) { WorkerWasCancelled = true; return; } try { ssh.Write("mkdir " + comparisonFolderName); response = ssh.ReadResponse(); ssh.Write("cp comparison88.sh " + comparisonFolderName); response = ssh.ReadResponse(); ssh.Write("cd " + comparisonFolderName); //Reading from the SSH channel response = ssh.ReadResponse(); ssh.Write("comparison88.sh " + "/net/" + refHost + refEnv + " /net/" + inputHost + inputEnv + " -A >" + comparisonFileName); bgDoServerWork.ReportProgress(5, "Starting Comparison..."); response = ssh.ReadResponse(); ssh.Write("d"); response = ssh.ReadResponse(); } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } bgDoServerWork.ReportProgress(5, "Comparison Completed"); if (bgDoServerWork.CancellationPending) { WorkerWasCancelled = true; return; } FtpConnection connection = new FtpConnection(scriptHost, "mxftp", "mxftp"); string localFileName = Path.GetTempFileName(); try { try { try { connection.Open(); bgDoServerWork.ReportProgress(5, "Validating Results..."); } catch (Exception ex) { CommonUtils.ShowError(ex.Message, ex); } connection.Login(); connection.SetCurrentDirectory(compareScriptLocation + comparisonFolderName); //Path.GetTempFileName connection.GetFile(comparisonFileName, localFileName, false); connection.RemoveFile(comparisonFileName); connection.SetCurrentDirectory(compareScriptLocation); bgDoServerWork.ReportProgress(5, "Building Output..."); } finally { connection.Close(); connection.Dispose(); } } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } try { ssh.Write("cd .."); //Reading from the SSH channel response = ssh.ReadResponse(); ssh.Write("rm -rf " + comparisonFolderName); //Reading from the SSH channel response = ssh.ReadResponse(); ssh.Flush(); ssh.Close(); ssh.Dispose(); if (bgDoServerWork.CancellationPending) { WorkerWasCancelled = true; return; } } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } try { string readFile = CommonUtils.ReadFile(localFileName); // Regex regex = new Regex("-.*-"); string[] array = new string[1]; // array[0]= regex.Match(readFile).Value; array[0] = "\n\n"; string[] splitFile = readFile.Split(array, StringSplitOptions.RemoveEmptyEntries); int counter = 1; bgDoServerWork.ReportProgress(5, "Displaying Results..."); Regex diffRegex = new Regex("diff.*"); DataTable results = new DataTable(); results.Columns.Add("Number"); results.Columns.Add("Operation"); results.Columns.Add("FileSize"); results.Columns.Add("FileModifyDate"); results.Columns.Add("FileType"); results.Columns.Add("FileName"); List<string> monthAbbreviations = new List<string>() { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; for (int j = 2; j < splitFile.Length; j++) { string[] splitByLines = splitFile[j].Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); for (int k = 3; k < splitByLines.Length; k++) { //-rw-rw-r-- 1 autoengine murex 1201 Jul 10 16:58 test.txt //-rwxrwxr-x 1 autoengine murex 546 May 10 2008 script.sh* // "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", and "Dec" if (j == 2) { string fileName = splitByLines[k].Replace("/net/" + refHost + refEnv, "").Replace("/net/" + inputHost + inputEnv, ""); string[] splitFileName = fileName.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (diffRegex.Matches(fileName).Count == 0) { DateTime date; try { if (splitFileName[7].Contains(":")) { date = new DateTime(DateTime.Now.Year, monthAbbreviations.IndexOf(splitFileName[5]), Convert.ToInt32(splitFileName[6]), Convert.ToInt32(splitFileName[7].Split(new char[] { ':' })[0]), Convert.ToInt32(splitFileName[7].Split(new char[] { ':' })[1]), 0); } else { date = new DateTime(Convert.ToInt32(splitFileName[7]), monthAbbreviations.IndexOf(splitFileName[5]), Convert.ToInt32(splitFileName[6])); } } catch (Exception ex) { CommonUtils.LogError("Could not get Date", ex); date = DateTime.Now; } long fileSize = (Convert.ToInt64(splitFileName[4]) / 1024) == 0 ? 1 : (Convert.ToInt64(splitFileName[4]) / 1024); results.Rows.Add(new object[] { counter, "Added", fileSize, date.ToString(), GetFileTypeFromExtension(splitFileName[8]), splitFileName[8] }); } } else { string fileName = splitByLines[k].Replace("/net/" + refHost + refEnv, "").Replace("/net/" + inputHost + inputEnv, ""); string[] splitFileName = fileName.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (diffRegex.Matches(fileName).Count == 0) { DateTime date; try { if (splitFileName[7].Contains(":")) { date = new DateTime(DateTime.Now.Year, monthAbbreviations.IndexOf(splitFileName[5]), Convert.ToInt32(splitFileName[6]), Convert.ToInt32(splitFileName[7].Split(new char[] { ':' })[0]), Convert.ToInt32(splitFileName[7].Split(new char[] { ':' })[1]), 0); } else { date = new DateTime(Convert.ToInt32(splitFileName[7]), monthAbbreviations.IndexOf(splitFileName[5]), Convert.ToInt32(splitFileName[6])); } } catch (Exception ex) { CommonUtils.LogError("Could not get Date", ex); date = DateTime.Now; } long fileSize = (Convert.ToInt64(splitFileName[4]) / 1024) == 0 ? 1 : (Convert.ToInt64(splitFileName[4]) / 1024); results.Rows.Add(new object[] { counter, "Modified", fileSize, date.ToString(), GetFileTypeFromExtension(splitFileName[8]), splitFileName[8] }); } } counter++; } } SAVED_SEARCH_RESULTS = results.Copy(); GOLDEN_ORIGINAL_RESTULS = results.Copy(); resultsTable = SAVED_SEARCH_RESULTS; } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } } else { bgDoServerWork.CancelAsync(); WorkerWasCancelled = true; } }
private bool IsValidToBeginDiff(string inputEnv, string inputHost, string refEnv, string refHost, string compareScriptLocation, string scriptHost) { FtpConnection connection; #region RefEnvValidation connection = new FtpConnection(refHost, "mxftp", "mxftp"); try { try { connection.Open(); // bgDoServerWork.ReportProgress(5, "Validating Results..."); } catch (Exception ex) { CommonUtils.ShowError(ex.Message, ex); return false; } connection.Login(); if (!connection.DirectoryExists(refEnv)) { CommonUtils.ShowInformation("The reference environment path is incorrect!",true); return false; } if (!connection.FileExists(refEnv + "/mxg2000_settings.sh")) { CommonUtils.ShowInformation("The reference environment path is incorrect!", true); return false; } if (connection.FileExists(refEnv + "/clean.log")) { CommonUtils.ShowInformation("The reference environment is cleaned!", true); return false; } } finally { connection.Close(); connection.Dispose(); } #endregion #region inputEnvValidations connection = new FtpConnection(inputHost, "mxftp", "mxftp"); try { try { connection.Open(); // bgDoServerWork.ReportProgress(5, "Validating Results..."); } catch (Exception ex) { CommonUtils.ShowError(ex.Message, ex); return false; } connection.Login(); if (!connection.DirectoryExists(inputEnv)) { CommonUtils.ShowInformation("The input environment path is incorrect!",true); return false; } if (!connection.FileExists(inputEnv + "/mxg2000_settings.sh")) { CommonUtils.ShowInformation("The input environment path is incorrect!", true); return false; } if (connection.FileExists(inputEnv + "/clean.log")) { CommonUtils.ShowInformation("The input environment is cleaned!", true); return false; } } finally { connection.Close(); connection.Dispose(); } #endregion #region ComparisonHostValidation connection = new FtpConnection(scriptHost, "mxftp", "mxftp"); try { try { connection.Open(); } catch (Exception ex) { CommonUtils.ShowError(ex.Message, ex); return false; } connection.Login(); if (!connection.DirectoryExists(compareScriptLocation)) { CommonUtils.ShowInformation("Could not connect to master host!", true); return false; } if (!connection.FileExists(compareScriptLocation + "/comparison.sh")) { //testing } } finally { connection.Close(); connection.Dispose(); } #endregion return true; }
private string GetVersionFile(string appDirectory, string host, bool forCleanup) { //generates size.log containing env size if (forCleanup) { GenerateSizeFile(); } string readFile = string.Empty; FtpConnection connection = new FtpConnection(host,21 ,"mxftp", "mxftp"); string localFileName = Path.GetTempFileName(); string localSizeFileName = Path.GetTempFileName(); try { try { try { connection.Open(); //bgDoServerWork.ReportProgress(5, "Validating Results..."); } catch (Exception ex) { CommonUtils.ShowError(ex.Message, ex); } connection.Login(); connection.SetCurrentDirectory(appDirectory ); //Path.GetTempFileName if (forCleanup) { connection.GetFile("size.log", localSizeFileName, false); string sizeFileRead = CommonUtils.ReadFile(localSizeFileName); environmentSize = sizeFileRead.Replace("\t.\n",""); } connection.SetCurrentDirectory(appDirectory + "/logs"); //Path.GetTempFileName connection.GetFile("mxversion.log", localFileName, false); } finally { connection.Close(); connection.Dispose(); } readFile = CommonUtils.ReadFile(localFileName); } catch (Exception ex) { // FrontendUtils.ShowInformation("Could not validate environment version \n["+appDirectory+"]"); CommonUtils.LogError(ex.Message, ex); } return readFile; }
void GetSizeAfterCleanup(string fileName) { string hostName = txtHostForCleanup.Text.Trim(); string appDirectory = txtInputEnvForCleanup.Text.Trim(); FtpConnection connection = new FtpConnection(hostName, "mxftp", "mxftp"); string localSizeFileName = Path.GetTempFileName(); try { try { try { connection.Open(); //bgDoServerWork.ReportProgress(5, "Validating Results..."); } catch (Exception ex) { CommonUtils.ShowError(ex.Message, ex); } connection.Login(); connection.SetCurrentDirectory(appDirectory ); connection.GetFile(fileName, localSizeFileName, false); } finally { connection.Close(); connection.Dispose(); } string sizeFileRead = CommonUtils.ReadFile(localSizeFileName); lblEnvironmentInfo.Text = lblEnvironmentInfo.Text +"\r\nSize After Cleanup:"+ sizeFileRead.Replace("\t.\n",""); } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } }
private void fMain_Load(object sender, EventArgs e) { try { ftp = new FtpConnection(ftpHost, ftpPort, ftpUserName, ftpPassWord); ftp.Open(); ftp.Login(); Update_Info_Labels(); Update_Boxes(); } catch { frmNewFtp.ShowDialog(); Update_Info_Labels(); } if (FTPbox.Properties.Settings.Default.Boxes != null) { bgWork.RunWorkerAsync(); } //CheckForUpdate(); setTimer(); }
protected void NewFoodPopupOk(object sender, EventArgs e) { if (DataValidate()) { bool checkFtpNotError = true; int foodId = 0; if (Session["edit"] != null && (int)Session["edit"] == 1) { foodId = (int) Session["id"]; } else { foodId = FoodController.GetMaxId(); } String imageFileName = ""; if (NewFoodImage.PostedFile != null) { var postImage = NewFoodImage.PostedFile; int imageFileLenght = postImage.ContentLength; string imageExtension = Path.GetExtension(postImage.FileName); imageFileName = foodId + imageExtension; if (imageFileLenght > 0 && (imageExtension == ".png" || imageExtension == ".jpg" || imageExtension == ".gif")) { byte[] myData = new byte[imageFileLenght]; // Read uploaded file from the Stream postImage.InputStream.Read(myData, 0, imageFileLenght); // Create a name for the file to store string strFilename = Path.GetFileName(postImage.FileName); String absServerFileName = Server.MapPath("~/Upload/" + strFilename); // Write data into a file if (FileOperation.WriteToFile(absServerFileName, ref myData)) { using (var ftpConnection = new FtpConnection("localhost",21,"imageupload","123456789")) { ftpConnection.Open(); ftpConnection.Login(); ftpConnection.SetCurrentDirectory("/"); try { ftpConnection.PutFile(absServerFileName, imageFileName); } catch (Exception) { //Báo lỗi checkFtpNotError = false; throw; } finally { ftpConnection.Close(); } } } } } String foodName = NewFoodName.Text; int foodPrice = int.Parse(NewFoodPrice.Text); int foodType = int.Parse(NewFoodType.SelectedValue); String imageOnCdn = imageFileName; String foodDetail = CKEditorNewFood.Text; if (Session["edit"] != null) { foodId = int.Parse(Session["id"].ToString()); if (NewFoodImage.PostedFile == null) { imageOnCdn = null; } if (!FoodController.Update(foodId, foodName, foodPrice, foodType, imageOnCdn, foodDetail)) { OfficeMessageBoxUpdateFoodFail.Show(); OfficePopupNewFood.Hide(); } else { OfficeMessageBoxUpdateFoodSuccess.Show(); OfficePopupNewFood.Hide(); } Session["edit"] = null; } else { if (checkFtpNotError) { if (!FoodController.Insert(foodId, foodName, foodPrice, foodType, imageOnCdn, foodDetail)) { OfficeMessageBoxAddFoodFail.Show(); OfficePopupNewFood.Hide(); } else { OfficeMessageBoxAddFoodSuccess.Show(); OfficePopupNewFood.Hide(); } } } } }
private void DownloadFileList(List<string> fileList, string remoteHost, string remoteLocation, string localLocation) { FtpConnection connection = new FtpConnection(remoteHost, "mxftp", "mxftp"); string localFileName = Path.GetTempFileName(); string currentProcessedFile = string.Empty; try { try { try { connection.Open(); } catch (Exception ex) { CommonUtils.ShowError(ex.Message, ex); } connection.Login(); connection.SetCurrentDirectory(remoteLocation); //Path.GetTempFileName connection.SetLocalDirectory(localLocation); for (int i = 0; i < fileList.Count; i++) { currentProcessedFile = fileList[i]; string localDownloadPath = string.Empty; if (fileList[i].StartsWith("/")) { localDownloadPath = Path.GetDirectoryName(localLocation + fileList[i]); } else { localDownloadPath = Path.GetDirectoryName(localLocation + "/" + fileList[i]); } if (!Directory.Exists(localDownloadPath)) { Directory.CreateDirectory(localDownloadPath); } connection.GetFile(fileList[i], false); } } finally { connection.Close(); connection.Dispose(); } } catch (Exception ex) { CommonUtils.ShowError("Stopped @"+currentProcessedFile+"!\n"+ex.Message, ex); } }
private void bDone_Click(object sender, EventArgs e) { bool ftporsftp; if (cMode.SelectedIndex == 0) { ftporsftp = true; Log.Write("FTP"); } else { ftporsftp = false; Log.Write("SFTP"); } try { if (ftporsftp) { ftp = new FtpConnection(tHost.Text, Convert.ToInt32(nPort.Value), tUsername.Text, tPass.Text); ftp.Open(); ftp.Login(); ftp.Close(); } else { string pass = AESEncryption.Encrypt(tPass.Text, decpass, salt, "SHA1", 2, "OFRna73m*aze01xY", 256); ((frmMain)this.Tag).SetPass(pass); //FTPbox.Properties.Settings.Default.ftpPass = tPass.Text; sftp_login(); //MessageBox.Show("SFTP Connected"); sftpc.quit(); } string hostEncr = AESEncryption.Encrypt(tHost.Text, decpass, salt, "SHA1", 2, "OFRna73m*aze01xY", 256); string unEncr = AESEncryption.Encrypt(tUsername.Text, decpass, salt, "SHA1", 2, "OFRna73m*aze01xY", 256); string passEncr = AESEncryption.Encrypt(tPass.Text, decpass, salt, "SHA1", 2, "OFRna73m*aze01xY", 256); ((frmMain)this.Tag).UpdateAccountInfo(hostEncr, unEncr, passEncr, Convert.ToInt32(nPort.Value), "", ftporsftp); //FTPbox.Properties.Settings.Default.ftpHost = tHost.Text; //FTPbox.Properties.Settings.Default.ftpPort = Convert.ToInt32(nPort.Value); //FTPbox.Properties.Settings.Default.ftpUsername = tUsername.Text; //FTPbox.Properties.Settings.Default.ftpPass = tPass.Text; //FTPbox.Properties.Settings.Default.FTPorSFTP = ftporsftp; //FTPbox.Properties.Settings.Default.timedif = ""; //FTPbox.Properties.Settings.Default.Save(); Log.Write("got new ftp acccount details"); ((frmMain)this.Tag).ClearLog(); ((frmMain)this.Tag).UpdateDetails(); //((frmMain)this.Tag).GetServerTime(); ((frmMain)this.Tag).loggedIn = true; fNewDir fnewdir = new fNewDir(); fnewdir.ShowDialog(); this.Close(); } catch (Exception ex) { MessageBox.Show("Could not connect to FTP server. Check your account details and try again." + Environment.NewLine + " Error message: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void fNewDir_Load(object sender, EventArgs e) { try { host = ((frmMain)this.Tag).ftpHost(); UN = ((frmMain)this.Tag).ftpUser(); pass = ((frmMain)this.Tag).ftpPass(); port = ((frmMain)this.Tag).ftpPort(); ftporsftp = ((frmMain)this.Tag).FTP(); ((frmMain)this.Tag).SetParent(host); if (ftporsftp) { ftp = new FtpConnection(host, port, UN, pass); ftp.Open(); ftp.Login(); } else { sftp_login(); sftproot = sftpc.pwd(); } if (((frmMain)this.Tag).ftpParent() == "") tParent.Text = ((frmMain)this.Tag).ftpHost(); else tParent.Text = ((frmMain)this.Tag).ftpParent(); tPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\FTPbox"; Log.Write(((frmMain)this.Tag).ftpParent() + " " + ((frmMain)this.Tag).ftpHost()); treeView1.Nodes.Clear(); TreeNode first = new TreeNode(); first.Text = "/"; treeView1.Nodes.Add(first); if (ftporsftp) { foreach (FtpDirectoryInfo dir in ftp.GetDirectories()) { if (dir.Name != "." && dir.Name != "..") { TreeNode ParentNode = new TreeNode(); ParentNode.Text = dir.Name.ToString(); treeView1.Nodes.Add(ParentNode); TreeNode ChildNode = new TreeNode(); ChildNode.Text = dir.Name.ToString(); ParentNode.Nodes.Add(ChildNode); } } } else { foreach (ChannelSftp.LsEntry lse in sftpc.ls(".")) { SftpATTRS attrs = lse.getAttrs(); if (lse.getFilename() != "." && lse.getFilename() != ".." && attrs.getPermissionsString().StartsWith("d")) { TreeNode ParentNode = new TreeNode(); ParentNode.Text = lse.getFilename(); treeView1.Nodes.Add(ParentNode); TreeNode ChildNode = new TreeNode(); ChildNode.Text = lse.getFilename(); ParentNode.Nodes.Add(ChildNode); } } } treeView1.SelectedNode = first; Set_Language(((frmMain)this.Tag).lang()); } catch { this.Close(); } }
private void GetFilesByFtp(string host, string remoteLocation) { List<string> remoteFiles = new List<string>(); string localDownloadDirectory = string.Empty; FtpConnection connection = new FtpConnection(host, "mxftp", "mxftp"); try { try { connection.Open(); } catch (Exception ex) { CommonUtils.ShowError(ex.Message, ex); } connection.Login(); connection.SetCurrentDirectory(remoteLocation); FtpFileInfo[] ftpFileInfo = connection.GetFiles("*act.rftvp"); ScriptName = connection.GetCurrentDirectoryInfo().Name; localDownloadDirectory = downloadDir + ScriptName; //if(Directory.Exists(localDownloadDirectory)){ // Directory.Delete(localDownloadDirectory,true); // } DirectoryInfo downloadDirectoryInfo = Directory.CreateDirectory(localDownloadDirectory); connection.SetLocalDirectory(downloadDirectoryInfo.FullName); for (int i = 0; i < ftpFileInfo.Length; i++) { connection.GetFile(ftpFileInfo[i].Name, false); } } finally { connection.SetLocalDirectory(Path.GetTempPath()); connection.Close(); connection.Dispose(); } ReplaceFiles(localDownloadDirectory, txtDest.Text); //deleting local files //Directory.Delete(localDownloadDirectory); }
public void PublishToGitFTP(DeploymentModel model) { if (model.GitDeployment) { Logger.Debug("Executing git add"); var addProcess = new Process(); var addProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" add -A" }; addProcess.StartInfo = addProcessStartInfo; addProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); addProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); addProcess.Start(); addProcess.BeginOutputReadLine(); addProcess.BeginErrorReadLine(); addProcess.WaitForExit(); Logger.Debug("git add process to exited"); Logger.Debug("Executing git email config process"); var emailProcess = new Process(); var emailProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.email \"[email protected]\"" }; emailProcess.StartInfo = emailProcessStartInfo; emailProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); emailProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); emailProcess.Start(); emailProcess.BeginOutputReadLine(); emailProcess.BeginErrorReadLine(); emailProcess.WaitForExit(); Logger.Debug("git email config process to exited"); Logger.Debug("Executing git name config process"); var userProcess = new Process(); var userProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.name \"barbato\"" }; userProcess.StartInfo = userProcessStartInfo; userProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); userProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); userProcess.Start(); userProcess.BeginOutputReadLine(); userProcess.BeginErrorReadLine(); userProcess.WaitForExit(); Logger.Debug("git name config process to exited"); Logger.Debug("Executing git commit"); var commitProcess = new Process(); var commitProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" commit -a -m \"Static Content Regenerated\"" }; commitProcess.StartInfo = commitProcessStartInfo; commitProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); commitProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); commitProcess.Start(); commitProcess.BeginOutputReadLine(); commitProcess.BeginErrorReadLine(); commitProcess.WaitForExit(); Logger.Debug("git commit process to exited"); Logger.Debug("Executing git push"); var pushProcess = new Process(); var pushProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" push -f origin master" }; pushProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); pushProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); pushProcess.StartInfo = pushProcessStartInfo; pushProcess.Start(); pushProcess.BeginOutputReadLine(); pushProcess.BeginErrorReadLine(); pushProcess.WaitForExit(); Logger.Debug("git push process to exited"); } else { using (ftp = new FtpConnection(model.FTPServer, model.FTPUsername, model.FTPPassword)) { try { ftp.Open(); ftp.Login(); if (!string.IsNullOrWhiteSpace(model.FTPPath)) { var parrentDirectory = String.Format("/{0}", Path.GetDirectoryName(model.FTPPath).Replace(Path.DirectorySeparatorChar, '/')); /* Get name of the directory */ var checkingDirectory = String.Format("{0}", Path.GetFileName(model.FTPPath)).ToLower(); /* Get all child directories info of the parent directory */ var ftpDirectories = ftp.GetDirectories(parrentDirectory); /* check if the given directory exists in the returned result */ var exists = ftpDirectories.Any(d => d.Name.ToLower() == checkingDirectory); if (!exists) { ftp.CreateDirectory(model.FTPPath); } ftp.SetCurrentDirectory(model.FTPPath); } FtpBlogFiles(publishGitPath, model.FTPPath); } catch (Exception ex) { } } } }
/// <summary> /// main method used to process the files every configurable interval /// </summary> public void ProcessFileControlThread() { string theFileToGrab = String.Empty; // main processing thread while (true) { try { using (FtpLib.FtpConnection ftp = new FtpLib.FtpConnection(m_FTPFolder, m_FTPUserName, m_FTPPwd)) { try { ftp.Open(); /* Open the FTP connection */ ftp.Login(); /* Login using previously provided credentials */ ftp.SetCurrentDirectory(m_FTPServerDirectory); /* change current directory */ FtpLib.FtpFileInfo[] flist = ftp.GetFiles(); foreach (FtpLib.FtpFileInfo fi in flist) { if (!_dbMgr.CheckDbBeforeDownloadingFile(fi.Name)) { try { string fil = m_FTPServerDirectory + fi.Name; if (ftp.FileExists(fil)) /* check that a file exists */ { ftp.GetFile(fil, m_FtpFileToLocation + fi.Name, false); FileWriter.Instance.WriteToLogFile("FtpHandler::ProcessFileControlThread:DownloadedFile" + fi.Name); // update the db so we do not download again _dbMgr.UpdateFtpFileNameInDb(fi.Name); } } catch (SystemException se) { FileWriter.Instance.WriteToLogFile("FtpHandler::ProcessControlThread:EXCEPTIONCAUGHT(Open/Login/Directory)::" + se.Message); FileWriter.Instance.WriteToLogFile(se.StackTrace); } } } } catch (SystemException se) { FileWriter.Instance.WriteToLogFile("FtpHandler::ProcessFileControlThread:EXCEPTIONCAUGHT::" + se.Message); } } } catch (SystemException se) { FileWriter.Instance.WriteToLogFile("FtpHandler::ProcessFileControlThread:EXCEPTIONCAUGHT::TryingToConnect" + se.Message); } // wait for the next interval to ftp the next file over System.Threading.Thread.Sleep(m_runIntervalInSeconds); }// while(true) }
private void SendFileToServer(string filename) { List<string> remoteFiles = new List<string>(); string localDownloadDirectory = string.Empty; FtpConnection connection = new FtpConnection("dell014srv", "mxftp", "mxftp"); try { try { connection.Open(); } catch (Exception ex) { CommonUtils.ShowError(ex.Message, ex); } connection.Login(); connection.SetCurrentDirectory("/dell014srv1/automation/automation-Jobs/"); connection.PutFile(filename, "launchJob.sh"); } finally { connection.SetLocalDirectory(Path.GetTempPath()); connection.Close(); connection.Dispose(); } }
/// <summary> /// checks if account's information used the last time has changed /// </summary> private void CheckAccount() { try { if (FTP()) { ftp = new FtpConnection(ftpHost(), ftpPort(), ftpUser(), ftpPass()); ftpbg = new FtpConnection(ftpHost(), ftpPort(), ftpUser(), ftpPass()); ftp.Open(); ftp.Login(); ftpbg.Open(); ftpbg.Login(); this.ShowInTaskbar = false; this.Hide(); this.ShowInTaskbar = true; loggedIn = true; } else { sftp_login(); this.ShowInTaskbar = false; this.Hide(); this.ShowInTaskbar = true; loggedIn = true; } } catch { fNewFtp.ShowDialog(); if (!loggedIn) { try { Process p = Process.GetCurrentProcess(); p.Kill(); } catch { } } if (FTP()) { Log.Write("FTP"); ftp = new FtpConnection(ftpHost(), ftpPort(), ftpUser(), ftpPass()); ftpbg = new FtpConnection(ftpHost(), ftpPort(), ftpUser(), ftpPass()); ftp.Open(); ftp.Login(); ftpbg.Open(); ftpbg.Login(); this.ShowInTaskbar = false; this.Hide(); this.ShowInTaskbar = true; loggedIn = true; } else { Log.Write("SFTP"); sftp_login(); this.ShowInTaskbar = false; this.Hide(); this.ShowInTaskbar = true; loggedIn = true; } newDir.ShowDialog(); } }
private void Button_Click_1(object sender, RoutedEventArgs e) { bool good = false; bool run = true; string check = chmodtxt.ToString().Remove(0, chmodtxt.ToString().Length - 3); //MessageBox.Show(check); if (which==true) { for (int i = 0; i <= 2; i++) { if (check[i] == '0' || check[i] == '1' || check[i] == '2' || check[i] == '3' || check[i] == '4' || check[i] == '5' || check[i] == '6' || check[i] == '7') { good = true; } else { good = false; break; } } if (good == false) { MessageBox.Show("Incorrect Format"); chmodtxt.Clear(); run = false; } } char owners = '7'; char groups = '7'; char worlds = '7'; if (good == true && which==true) { owners = check[0]; groups = check[1]; worlds = check[2]; } //MessageBox.Show("" + owners + groups + worlds); if (run == true) { try { FtpConnection chmod = new FtpConnection(MainWindow.address.Remove(0, 6), MainWindow.c_username, MainWindow.c_password); chmod.Open(); chmod.Login(); if (which == true) chmod.SendCommand("SITE CHMOD " + owners + groups + worlds + " " + MainWindow.directory + item); else chmod.SendCommand("SITE CHMOD " + owner.ToString() + group.ToString() + world.ToString() + " " + MainWindow.directory + item); //MessageBox.Show(MainWindow.address.Remove(0,6), "SITE CHMOD " + owner + group + world + " " + MainWindow.directory + item); //MessageBox.Show(item + " permissions changed to " + owner + group + world); chmod.Close(); } catch { MessageBox.Show("ERROR"); } Close(); } }