static void Main(string[] args) { Sftp sftp = new Sftp("[SERVER]", "[USERNAME]", string.Empty); sftp.AddIdentityFile("[Path to Private kEY]"); sftp.Connect(); sftp.Put(@"D:\temp\blog\feed.csv", "[PATH OF FILE ON SERVER]"); sftp.Delete("[PATH OF FILE ON SERVER]"); }
public bool GetFiles() { bool status = true; Sftp sftp = new Sftp( m_sftpSite, m_sftpSiteUserName ); try { // add our private key to connect // put these in the config file sftp.AddIdentityFile(@"d:\apps\RSAKeys\opensshkey"); // connect sftp.Connect(); // get a directory list ArrayList rFiles = sftp.GetFileList( m_sftpSiteRemoteFolder ); foreach ( string file in rFiles ) { if (file.Equals(".") || file.Equals("..")) continue; // get the file and put in the watch folder to be processed sftp.Get(m_sftpSiteRemoteFolder + file, m_moveToProcessFolder + file); // update our database that we have downloaded the file from the server // this.updateDb( file ); // delete the file on the remote server after pulling it over // sftp.Delete(f); } sftp.Close(); status = true; } catch (Tamir.SharpSsh.jsch.SftpException se) { LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + se.Message); } catch (Tamir.SharpSsh.jsch.JSchException jse) { LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + jse.Message); } catch (Tamir.SharpSsh.SshTransferException ste) { LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + ste.Message); } catch (SystemException se) { LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + se.Message); } return status; }
static void Main(string[] args) { Sftp sftp = new Sftp("10.5.1.108", "developer", "pandora"); //sftp.AddIdentityFile("[Path to Private kEY]"); sftp.Connect(); //sftp.Put(@"D:\temp\blog\feed.csv", "[PATH OF FILE ON SERVER]"); //sftp.Delete("[PATH OF FILE ON SERVER]"); Console.WriteLine(String.Join("\n", sftp.GetFileList("Desktop"))); foreach (long size in sftp.GetFileSizes("Desktop")) { Console.WriteLine(Convert.ToString(size)); } sftp.Close(); }
public static Sftp Clone(SshBase baseConnection) { var clone = new Sftp(baseConnection.Host, baseConnection.Username, baseConnection.Password); clone.Session = baseConnection.Session; return clone; }
public bool SftpFile( string fileName ) { SshTransferProtocolBase sshCp = new Sftp( m_sftpSite, m_sftpSiteUserName ); sshCp.Password = m_sftpSitePassword; sshCp.OnTransferStart += new FileTransferEvent(sshCp_OnTransferStart); sshCp.OnTransferProgress += new FileTransferEvent(sshCp_OnTransferProgress); sshCp.OnTransferEnd += new FileTransferEvent(sshCp_OnTransferEnd); // string lfile = @"d:\apps\logs\ReadWriteMgrLog.log"; string rfile = ParseFileName(fileName); string remoteFileName = m_sftpSiteRemoteFolder + rfile; sshCp.Connect(); try { sshCp.Put(fileName, remoteFileName); } catch (Tamir.SharpSsh.jsch.SftpException e) { LogMsg("SftpHandler::SftpFile():ECaught:UnableToCreateEventLogFile::" + e.Message + e.InnerException); return false; } catch (Tamir.SharpSsh.SshTransferException e) { LogMsg("SftpHandler::SftpFile():ECaught:UnableToCreateEventLogFile::" + e.Message + e.InnerException); return false; } catch (SystemException se) { LogMsg("SftpHandler::SftpFile():ECaught:UnableToCreateEventLogFile::" + se.Message); return false; } return true; }
public static Sftp Clone(SshBase baseConnection) { var clone = new Sftp(baseConnection.Host, baseConnection.Username, baseConnection.Password); clone.Session = baseConnection.Session; return(clone); }
public static void RunExample() { try { SshConnectionInfo input = Util.GetInput(); string proto = GetProtocol(); SshTransferProtocolBase sshCp; if(proto.Equals("scp")) sshCp = new Scp(input.Host, input.User); else sshCp = new Sftp(input.Host, input.User); if(input.Pass != null) sshCp.Password = input.Pass; if(input.IdentityFile != null) sshCp.AddIdentityFile( input.IdentityFile ); sshCp.OnTransferStart += new FileTransferEvent(sshCp_OnTransferStart); sshCp.OnTransferProgress += new FileTransferEvent(sshCp_OnTransferProgress); sshCp.OnTransferEnd += new FileTransferEvent(sshCp_OnTransferEnd); Console.Write("Connecting..."); sshCp.Connect(); Console.WriteLine("OK"); while(true) { string direction = GetTransferDirection(); if(direction.Equals("to")) { string lfile = GetArg("Enter local file ['Enter to cancel']"); if(lfile=="") break; string rfile = GetArg("Enter remote file ['Enter to cancel']"); if(rfile=="") break; sshCp.Put(lfile, rfile); } else { string rfile = GetArg("Enter remote file ['Enter to cancel']"); if(rfile=="") break; string lpath = GetArg("Enter local path ['Enter to cancel']"); if(lpath=="") break; sshCp.Get(rfile, lpath); } } Console.Write("Disconnecting..."); sshCp.Close(); Console.WriteLine("OK"); } catch(Exception e) { Console.WriteLine(e.Message); } }
public bool AddFile(int jobId, byte[] fileData, string filename) { if(filename.Contains("/")) return false; //fail for securety //if (filename.Contains(' ')) return false; //fail for securety string dir = string.Format(@"{0}{1}", tempDir, filename); Sftp sftp = new Sftp(HostName, UserName,Password); sftp.Connect(); File.WriteAllBytes(dir, (byte[]) fileData); sftp.Put(dir,string.Format("{2}{1}/{0}", filename, jobId.ToString(),DataPath)); File.Delete(dir); return true; }
public static void Upload(RemoteDevice target, string sourcefile, string targetfile, bool overwrite) { var sftp = new Sftp(target.target.ToString(), target.username, target.password); sftp.Connect(); if (!sftp.Connected) { //MonoDevelop.Ide.Gui.Dialogs.MultiMessageDialog dlg = new MultiMessageDialog(); //dlg.AddMessage("Can not connect to Remote Host for File Transfer", ""); //dlg.ShowAll(); //return null; } sftp.Close(); }
public static bool DeleteSecureFileOnServer(Uri serverUri, string username, string password) { // The serverUri parameter should use the ftp:// scheme. // It contains the name of the server file that is to be deleted. // Example: ftp://contoso.com/someFile.txt. // if (serverUri.Scheme != Uri.UriSchemeFtp) { return false; } Sftp sftp = new Sftp(serverUri.Host, username, password); if (sftp == null) { //Error connecting to FTP server throw new WebException("ERROR - " + ClassName + ": Error connecting to FTP server", WebExceptionStatus.SecureChannelFailure); } else { try { sftp.Connect(); var prop = sftp.GetType().GetProperty("SftpChannel", BindingFlags.NonPublic | BindingFlags.Instance); var methodInfo = prop.GetGetMethod(true); var sftpChannel = methodInfo.Invoke(sftp, null); ((Tamir.SharpSsh.jsch.ChannelSftp)sftpChannel).rm(serverUri.AbsolutePath); return true; } catch (Tamir.SharpSsh.jsch.SftpException sfex) { // write to log - note the lowercase m in message - this library uses nonstandard error reporting Trace.TraceInformation("ERROR - " + ClassName + ":" + sfex.message); throw new WebException("ERROR - " + ClassName + ": " + sfex.message); } catch (Exception ex) { // write to log Trace.TraceInformation("ERROR - " + ClassName + ":" + ex.Message); //EventLog.WriteEntry(Application.ProductName, "ERROR - " + ClassName + ":" + ex.Message, EventLogEntryType.Error); throw new WebException("ERROR - " + ClassName + ": " + ex.Message); //return false; } finally { sftp.Close(); } } }
//FIXME: needs better file list and handling of subdirectories public static IAsyncOperation Upload (MeeGoDevice targetDevice, MeeGoProjectConfiguration conf, TextWriter outWriter, TextWriter errorWriter) { var sftp = new Sftp (targetDevice.Address, targetDevice.Username, targetDevice.Password); var files = Directory.GetFiles (conf.OutputDirectory, "*", SearchOption.TopDirectoryOnly); var op = conf.OutputDirectory.ParentDirectory; for (int i = 0; i < files.Length; i++) files[i] = op.Combine (files[i]); var scop = new SshTransferOperation<Sftp> (sftp, delegate (Sftp s) { var dir = conf.ParentItem.Name; try { s.Mkdir (dir); } catch {} s.Put (files, dir); }); scop.Run (); return scop; }
public static bool image_01_FileMake(string filePath) { Boolean bResult; string _sftpHost = "ledev.leisureq.co.kr"; string _sftpUserId = "lion"; string _sftpUserPw = "gkffl1!"; Int32 _sftpPort = 10004; string[] path = filePath.Split(new char[] { '/' }); try { string ppath = ""; Sftp sftp = new Tamir.SharpSsh.Sftp(_sftpHost, _sftpUserId, _sftpUserPw); sftp.Connect(_sftpPort); for (int i = 1; i < path.Length; i++) { ppath = ppath + "/" + path[i]; ArrayList res = sftp.GetFileList(ppath); string checkFile = path[i+1]; if (res.IndexOf(checkFile) == -1) { sftp.Mkdir(ppath + "/" + checkFile); } } bResult = true; } catch (SystemException ex) { NewLogManager2.Instance.Log(string.Format("Error image_01_FileMake {0}", ex.Message)); bResult = false; } return bResult; }
public static bool image_01_FileMake(string filePath) { Boolean bResult; string _sftpHost = "ledev.leisureq.co.kr"; string _sftpUserId = "lion"; string _sftpUserPw = "gkffl1!"; Int32 _sftpPort = 10004; string[] path = filePath.Split(new char[] { '/' }); try { string ppath = ""; Sftp sftp = new Tamir.SharpSsh.Sftp(_sftpHost, _sftpUserId, _sftpUserPw); sftp.Connect(_sftpPort); for (int i = 1; i < path.Length; i++) { ppath = ppath + "/" + path[i]; ArrayList res = sftp.GetFileList(ppath); string checkFile = path[i + 1]; if (res.IndexOf(checkFile) == -1) { sftp.Mkdir(ppath + "/" + checkFile); } } bResult = true; } catch (SystemException ex) { NewLogManager2.Instance.Log(string.Format("Error image_01_FileMake {0}", ex.Message)); bResult = false; } return(bResult); }
public void TransferFile(SshConnectionInfo input) { try { string proto = "scp"; SshTransferProtocolBase sshCp; if (proto.Equals("scp")) sshCp = new Scp(input.Host, input.User); else sshCp = new Sftp(input.Host, input.User); if (input.Pass != null) sshCp.Password = input.Pass; //if (input.IdentityFile != null) sshCp.AddIdentityFile(input.IdentityFile); sshCp.OnTransferStart += new FileTransferEvent(sshCp_OnTransferStart); sshCp.OnTransferProgress += new FileTransferEvent(sshCp_OnTransferProgress); sshCp.OnTransferEnd += new FileTransferEvent(sshCp_OnTransferEnd); Console.Write("Connecting..."); sshCp.Connect(); Console.WriteLine("OK"); if (input.Direction == TransferDirection.To) sshCp.Put(input.LocalFilePath, input.RemoteFilePath); else sshCp.Get(input.RemoteFilePath, input.LocalFilePath); Console.Write("Disconnecting..."); sshCp.Close(); Console.WriteLine("OK"); } catch (Exception e) { Console.WriteLine(e.Message); throw e; } }
//Connects to the FTP server and request the list of available files public static List<String> getSecureFileList(Uri FTPAddress, string username, string password, bool UseSSL) { List<String> files = new List<String>(); //string temp = "208.109.47.128"; //"/home/content/74/9833874/html/_RBC/" //Use the URI object to separate the address from the subfolders //Create sFTP request Sftp sftp = new Sftp(FTPAddress.Host, username, password); if (sftp == null) { //Error connecting to FTP server throw new WebException("ERROR - " + ClassName + ": Error connecting to FTP server", WebExceptionStatus.SecureChannelFailure); } else { try { sftp.Connect(); //the foldername cannot be empty, or the listing will not show ArrayList fileList = sftp.GetFileList(FTPAddress.AbsolutePath); foreach (var item in fileList) { if (item.ToString() != "." && item.ToString() != "..") //Console.WriteLine(item.ToString()); files.Add(item.ToString()); } } catch (Tamir.SharpSsh.jsch.SftpException sfex) { // write to log - note the lowercase m in message - this library uses nonstandard error reporting Trace.TraceInformation("ERROR - " + ClassName + ":" + sfex.message); throw new WebException("ERROR - " + ClassName + ": " + sfex.message); } catch (Exception ex) { // write to log Trace.TraceInformation("ERROR - " + ClassName + ": " + ex.Message); //EventLog.WriteEntry(Application.ProductName, "ERROR - " + ClassName + ": " + ex.Message, EventLogEntryType.Error); throw new WebException("ERROR - " + ClassName + ": " + ex.Message); } finally { sftp.Close(); } } return files; }
public MyProgressMonitor(Sftp sftp) { m_sftp = sftp; }
private void button1_Click(object sender, EventArgs e) { string makefile = HKLibrary.UTIL.HKFileHelper.GetCurrentDirectory(); string sDirPath; sDirPath = makefile + "\\data"; DirectoryInfo di = new DirectoryInfo(sDirPath); if (di.Exists == false) { di.Create(); } string PinCode = "41302903000002"; makefile = makefile + "\\data\\" + PinCode + ".png"; Int32 OrderSeq = 406359; string folderName = Convert.ToString(OrderSeq); string ftpfileName = folderName + "/" + PinCode + ".jpg"; string ftpBasicPath = "/var/www/IMAGE/Web/upload/order/barcode"; //string ftpBasicPath = "/var/www/IMAGE/Web/upload/order/qrcode/"; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = qrEncoder.Encode(PinCode); var renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); var image = new Bitmap(Image.FromStream(ms), new Size(new Point(200, 200))); image.Save(makefile, ImageFormat.Png); Tamir.SharpSsh.Sftp sftp; sftp = new Tamir.SharpSsh.Sftp("ledev.leisureq.co.kr", "lion", "gkffl1!"); sftp.Connect(10004); ArrayList res = sftp.GetFileList("/"); sftp.Mkdir(ftpBasicPath + "/" + folderName + "/"); sftp.Put(makefile, ftpBasicPath + "/" + ftpfileName); sftp.Close(); //BarcodeLib.Barcode b = new BarcodeLib.Barcode(); //b.Encode(BarcodeLib.TYPE.CODE128, PinCode); //b.SaveImage(makefile, BarcodeLib.SaveTypes.JPG); /* * string date = "2015-05-20 17:16:44"; * string[] datePartPath = new string[4]; * * DateTime dt = Convert.ToDateTime(date); * datePartPath[0] = dt.ToString("yyyy"); * datePartPath[1] = dt.ToString("MM"); * datePartPath[2] = dt.ToString("dd"); * datePartPath[3] = Convert.ToString(OrderSeq); * * * for(Int32 i =0; i<datePartPath.Length; i++){ * ftpBasicPath = ftpBasicPath + "/" + datePartPath[i]; * } * comwls.image_01_FileMake(ftpBasicPath); * */ string ftpUri = "sftp://ledev.leisureq.co.kr:10004/" + ftpBasicPath + folderName; HKLibrary.comwls.comwls.image_01_FileMake(ftpBasicPath + folderName); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri); request.Method = WebRequestMethods.Ftp.MakeDirectory; //request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("lion", "gkffl1!"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); /* * string ftpUri = "ftp://121.78.127.40:21/" + ftpBasicPath + folderName; * * FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri); * request.Method = WebRequestMethods.Ftp.MakeDirectory; * * // This example assumes the FTP site uses anonymous logon. * request.Credentials = new NetworkCredential("infobay", "info9887"); * FtpWebResponse response = (FtpWebResponse)request.GetResponse(); * Stream ftpStream = response.GetResponseStream(); * * ftpStream.Close(); * response.Close(); * * ftpUri = "ftp://121.78.127.40:21/" + ftpBasicPath + ftpfileName; * request = (FtpWebRequest)WebRequest.Create(ftpUri); * request.Method = WebRequestMethods.Ftp.UploadFile; * * // This example assumes the FTP site uses anonymous logon. * request.Credentials = new NetworkCredential("infobay", "info9887"); * * byte[] fileContents = File.ReadAllBytes(makefile); * request.ContentLength = fileContents.Length; * * request.UsePassive = true; * Stream requestStream = request.GetRequestStream(); * requestStream.Write(fileContents, 0, fileContents.Length); * requestStream.Close(); * response = (FtpWebResponse)request.GetResponse(); * response.Close(); * * * * //sftp.ConnectTimeoutMs = 15000; * //sftp.IdleTimeoutMs = 15000; * * //string hostname = "ftp://ledev.leisureq.co.kr:10004/"; * * //bool success = sftp.Connect(hostname, 10004); */ }
private bool GetFiles() { bool status = true; Sftp sftp = new Sftp( m_sftpSite, m_sftpSiteUserName ); try { // add our private key to connect // put these in the config file sftp.AddIdentityFile( m_identityFile ); // connect sftp.Connect(); // get a directory list ArrayList rFiles = sftp.GetFileList( m_sftpSiteRemoteFolder ); int indx = 0; foreach ( string file in rFiles ) { indx++; if (file.Equals(".") || file.Equals("..")) continue; if ( this.CheckDb(file) ) continue; try { // get the file and put in the watch folder to be processed sftp.Get(m_sftpSiteRemoteFolder + file, m_moveToProcessFolder + file); // update the database to indicate file has been downloaded this.UpdateDb(file); // delete the file on the remote server after pulling it over // sftp.Delete(f); } catch (SystemException se) { LogMsg("NEXCEPTION:AMSSftpMgr::GetFile():ECaught:TryingToGetFile:" + indx + ":" + file + "::" + se.Message); } } sftp.Close(); status = true; } catch (Tamir.SharpSsh.jsch.SftpException se) { LogMsg("NEXCEPTION:AMSSftpMgr::GetFile():ECaught:" + se.Message); } catch (Tamir.SharpSsh.jsch.JSchException jse) { LogMsg("NEXCEPTION:AMSSftpMgr::GetFile():ECaught:" + jse.Message); } catch (Tamir.SharpSsh.SshTransferException ste) { LogMsg("NEXCEPTION:AMSSftpMgr::GetFile():ECaught:" + ste.Message); } catch (SystemException se) { LogMsg("NEXCEPTION:AMSSftpMgr::GetFile():ECaught:" + se.Message); } return status; }
//This method was implemented in order to eliminate RFG's previous ChilkatFTP //dependency. It uses a custom SFTP class (NETsFTP) to upload the files. //Fabian Gutierrez 07/23/2008. private static bool upload_to_ftp(string fName) { //Chilkat.Ftp2 ftp = ChilkatComponents.ChilkatFtp2; //ftp.Hostname = utility.getParameter("crm_ftp_host"); string Hostname = utility.getParameter("crm_ftp_host"); string dir_path = utility.getParameter("crm_ftp_dir"); //ftp.Username = utility.getParameter("crm_ftp_user"); string Username = utility.getParameter("crm_ftp_user"); //ftp.Password = utility.getParameter("crm_ftp_pwd"); string Password = utility.getParameter("crm_ftp_pwd"); Sftp sftpClient = new Sftp(Hostname, Username, Password); //socks einstellen funktioniert nicht?! //ftp.Proxy = "socks-server.grenoble.hp.com"; Hashtable h_params = new Hashtable(); //bool connected = ftp.Connect(); //bool connected; bool upload_success; bool changed_dir; try { //NETsFTP.SFTP.Upload(Hostname, dir_path, Username, Password, path_to_file); sftpClient.Connect(22); if (sftpClient.Connected) { } sftpClient.Put(fName, dir_path); sftpClient.Close(); upload_success = true; return upload_success; } catch (DirectoryNotFoundException e) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("FTP ERROR - {0}{1}", utility.newline, e.ToString().Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); changed_dir = false; return changed_dir; } //catch (TimeoutException e) //{ // h_params["submit_flag"] = "crm_submit"; // h_params["failure_reason"] = String.Format("FTP ERROR - {0}{1}", utility.newline, e.ToString().Replace("\r\n", "")); // DB.execProc("insert_failed_submit", h_params); // connected = false; // return connected; //} catch (Exception e) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("GENERAL ERROR - {0}", e.ToString().Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); upload_success = false; return upload_success; } /*if (!connected) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("FTP ERROR - {0}{1}", utility.newline, ftp.LastErrorText.Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); return connected; } bool changed_dir = false; changed_dir = ftp.ChangeRemoteDir(dir_path); if (!changed_dir) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("FTP ERROR - {0}{1}", utility.newline, ftp.LastErrorText.Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); return changed_dir; } // Upload a file to the FTP server. bool upload_success = ftp.PutFile(path_to_tempdir, filename); if (!upload_success) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = ftp.LastErrorText.Replace("\r\n", ""); DB.execProc("insert_failed_submit", h_params); return upload_success; }*/ //return true; }
/*public byte[] getZipFile(int jobId, string fileName) { if (fileName.Contains("/")) return null; //fail for securety //if (fileName.Contains(' ')) return null; //fail for securety Sftp sftp = getSftp(); SshStream shell = getShell(); shell.Write(string.Format(@"cd poy_service/{1} ; zip {0}.zip {0}", fileName, jobId )); for(int i = 0 ; i<30 ; i++) { Thread.Sleep(2000); if(sftp.GetFileList(string.Format(@"poy_service/{0}/", jobId)).Contains(fileName+".zip")) i=30; } string vmFileName = string.Format(@"{0}{1}.zip", tempDir, fileName); if(File.Exists(vmFileName)) { File.Delete(vmFileName); } sftp.Get( string.Format(@"poy_service/{1}/{0}.zip", fileName, jobId), vmFileName ); shell.Write(string.Format(@"rm {0}.zip", fileName, jobId )); FileStream fileStream = File.OpenRead(vmFileName); byte[] filedata = new byte[(int)fileStream.Length]; fileStream.Read(filedata, 0, (int)fileStream.Length); //File.Delete(string.Format(@"{0}{1}", tempDir, fileName)); return filedata; }*/ public string getTextFile(int jobId, string fileName) { if (fileName.Contains("/")) return null; //fail for securety //if (fileName.Contains(' ')) return null; //fail for securety Sftp sftp = new Sftp(HostName, UserName, Password); sftp.Connect(); sftp.Get( string.Format(@"poy_service/{1}/{0}", fileName, jobId,DataPath), string.Format(@"{0}{1}",tempDir, fileName) ); string output = File.ReadAllText(string.Format(@"{0}{1}", tempDir, fileName)); File.Delete(string.Format(@"{0}{1}", tempDir, fileName)); return output; }
protected void APN_Send(int msgid, string m_ftp_host, string m_ftp_username, string m_ftp_password, string m_sftp_path) { var m_msgid = msgid.ToString(); string m_msg_file = m_msgid + ".xml"; string m_fileroot = "http://businessdesk.blob.core.windows.net/messages/"; string m_file = m_fileroot + m_msg_file; CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=businessdesk;AccountKey=zWYFxlr7zhbMhXLptJ2lvtrORvoPTVunsDAf/v8B0tDsUWMigwFOJs9wEZ62XU6UdFWM1BQJ/SN9dZ0JsWVlpw=="); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("messages"); CloudBlockBlob blockBlob = container.GetBlockBlobReference(m_msg_file); string pathToFiles = Server.MapPath("/Stories/"); string m_File = pathToFiles + m_msg_file; using (var fileStream = File.OpenWrite(m_File)) { blockBlob.DownloadToStream(fileStream); } try { SshTransferProtocolBase sshCpAPN; sshCpAPN = new Sftp("ftp1.apnz.co.nz", "ContentLtd"); sshCpAPN.Password = "******"; sshCpAPN.Connect(); string lfile = m_File; string rfile = "/incoming/" + m_msg_file; sshCpAPN.Put(lfile, rfile); sshCpAPN.Close(); } catch (Exception ex) { //LogError("SFTP - Sharechat", ex.Message); } }
public void APN(int storyid, string p_headline, string p_story) { // check to see if the APN feed is active // if Yes, create the NewsML record and send it out string m_headline = p_headline; string m_story = p_story; string m_active = ""; String connectionString = ConfigurationManager.ConnectionStrings["azureConnectionString"].ConnectionString; try { // Connect to the database and run the query. SqlConnection con = new SqlConnection(connectionString); string strSQL = "Select active from customermessage where customerid = '2' and active = 'Y'"; SqlCommand cmd = new SqlCommand(strSQL, con); cmd.CommandType = CommandType.Text; con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { m_active = (dr["active"].ToString()); TimeZoneInfo timeZoneInfo; //Set the time zone information to New Zealand Standard Time timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("New Zealand Standard Time"); //Get date and time in New Zealand Standard Time var m_nzdate = TimeZoneInfo.ConvertTimeFromUtc(System.DateTime.UtcNow, timeZoneInfo); XmlWriter writer = null; var m_id = Convert.ToString(storyid); //Trace.WriteLine("Processing Story ID: " + m_id); string file_now = m_nzdate.ToString("yyyMMddHHmmss") + "-" + m_id + ".XML"; //LocalResource myStorage = RoleEnvironment.GetLocalResource("XMLStorage"); string pathToFiles = Server.MapPath("/Stories/"); string filepath = Path.Combine(pathToFiles, file_now); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; // write the NewsML file for APN, writer = XmlWriter.Create(filepath, settings); string x_story = ReplaceWordChars(m_story); m_story = x_story; string[] lines = m_story.Replace("\r", "").Split('\n'); string m_embargoed = string.Empty; m_headline = m_headline.Replace("\r", string.Empty); //var m_reporter = lines[0]; var m_reporter = "Staff Reporter"; //if (m_reporter.Length > 3) //{ // m_reporter = m_reporter.Substring(3, m_reporter.Length - 3); //} //else //{ // m_reporter = "Staff Reporter"; //} // write the NewsML file for APN, IRG writer.WriteComment("BusinessDesk NewsML"); writer.WriteStartElement("newsMessage", "http://iptc.org/std/nar/2006-10-01/"); writer.WriteAttributeString("xsi", "schemaLocation", "http://iptc.org/std/nar/2006-10-01/", "http://www.iptc.org/std/NAR/1.9/specification/NewsML-G2_2.8-spec-NewsItem-Power.xsd"); writer.WriteAttributeString("standard", "NewsML-G2"); writer.WriteAttributeString("standardversion", "2.8"); writer.WriteAttributeString("conformance", "power"); writer.WriteAttributeString("lang", "en-US"); // START Header writer.WriteStartElement("Header"); writer.WriteStartElement("Sent"); writer.WriteString(m_nzdate.ToString("yyyy-MM-dd HH:mm:ss")); writer.WriteEndElement(); writer.WriteStartElement("sender"); writer.WriteString("BusinessDesk"); writer.WriteEndElement(); writer.WriteStartElement("origin"); writer.WriteString("BusinessDesk"); writer.WriteEndElement(); writer.WriteStartElement("transmitId"); writer.WriteString(m_nzdate.ToString("yyyMMddHHmmss")); writer.WriteEndElement(); writer.WriteStartElement("priority"); writer.WriteString("5"); writer.WriteEndElement(); writer.WriteStartElement("destination"); writer.WriteString("All"); writer.WriteEndElement(); writer.WriteEndElement(); // END Header // // START ItemSet writer.WriteStartElement("itemSet"); // START Package Item writer.WriteStartElement("packageItem"); writer.WriteStartElement("itemRef"); writer.WriteAttributeString("residref", m_nzdate.ToString("yyyMMddHHmmss")); writer.WriteEndElement(); writer.WriteEndElement(); // END PackageItem // // START NewsItem writer.WriteStartElement("newsItem"); writer.WriteAttributeString("guid", "BD-" + m_nzdate.ToString("yyyMMddHHmmss")); writer.WriteAttributeString("version", "3"); writer.WriteAttributeString("standard", "NewsML-G2"); writer.WriteAttributeString("standardversion", "2.7"); writer.WriteStartElement("catalogRef"); writer.WriteAttributeString("href", "http://www.iptc.org/std/catalog/catalog.IPTC-G2-Standards_13.xml"); writer.WriteEndElement(); // START RightsInfo writer.WriteStartElement("rightsInfo"); writer.WriteStartElement("copyrightHolder"); writer.WriteAttributeString("literal", ""); writer.WriteEndElement(); writer.WriteStartElement("copyrightNotice"); writer.WriteEndElement(); writer.WriteEndElement(); // END RightsInfo // // START ItemMeta writer.WriteStartElement("itemMeta"); writer.WriteStartElement("itemClass"); writer.WriteAttributeString("qcode", "ninat:text"); writer.WriteEndElement(); writer.WriteStartElement("provider"); writer.WriteAttributeString("literal", "CL"); writer.WriteEndElement(); writer.WriteStartElement("versionCreated"); writer.WriteString(m_nzdate.ToString("yyyMMddHHmmss")); writer.WriteEndElement(); writer.WriteStartElement("embargoed"); writer.WriteString(m_embargoed); writer.WriteEndElement(); writer.WriteStartElement("ednote"); writer.WriteString(""); writer.WriteEndElement(); writer.WriteStartElement("pubStatus"); writer.WriteAttributeString("qcode", "stat:usable"); writer.WriteEndElement(); writer.WriteEndElement(); // END ItemMeta // // START ContentMeta writer.WriteStartElement("contentMeta"); writer.WriteStartElement("urgency"); writer.WriteString("5"); writer.WriteEndElement(); writer.WriteStartElement("keyword"); writer.WriteAttributeString("role", "krole:index"); writer.WriteString(""); writer.WriteEndElement(); // Taxonomy field value string smarket = ""; string mqcode = "type"; writer.WriteStartElement("subject"); writer.WriteAttributeString(mqcode, "Topic"); writer.WriteStartElement("name"); writer.WriteString(smarket); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); // END COntentMeta // // START COntentSet writer.WriteStartElement("contentSet"); // START INLINEXML writer.WriteStartElement("inlineXML"); writer.WriteAttributeString("contenttype", "application/nitf+xml"); writer.WriteStartElement("nitf"); //writer.WriteAttributeString("xmlns", "http://iptc.org/std/NITF/2006-10-18/"); writer.WriteAttributeString("xsi", "schemaLocation", "http://iptc.org/std/NITF/2006-10-18/", "http://www.iptc.org/std/NITF/3.5/specification/nitf-3-5.xsd"); // HEAD writer.WriteStartElement("head"); writer.WriteStartElement("title"); writer.WriteString(m_headline); writer.WriteEndElement(); writer.WriteEndElement(); // END HEAD // // START BODY writer.WriteStartElement("body"); // START BODY Head writer.WriteStartElement("body.head"); writer.WriteStartElement("byline"); writer.WriteString("By"); writer.WriteStartElement("person"); writer.WriteString(m_reporter); writer.WriteEndElement(); writer.WriteStartElement("byttl"); writer.WriteString("BusinessDesk"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteStartElement("abstract"); writer.WriteString(" "); writer.WriteEndElement(); writer.WriteEndElement(); //END Body Head // // START Body Content writer.WriteStartElement("body.content"); foreach (string str in lines) { if (str.Length > 1) { writer.WriteStartElement("p"); writer.WriteString(str.Trim()); writer.WriteEndElement(); } } writer.WriteEndElement(); // END Body Content writer.WriteEndElement(); //END BODY writer.WriteEndElement(); // END NITF writer.WriteEndElement(); // END INLINEXML writer.WriteEndElement(); // END CONTENTSET writer.WriteEndElement(); // END NewsItem writer.WriteEndElement(); // END ItemSet writer.WriteEndElement(); // END NewsMessage writer.Flush(); writer.Close(); // try { // // now send to APN // SshTransferProtocolBase sshCpAPN; sshCpAPN = new Sftp("ftp1.apnz.co.nz", "ContentLtd"); sshCpAPN.Password = "******"; sshCpAPN.Connect(); string lfile = filepath; string rfile = "/incoming/" + file_now; sshCpAPN.Put(lfile, rfile); sshCpAPN.Close(); //Trace.WriteLine(m_id, "APN - Success"); } catch (Exception ex) { //Trace.WriteLine(m_id, "APN - Fail"); } } cmd.Dispose(); con.Close(); con.Dispose(); } catch (Exception) { } }
protected void APN_Send(int msgid, string m_ftp_host, string m_ftp_username, string m_ftp_password, string m_sftp_path, string m_messagename) { var m_headline = ""; string m_customer = "APN"; var m_msgid = msgid.ToString(); String connectionString = ConfigurationManager.ConnectionStrings["azureConnectionString"].ConnectionString; try { // Connect to the database and run the query. SqlConnection con = new SqlConnection(connectionString); string strSQL = "Select headline from story where storyid = " + msgid; SqlCommand cmd = new SqlCommand(strSQL, con); cmd.CommandType = CommandType.Text; con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { m_headline = (dr["headline"].ToString()); } cmd.Dispose(); con.Close(); con.Dispose(); } catch (Exception ex) { // The connection failed. Display an error message. PublishLog(m_msgid, m_headline, m_customer, ex.Message, "Pub Error"); } //PublishLog(m_msgid, m_headline, m_customer, "APN Step 1", "Publish OK"); string m_msg_file = m_msgid + ".xml"; string m_fileroot = "http://businessdesk.blob.core.windows.net/messages/"; string m_file = m_fileroot + m_msg_file; CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=businessdesk;AccountKey=zWYFxlr7zhbMhXLptJ2lvtrORvoPTVunsDAf/v8B0tDsUWMigwFOJs9wEZ62XU6UdFWM1BQJ/SN9dZ0JsWVlpw=="); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("messages"); CloudBlockBlob blockBlob = container.GetBlockBlobReference(m_msg_file); string pathToFiles = Server.MapPath("/Stories/"); string m_File = pathToFiles + m_msg_file; //PublishLog(m_msgid, m_headline, m_customer, "APN Step 2", "Publish OK"); try { using (var fileStream = File.OpenWrite(m_File)) { blockBlob.DownloadToStream(fileStream); } } catch (Exception ex) { PublishLog(m_msgid, m_headline, m_customer, ex.Message, "Pub Error"); } try { SshTransferProtocolBase sshCpAPN; sshCpAPN = new Sftp("ftp1.apnz.co.nz", "ContentLtd"); sshCpAPN.Password = "******"; sshCpAPN.Connect(); string lfile = m_File; string rfile = "/incoming/" + m_msg_file; sshCpAPN.Put(lfile, rfile); sshCpAPN.Close(); PublishLog(m_msgid, m_headline, m_customer, "APN SFTP Pub OK", "Publish OK"); } catch (WebException ex) { PublishLog(m_msgid, m_headline, m_customer, ex.Message, "Pub Error"); } }
public static bool downloadSecureFile(Uri serverUri, string filename, string username, string password, bool UseSSL, string destFile) { // The serverUri parameter should use the ftp:// scheme. // It contains the name of the server file that is to be deleted. // Example: ftp://contoso.com/someFile.txt. // if (serverUri.Scheme != Uri.UriSchemeFtp) { return false; } Sftp sftp = new Sftp(serverUri.Host, username, password); if (sftp == null) { //Error connecting to FTP server throw new WebException("ERROR - " + ClassName + ": Error connecting to FTP server", WebExceptionStatus.SecureChannelFailure); } else { try { sftp.OnTransferStart += new FileTransferEvent(sftp_OnTransferStart); sftp.OnTransferProgress += new FileTransferEvent(sftp_OnTransferProgress); sftp.OnTransferEnd += new FileTransferEvent(sftp_OnTransferEnd); sftp.Connect(); sftp.Get(serverUri.LocalPath + filename, destFile); //confirm the file is fully downloaded long remoteSize = sftp.getSize(serverUri.LocalPath + filename); FileInfo localfile = new FileInfo(destFile); long localSize = localfile.Length; if (localSize >= (remoteSize - 100)) { return true; } else { //file was not complete return false; } } catch (Tamir.SharpSsh.jsch.SftpException sfex) { // write to log - note the lowercase m in message - this library uses nonstandard error reporting Trace.TraceInformation("ERROR - " + ClassName + ":" + sfex.message); throw new WebException("ERROR - " + ClassName + ": " + sfex.message); } catch (Exception ex) { // write to log Trace.TraceInformation("ERROR - " + ClassName + ":" + ex.Message); //EventLog.WriteEntry(Application.ProductName, "ERROR - " + ClassName + ":" + ex.Message, EventLogEntryType.Error); throw new WebException("ERROR - " + ClassName + ": " + ex.Message); //return false; } finally { sftp.Close(); } } }
public bool AddZipFile(int jobId, byte[] fileData, string filename) { if(filename.Contains("/")) return false; //fail for securety //if (filename.Contains(' ')) return false; //fail for securety string dir = string.Format(@"{0}{1}.zip", tempDir, filename); Sftp sftp = new Sftp(HostName, UserName,Password); sftp.Connect(); File.WriteAllBytes(dir, (byte[]) fileData); sftp.Put(dir,DataPath+'/'+jobId+'/'); SshStream shell = getShell(); shell.Write(string.Format("unzip {2}{1}/{0}.zip", filename, jobId.ToString(),DataPath)); shell.Write(string.Format("rm {2}{1}/{0}.zip", filename, jobId.ToString(),DataPath)); File.Delete(dir); return true; }
private Sftp getSftp() { Sftp sftp = new Sftp(HostName, UserName, Password); sftp.Connect(); return sftp; }
public string SubmitGenPhen(int jobId,string jobName,string treeName, string postBackURL) { Sftp sftp = new Sftp(HostName, UserName, Password); sftp.Connect(); string dir = string.Format(@"{0}GenPhenBatch.job", tempDir); using (StreamWriter writer = new StreamWriter(dir, false)) { writer.Write("#PBS -l walltime=03:00:00 \n#PBS -l nodes=1:ppn=1 \n"); writer.Write("#PBS -N GenPhen_" + jobId.ToString() + " \n#PBS -j oe \n"); writer.Write("#PBS -S /bin/ksh \n"); writer.Write("PATH=$PATH:"+PoyPath+" \n"); writer.Write(string.Format("cd {0}{1}/ \n", DataPath,jobId)); writer.Write("echo the start time is `date`\n"); writer.Write("mpiexec add_arbitrary_weights.awk "+treeName+" >temp_tree.tre\n"); writer.Write("cat temp_tree.tre "+jobName+".poy_output | mpiexec add_tree.pl >"+jobName+"_parsed.txt\n"); writer.Write("mpiexec reweight_tree.awk "+jobName+"_parsed.txt "+jobName+"_parsed.txt > "+jobName+"_rwt.txt \n"); writer.Write("mpiexec divisiderum_postparse_totaldown.pl root "+jobName+"_rwt.txt > "+jobName+"_down.txt \n"); writer.Write("mpiexec apomorphy_andtable_test_statistic_cox.pl "+jobName+"_rwt.txt "+jobName+"_down.txt > "+jobName+"_stat.txt\n"); writer.Write("awk '($1 != $2 && ($3+$4) > 3 && $3 > $5 && ($3-$10)/sqrt($10) >=sqrt(6)){print;}' "+jobName+"_stat.txt > "+jobName+"_stat_p0.05.txt\n"); writer.Write("awk '($1 != $2 && ($3+$4) > 3 && $3 > $5 && ($3-$10)/sqrt($10) >=sqrt(19)){print;}' "+jobName+"_stat.txt > "+jobName+"_stat_p0.001.txt\n"); writer.Write("awk '($1 != $2 && ($3+$4) > 3 && $3 > $5 && ($3-$10)/sqrt($10) >=sqrt(200)){print;}' "+jobName+"_stat.txt > "+jobName+"_stat_p0.0001.txt\n"); writer.Write("wget "+postBackURL+ " \n"); writer.Write(" echo the end time is `date`\n"); } sftp.Put(dir); sftp.Close(); //I could not Ftp to put the files in the right directory so I put them in the base and moved them with a ssh command SshStream shell = getShell(); shell.Write(string.Format("mv {0} {2}{1}/{0} ;", "GenPhenBatch.job", jobId.ToString(),DataPath)); shell.Write(string.Format("cd {1}{0} ;", jobId.ToString(),DataPath)); //echo `qstat | awk '/supramap/ {print $1}'` //shell.Write(string.Format("qsub -W depend=afterok:{0} GenPhenBatch.job",pbs_id)); //please excuese the uglness of haveing code nested in code nested in code. //awk is nest in bash that is nested in C# shell.Write(string.Format("qsub -W depend=afterany:`qstat | awk '/poy_{0}/ {{split($1,array,\".\");print array[1]}}'` GenPhenBatch.job",jobId.ToString())); File.Delete(dir); //sftp.Get("poy_test.o4281361",@"C:\temp\poy_test.o4281361"); //FileStream fileStream = File.OpenRead(@"C:\temp\poy_test.o4281361"); //byte[] filedata = new byte[(int)fileStream.Length]; //fileStream.Read(filedata,0,(int)fileStream.Length); return "Success"; }
public string Submit(int jobId, int numberOfNodes, int wallTimeHours, int wallTimeMinutes, string postBackURL) { if (wallTimeMinutes >= 60) return "Minutes must be less then 60"; if (wallTimeHours >= 99) return "Hours must be less then 99"; if (numberOfNodes >= 101) return "Number of Nodes must be less then 101"; if (numberOfNodes < 1) return "you need at least 1 node"; if (wallTimeHours < 0 || wallTimeMinutes < 0) return "We currently don't support time travel at this time"; Sftp sftp = new Sftp(HostName, UserName, Password); sftp.Connect(); string dir = string.Format(@"{0}batch.job", tempDir); using (StreamWriter writer = new StreamWriter(dir, false)) { writer.Write(string.Format("#PBS -l walltime={0}:{1}:00 \n", wallTimeHours.ToString().PadLeft(2,'0'), wallTimeMinutes.ToString().PadLeft(2,'0') )); if(superComputer.HostName=="glenn.osc.edu") writer.Write(string.Format("#PBS -l nodes={0}:ppn=12 \n",numberOfNodes)); else if(superComputer.HostName=="superdev.bmi.ohio-state.edu") writer.Write("#PBS -l nodes=5:ppn=8+4:ppn=4 \n" ); else writer.Write(string.Format("#PBS -l nodes={0} \n",numberOfNodes)); writer.Write("#PBS -N poy_" + jobId.ToString() + " \n"); writer.Write("#PBS -j oe \n"); //writer.Write("#PBS –o output.txt \n"); //writer.Write("#PBS -S /bin/ksh \n"); if(superComputer.HostName!="superdev.bmi.ohio-state.edu") writer.Write("PATH="+PoyPath+":$PATH \n"); writer.Write(string.Format("cd {0}{1}/ \n", DataPath,jobId)); writer.Write("echo the start time is `date`\n"); if(superComputer.HostName=="superdev.bmi.ohio-state.edu") //writer.Write(string.Format("mpirun -np $NUM_PROC -machinefile $PBS_NODEFILE --mca btl tcp,self --mca btl_tcp_if_include eth0 {0}poy -plugin {0}supramap.cmxs *.poy \n",superComputer.PluginPath)); writer.Write("mpirun -np 56 -machinefile $PBS_NODEFILE --mca btl tcp,self --mca btl_tcp_if_include eth0 poy_mpi -plugin /usr/local/poy-4.1.2/bin/supramap_mpi.cmxs *.poy \n"); else writer.Write(string.Format("mpiexec {0}poy -plugin {0}supramap.cmxs *.poy \n",superComputer.PluginPath)); writer.Write("wget "+postBackURL+ " \n"); writer.Write(" echo the end time is `date`\n"); } sftp.Put(dir); sftp.Close(); //I could not Ftp to put the files in the right directory so I put them in the base and moved them with a ssh command SshStream shell = getShell(); shell.Write(string.Format("mv {0} {2}{1}/{0} ;", "batch.job", jobId.ToString(),DataPath)); shell.Write(string.Format("cd {1}{0} ;", jobId.ToString(),DataPath)); shell.Write("qsub batch.job"); File.Delete(dir); //sftp.Get("poy_test.o4281361",@"C:\temp\poy_test.o4281361"); //FileStream fileStream = File.OpenRead(@"C:\temp\poy_test.o4281361"); //byte[] filedata = new byte[(int)fileStream.Length]; //fileStream.Read(filedata,0,(int)fileStream.Length); return "Success"; }
public static bool moveSecureFile(Uri serverUri, string filename, string username, string password, bool UseSSL, string destination) { // The serverUri parameter should use the ftp:// scheme. // It contains the name of the server file that is to be deleted. // Example: ftp://contoso.com/someFile.txt. // if (serverUri.Scheme != Uri.UriSchemeFtp) { return false; } Sftp sftp = new Sftp(serverUri.Host, username, password); if (sftp == null) { //Error connecting to FTP server throw new WebException("ERROR - " + ClassName + ": Error connecting to FTP server", WebExceptionStatus.SecureChannelFailure); } else { try { //Ensure the folder separator exists if (!destination.EndsWith("/")) { destination += "/"; } sftp.Connect(); sftp.Rename(serverUri.LocalPath + filename, Path.Combine(serverUri.LocalPath, destination + filename)); return true; } catch (Tamir.SharpSsh.jsch.SftpException sfex) { // write to log - note the lowercase m in message - this library uses nonstandard error reporting Trace.TraceInformation("ERROR - " + ClassName + ":" + sfex.message); throw new WebException("ERROR - " + ClassName + ": " + sfex.message); } catch (Exception ex) { // write to log Trace.TraceInformation("ERROR - " + ClassName + ":" + ex.Message); //EventLog.WriteEntry(Application.ProductName, "ERROR - " + ClassName + ":" + ex.Message, EventLogEntryType.Error); throw new WebException("ERROR - " + ClassName + ": " + ex.Message); //return false; } finally { sftp.Close(); } } }
public void ssh_command(string type, string host, string user, string password, string command) { if (type == "list dir") { Sftp sftp = new Sftp(host, user, password); try { sftp.Connect(); ArrayList analyses = sftp.GetFileList(command); if (analyses.Count > 0) { foreach (string run in analyses) { if (run.Length > 10) { this.stdRunsList.Items.Add(run); } } count_label.Text = "Count: " + stdRunsList.Items.Count.ToString(); connected(); } } catch { ConnectionError.Visible = true; pwdBox.ResetText(); } finally { sftp.Close(); } } else if (type == "kill") { ssh.Write(command); terminalThread.CancelAsync(); } else { try { ssh = new SshStream(host, user, password); abort = false; stopWatch.Start(); terminalThread.RunWorkerAsync(); checkThread.RunWorkerAsync(); ssh.Write(command); } catch (Exception ex) { MessageBox.Show(ex.Message, "Minion - Stream Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public void ShareChat(int storyid) { // check to see if the Sharechat feed is active // if Yes, create the RSS record and send it out string m_headline = ""; string m_story = ""; string m_active = ""; String connectionString = ConfigurationManager.ConnectionStrings["azureConnectionString"].ConnectionString; try { // Connect to the database and run the query. SqlConnection con = new SqlConnection(connectionString); string strSQL = "Select headline,body from story where storyid = " + storyid; SqlCommand cmd = new SqlCommand(strSQL, con); cmd.CommandType = CommandType.Text; con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { m_headline = (dr["headline"].ToString()); m_story = (dr["body"].ToString()); } cmd.Dispose(); con.Close(); con.Dispose(); } catch (Exception) { // The connection failed. Display an error message. //Message.Text = "Unable to connect to the database."; } try { // Connect to the database and run the query. SqlConnection con = new SqlConnection(connectionString); string strSQL = "Select active from customermessage where customerid = '5' and active = 'Y'"; SqlCommand cmd = new SqlCommand(strSQL, con); cmd.CommandType = CommandType.Text; con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { m_active = (dr["active"].ToString()); TimeZoneInfo timeZoneInfo; //Set the time zone information to New Zealand Standard Time timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("New Zealand Standard Time"); //Get date and time in New Zealand Standard Time var m_nzdate = TimeZoneInfo.ConvertTimeFromUtc(System.DateTime.UtcNow, timeZoneInfo); var m_id = Convert.ToString(storyid); string m_RSS_File = m_nzdate.ToString("yyyMMddHHmmss") + "-" + m_id + "RSS.xml"; string pathToFiles = Server.MapPath("/Stories/"); string RSS_FilePath = Path.Combine(pathToFiles, m_RSS_File); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; string[] lines = m_story.Replace("\r", "").Split('\n'); string m_embargoed = string.Empty; m_headline = m_headline.Replace("\r", string.Empty); // write the RSS file for ShareChat // string[] rsslines = m_story.Replace("\r", "").Split('\n'); string m_body = string.Empty; foreach (string str in rsslines) { if (str.Length > 1) { m_body += "<p> "; m_body += str; m_body += " </p>"; } } var currentdate = m_nzdate.ToString("yyyy-MM-dd HH:mm:ss"); XmlTextWriter objX = new XmlTextWriter(RSS_FilePath, Encoding.UTF8); objX.WriteStartDocument(); objX.WriteStartElement("rss"); objX.WriteAttributeString("version", "2.0"); objX.WriteStartElement("channel"); objX.WriteElementString("title", "BusinessDesk"); objX.WriteElementString("link", "http://businessdesk.co.nz/"); objX.WriteElementString("description", "BusinessDesk News Feed"); objX.WriteElementString("copyright", "(c) 2012, Content Ltd. All rights reserved."); objX.WriteElementString("ttl", "5"); objX.WriteStartElement("item"); objX.WriteElementString("title", m_headline); objX.WriteElementString("description", m_body); objX.WriteElementString("link", "http://www.businessdesk.co.nz/"); objX.WriteElementString("pubDate", currentdate); objX.WriteEndElement(); objX.WriteEndElement(); objX.WriteEndElement(); objX.WriteEndDocument(); objX.Flush(); objX.Close(); try { // Send message to ShareChat using SFTP // SshTransferProtocolBase sshCp; sshCp = new Sftp("www.sharechat.co.nz", "root"); sshCp.Password = "******"; sshCp.Connect(); string lfile = RSS_FilePath; string rfile = "/root/BusinessDesk/" + m_RSS_File; sshCp.Put(lfile, rfile); sshCp.Close(); } catch (Exception ex) { } } } catch (Exception) { // The connection failed. Display an error message. //Message.Text = "Unable to connect to the database."; } }
//RFG 2.20 | This method will upload RI file into HPE sftp location private static bool upload_to_ftp_HPE(string fName) { string Hostname = utility.getParameter("crm_ftp_host_HPE"); string dir_path = utility.getParameter("crm_ftp_dir_HPE"); string Username = utility.getParameter("crm_ftp_user_HPE"); string Password = utility.getParameter("crm_ftp_pwd_HPE"); Sftp sftpClient = new Sftp(Hostname, Username, Password); Hashtable h_params = new Hashtable(); bool upload_success; bool changed_dir; try { //NETsFTP.SFTP.Upload(Hostname, dir_path, Username, Password, path_to_file); sftpClient.Connect(22); if (sftpClient.Connected) { } sftpClient.Put(fName, dir_path); sftpClient.Close(); upload_success = true; return upload_success; } catch (DirectoryNotFoundException e) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("FTP ERROR - {0}{1}", utility.newline, e.ToString().Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); changed_dir = false; return changed_dir; } catch (Exception e) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("GENERAL ERROR - {0}", e.ToString().Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); upload_success = false; return upload_success; } }
public byte[] getFile(int jobId, string fileName) { if (fileName.Contains("/")) return null; //fail for securety //if (fileName.Contains(' ')) return null; //fail for securety Sftp sftp = new Sftp(HostName, UserName, Password); sftp.Connect(); sftp.Get( string.Format(@"poy_service/{1}/{0}", fileName, jobId,DataPath), string.Format(@"{0}{1}",tempDir, fileName) ); FileStream fileStream = File.OpenRead(string.Format(@"{0}{1}", tempDir, fileName)); byte[] filedata = new byte[(int)fileStream.Length]; fileStream.Read(filedata, 0, (int)fileStream.Length); File.Delete(string.Format(@"{0}{1}", tempDir, fileName)); return filedata; }