public FTPClientForm(FTPAccount account) { InitializeComponent(); Icon = ShareXResources.Icon; lblStatus.Text = string.Empty; lvFTPList.SubItemEndEditing += lvFTPList_SubItemEndEditing; FtpTrace.AddListener(new TextBoxTraceListener(txtDebug)); Account = account; Client = new FTP(account); pgAccount.SelectedObject = Client.Account; Text = "ShareX FTP client - " + account.Name; lblConnecting.Text = "Connecting to " + account.FTPAddress; TaskEx.Run(() => { Client.Connect(); }, () => { pConnecting.Visible = false; Refresh(); RefreshDirectory(); }); }
public EjecutarTodo(string nombre, string nombrearchivo, ArchivoLocal ctxarchivo, ArchivoRespaldo ctxarchivoRespaldo, FTP ctxftp) : base(nombre, nombrearchivo) { this.ctxarchivo = ctxarchivo; this.ctxarchivoRespaldo = ctxarchivoRespaldo; this.ctxftp = ctxftp; }
/// <summary> /// Создать подключение с удаленым сервером /// </summary> /// <param name="_typeSunc">Тип синхронизации</param> /// <param name="ftpConf">Конфигурация удаленого сервера 'ftp/sftp'</param> /// <param name="webDavConf">Конфигурация удаленого сервера 'WebDav'</param> /// <param name="oneDriveConf">Конфигурация удаленого сервера 'OneDrive'</param> /// <param name="report">Класс для создания отчета ошибок синхронизации</param> public RemoteServer(TypeSunc _typeSunc, FTP ftpConf, Models.SyncBackup.Tasks.WebDav webDavConf, OneDrive oneDriveConf, Report _report, out string NewRefreshTokenToOneDrive) { NewRefreshTokenToOneDrive = null; try { typeSunc = _typeSunc; report = _report; webDavConfToReport = webDavConf; switch (typeSunc) { case TypeSunc.SFTP: { sftp = new SftpClient(ftpConf.HostOrIP, ftpConf.GetToPort(_typeSunc), ftpConf.Login, ftpConf.Passwd); sftp.Connect(); break; } case TypeSunc.FTP: { try { // create an FTP client ftp = new FtpClient(ftpConf.HostOrIP, ftpConf.GetToPort(_typeSunc), ftpConf.Login, ftpConf.Passwd); // begin connecting to the server ftp.Connect(); } catch { ftp = new FtpClient(ftpConf.HostOrIP, ftpConf.GetToPort(_typeSunc), ftpConf.Login, ftpConf.Passwd); ftp.EncryptionMode = FtpEncryptionMode.Explicit; ftp.SslProtocols = SslProtocols.Tls; ftp.ValidateCertificate += new FtpSslValidation(OnValidateCertificate); ftp.Connect(); void OnValidateCertificate(FtpClient control, FtpSslValidationEventArgs e) { // add logic to test if certificate is valid here e.Accept = true; } } break; } case TypeSunc.WebDav: { webDav = new WebDavClient(new WebDavClientParams { BaseAddress = new Uri(webDavConf.url), Credentials = new NetworkCredential(webDavConf.Login, webDavConf.Passwd), PreAuthenticate = true, UseDefaultCredentials = false // Yandex.Disk на linux так работает }); break; } case TypeSunc.OneDrive: { /// <summary> /// Version 2.0.1.0 /// https://github.com/KoenZomers/OneDriveAPI /// </summary> oneDrive = new OneDriveGraphApi(oneDriveConf.ApplicationId); oneDrive.AuthenticateUsingRefreshToken(oneDriveConf.RefreshToken).Wait(); if (!string.IsNullOrWhiteSpace(oneDrive.AccessToken.RefreshToken)) { IsConnectedToOneDrive = true; NewRefreshTokenToOneDrive = oneDrive.AccessToken.RefreshToken; } break; } } } catch (Exception ex) { report.Connect(_typeSunc, ftpConf, webDavConf, oneDriveConf, ex.ToString()); ConnectionError = true; } }
static void Main(string[] args) { //byte[] filetobytes = FTP.GetStreamBytes("C:\\Users\\MY PC\\Desktop\\myimage.jpg"); List <string> errors = new List <string>(); List <string> directories = FTP.GetDirectory(Constants.FTP.BaseUrl); List <Student> studnets = new List <Student>(); Student std = new Student(); string imagesOutputFolder = @" C:\Users\MY PC\Desktop\Images\"; foreach (var directory in directories) { Console.WriteLine(directory); } Student student = new Student(); //student.FromDirectory(directory); //studnets.Add(student); //string[] directoryPart = directory.Split(" ", StringSplitOptions.None); try { Console.WriteLine(Constants.FTP.BaseUrl + "/" + directory + "/"); //Path to the remote file you will download string remoteDownloadFilePath = "/200464602 Dixit Ohri/info.csv"; //Path to a valid folder and the new file to be saved string localDownloadFileDestination = @"C:\Users\MY PC\Desktop\Encoding\info2.csv"; //Path to download myimage file string DownloadFilePath = "/200464602 Dixit Ohri/myimage.jpg"; //Path to a valid folder and the new file to be saved string DownloadFileDestination = @"C:\Users\MY PC\Desktop\Encoding\myimage.jpg"; Console.WriteLine(FTP.DownloadFile(Constants.FTP.BaseUrl + remoteDownloadFilePath, localDownloadFileDestination)); Console.WriteLine(FTP.DownloadFile(Constants.FTP.BaseUrl + DownloadFilePath, DownloadFileDestination)); } catch (Exception e) { Console.WriteLine(e.Message); } //student class if (FTP.FileExists(Constants.FTP.BaseUrl + "/200464602 Dixit Ohri/info.csv")) { Console.WriteLine(" info.csv exist "); } else { errors.Add(directory + " info.csv does not exist "); Console.WriteLine(" info.csv doest not exist "); } if (FTP.FileExists(Constants.FTP.BaseUrl + "/200464602 Dixit Ohri/info.html")) { Console.WriteLine(" info.html exist "); } else { errors.Add(directory + " info.html does not exist "); Console.WriteLine(" info.html doest not exist "); } if (FTP.FileExists(Constants.FTP.BaseUrl + "/200464602 Dixit Ohri/myimage.jpg")) { Console.WriteLine(" myimage.jpg exist "); string downloadFileResult = FTP.DownloadFile(Constants.FTP.BaseUrl + "/200464602 Dixit Ohri/myimage.jpg ", imagesOutputFolder + "myimage.jpg"); Console.WriteLine(downloadFileResult); } else { errors.Add(directory + " myimage.jpg does not exist "); Console.WriteLine(" myimage.jpg doest not exist "); } if (errors.Count > 0) { Console.WriteLine($"Found {errors.Count} errors"); foreach (var er in errors) { Console.WriteLine(er); } } if (FTP.FileExists(Constants.FTP.BaseUrl + "/200464602 Dixit Ohri/" + "info.csv")) { var fileBytes = FTP.DownloadFileBytes(Constants.FTP.BaseUrl + "/200464602 Dixit Ohri/" + "info.csv"); string infoCsvData = Encoding.UTF8.GetString(fileBytes, 0, fileBytes.Length); string[] lines = infoCsvData.Split("\r\n", StringSplitOptions.RemoveEmptyEntries); Student studenta = new Student(); studenta.FromCSV(lines[1]); string dataToString = studenta.ToString(); Console.WriteLine(dataToString); string csvData = studenta.ToCSV(); Console.WriteLine(csvData); } else { Console.WriteLine("File not found"); } List <Student> students = new List <Student>(); List <string> alldirectories = FTP.GetDirectory(Constants.FTP.BaseUrl); foreach (var directory in alldirectories) { Console.WriteLine(directory); Student st = new Student(); if (FTP.FileExists(Constants.FTP.BaseUrl + "/" + directory + "/info.csv")) { var fileBytes = FTP.DownloadFileBytes(Constants.FTP.BaseUrl + "/" + directory + "/info.csv"); string CsvData = Encoding.UTF8.GetString(fileBytes, 0, fileBytes.Length); string[] lines = CsvData.Split("\r\n", StringSplitOptions.RemoveEmptyEntries); st.FromCSV(lines[1]); string dataToString = st.ToString(); Console.WriteLine(dataToString); string csvData = st.ToCSV(); Console.WriteLine(csvData); students.Add(st); } } //Agregate Functions to find max and min, average age and count students Student me = new Student { StudentId = "<200464602>", FirstName = "<Dixit>", LastName = "<Ohri>", DateOfBirth = "1995-02-04", }; int count = students.Count(); Console.WriteLine($"The list contain {count} students"); int highestMax = students.Max(x => x.Age); Console.WriteLine($"The highest Age in the list is {highestMax}"); int lowestMax = students.Min(x => x.Age); Console.WriteLine($"The lowest Age in the list is {lowestMax}"); double averageAge = students.Average(x => x.Age); Console.WriteLine($"The average age is => {averageAge.ToString("0")}"); Student student1 = students.Find(x => x.StudentId == me.StudentId); if (student1 != null) { Console.WriteLine($"Found Student {student1}"); } else { Console.WriteLine($"Could not find Student {student1}"); } Student studentSingleOrDefault = students.SingleOrDefault(x => x.StudentId == me.StudentId); if (studentSingleOrDefault != null) { Console.WriteLine($"Found Student {studentSingleOrDefault}"); } else { Console.WriteLine($"Could not find Student {studentSingleOrDefault}"); } }
public static void TestFTPAccount(FTPAccount account, bool silent) { string msg = string.Empty; string sfp = account.GetSubFolderPath(); switch (account.Protocol) { case FTPProtocol.SFTP: try { using (SFTP sftp = new SFTP(account)) { if (!sftp.IsValidAccount) { msg = "An SFTP client couldn't be instantiated, not enough information.\r\nCould be a missing key file."; } else if (sftp.Connect()) { List<string> createddirs = new List<string>(); if (!sftp.DirectoryExists(sfp)) { createddirs = sftp.CreateMultiDirectory(sfp); } if (sftp.IsConnected) { msg = (createddirs.Count == 0) ? "Connected!" : "Connected!\r\nCreated folders:\r\n"; for (int x = 0; x <= createddirs.Count - 1; x++) { msg += createddirs[x] + "\r\n"; } msg += "\r\n\r\nPing results:\r\n " + SendPing(account.Host, 3); } } } } catch (Exception e) { msg = e.Message; } break; default: try { using (FTP ftpClient = new FTP(account)) { if (ftpClient.ChangeDirectory(sfp, true)) { msg = "Connected!\r\n\r\nPing results:\r\n" + SendPing(account.Host, 3); } } } catch (Exception e) { msg = e.Message; } break; } if (silent) { DebugHelper.WriteLine(string.Format("Tested {0} sub-folder path in {1}", sfp, account)); } else { MessageBox.Show(msg, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public EjecutarFtp(string nombre, string nombrearchivo, ArchivoLocal ctxarchivo, FTP ctxftp) : base(nombre, nombrearchivo) { this.ctxarchivo = ctxarchivo; this.ctxftp = ctxftp; }
private void uploadToFtpButton_Click(object sender, EventArgs e) { uploadToSiteButton.Enabled = false; uploadToFtpButton.Enabled = false; applyEffectButton.Enabled = false; this.lifeTimer.Enabled = false; try { if(mySettings.ftpOKsettings) { FTP f = new FTP(mySettings.ftphostSetting.ToString(), ".", mySettings.ftpusernameSetting, mySettings.ftppasswordSetting, mySettings.ftpportSetting); f.ChangeDirectory(mySettings.ftpdirectorySetting); f.UploadFile(_FileNameToHandle); } else { MessageBox.Show("Please supply ftp settings first"); } //MessageBox.Show("Done"); } catch(Exception ex) { MessageBox.Show(ex.Message); } this.applyEffectButton.Enabled = true; this.uploadToSiteButton.Enabled = true; this.uploadToFtpButton.Enabled = true; this.lifeTimer.Enabled = true; }
static void Main(string[] args) { { CsvFileReaderWriter reader = new CsvFileReaderWriter(); List <string> directories = FTP.GetDirectory(Constants.FTP.BaseUrl); List <Student> students = new List <Student>(); foreach (var directory in directories) { Student student = new Student() { AbsoluteUrl = Constants.FTP.BaseUrl }; student.FromDirectory(directory); Student.counter++; Console.WriteLine("Position " + students.Count); Console.WriteLine(student); string infoFilePath = student.FullPathUrl + "/" + Constants.Locations.InfoFile; bool fileExists = FTP.FileExists(infoFilePath); if (fileExists == true) { Console.WriteLine("Found info file:"); var infoFileBytes = FTP.DownloadFileBytes(infoFilePath); //Convert from infoFileBytes incoming bytes to string string asciiString = Encoding.ASCII.GetString(infoFileBytes, 0, infoFileBytes.Length); var csvFile = reader.ParseString(asciiString); //var entries = reader.GetEntities(csvFile); if (csvFile.Count.Equals(2)) { student.FromCSV(csvFile[1]); //if (student.StudentId.Equals(Constants.myrecord.StudentId)) //{ // student.MyRecord = true; //} if (student.Age >= 15 && student.Age < 100) { Console.WriteLine("The student age is " + student.Age); } else { Console.WriteLine("Invalid age detected"); } } else { Console.WriteLine("Bad CSV data detected"); } } else { Console.WriteLine("Could not find info file:"); } Console.WriteLine("\t" + infoFilePath); string imageFilePath = student.FullPathUrl + "/" + Constants.Locations.ImageFile; bool imageFileExists = FTP.FileExists(imageFilePath); if (imageFileExists == true) { Console.WriteLine("Found image file:"); var imageBytes = FTP.DownloadFileBytes(imageFilePath); Image image = Imaging.byteArrayToImage(imageBytes); //student.ImageData = Imaging.ImageToBase64(image, System.Drawing.Imaging.ImageFormat.Jpeg); } else { Console.WriteLine("Could not find image file:"); } Console.WriteLine("\t" + imageFilePath); students.Add(student); } Student me = students.SingleOrDefault(x => x.StudentId.Equals(Constants.myrecord.StudentId)); me.MyRecord = true; var avgage = students.Average(x => x.Age); var minage = students.Min(x => x.Age); var maxage = students.Max(x => x.Age); Console.WriteLine("Thera are a total of " + students.Count + " records."); Console.WriteLine("The students age average is " + avgage); Console.WriteLine("The older student is " + maxage + " years"); Console.WriteLine("The younger student is " + minage + " years"); foreach (var student in students) { Console.WriteLine(student.ToString()); //Console.WriteLine(student.ToCSV()); } using (var file = File.CreateText($@"{Constants.Locations.ContentFolder}" + "\\Records.csv")) { file.WriteLine("StudentId,FirstName,LastName,DateOfBirth,MyRecord,ImageData"); foreach (var student in students) { file.WriteLine(string.Join(",", student.ToCSV())); } } using (var file = File.CreateText($@"{Constants.Locations.ContentFolder}" + "\\Records.xml")) { foreach (var student in students) { file.WriteLine(string.Join(",", student.ToXML())); } } using (var file = File.CreateText($@"{Constants.Locations.ContentFolder}" + "\\Records.json")) { foreach (var student in students) { file.WriteLine(string.Join(",", student.ToJSON())); } } UploadFolder(Constants.Locations.ContentFolder, Constants.FTP.BaseUrl); } }
private void FTPTestAccount(FTPAccount account) { string msg = ""; string remotePath = account.GetSubFolderPath(); List <string> directories = new List <string>(); try { if (account.Protocol == FTPProtocol.FTP || account.Protocol == FTPProtocol.FTPS) { using (FTP ftp = new FTP(account)) { if (ftp.Connect()) { if (!ftp.DirectoryExists(remotePath)) { directories = ftp.CreateMultiDirectory(remotePath); } if (ftp.IsConnected) { if (directories.Count > 0) { msg = Resources.UploadersConfigForm_TestFTPAccount_Connected_Created_folders + "\r\n" + string.Join("\r\n", directories); } else { msg = Resources.UploadersConfigForm_TestFTPAccount_Connected_; } } } } } else if (account.Protocol == FTPProtocol.SFTP) { using (SFTP sftp = new SFTP(account)) { if (sftp.Connect()) { if (!sftp.DirectoryExists(remotePath)) { directories = sftp.CreateMultiDirectory(remotePath); } if (sftp.IsConnected) { if (directories.Count > 0) { msg = Resources.UploadersConfigForm_TestFTPAccount_Connected_Created_folders + "\r\n" + string.Join("\r\n", directories); } else { msg = Resources.UploadersConfigForm_TestFTPAccount_Connected_; } } } } } } catch (Exception e) { msg = e.Message; } MessageBox.Show(msg, "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Information); }
/// <summary> /// TICK /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void dispatcherTimer_Tick(object sender, EventArgs e) { try { InternetConnectionState_e flags = 0; isConnected = InternetGetConnectedState(ref flags, 0); if (isConnected == false) { return; } if (AvaliableVersions.Count == 0) { return; } String oldLast = AvaliableVersions[AvaliableVersions.Count - 1]; try { ftp = new FTP("ftp.ploobs.com.br", "ploobs", "5ruTrus6"); ftp.Connect(); ftp.ChangeDir("/ploobs/Web/Updater"); System.Collections.ArrayList fileList = ftp.List(); AvaliableVersions.Clear(); listBox1.Items.Clear(); foreach (String item in fileList) { String[] files = item.Split(' '); String file = files[files.Count() - 1]; AvaliableVersions.Add(file); listBox1.Items.Add(file); } } catch (Exception) { ///do not show message box here .... return; } finally { ftp.Disconnect(); } if (oldLast != AvaliableVersions[AvaliableVersions.Count - 1]) { string title = "PloobsUpdates"; string text = "There is a new Version of PloobsEngine Avaliable"; //show balloon with built-in icon this.MyNotifyIcon.ShowBalloonTip(title, text, BalloonIcon.Info); this.MyNotifyIcon.TrayBalloonTipClicked += new RoutedEventHandler(MyNotifyIcon_TrayBalloonTipClicked); } if (AvaliableVersions.Count == 0) { button1.IsEnabled = false; button2.IsEnabled = false; } } catch (Exception) { ///nothing } }
private void button1_Click(object sender, RoutedEventArgs e) { isDownloading = true; this.remove.Dispatcher.BeginInvoke(DispatcherPriority.Send, (Action)(() => { remove.IsEnabled = false; })); HandleXnaVersion(); if (isConnected == false) { MessageBox.Show("No Internet Connection"); return; } try { String sitem = listBox1.SelectedItem as String; if (String.IsNullOrEmpty(sitem)) { MessageBox.Show("You Must select a version"); this.remove.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { remove.IsEnabled = true; })); isDownloading = false; return; } if (sitem != packageName) { if (!String.IsNullOrEmpty(packageName)) { DeleteCurrentEngineVersion(); GetVersionOnRegistry(); if (!String.IsNullOrEmpty(packageName)) { MessageBox.Show("You need to unistall current version to be able to install another"); this.remove.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { remove.IsEnabled = true; })); isDownloading = false; return; } } Random rd = new Random(); int rdnum = rd.Next(); button1.IsEnabled = false; progressBar1.Value = 0; label2.Content = "Downloading"; Task.Factory.StartNew(() => { try { FTP ftp = new FTP("ftp.ploobs.com.br", "ploobs", "5ruTrus6"); ftp.Connect(); ftp.ChangeDir("/ploobs/Web/Updater/" + sitem); String temppath = System.IO.Path.GetTempPath() + System.IO.Path.GetRandomFileName(); ftp.OpenDownload("PloobsEngine.rar", temppath, true); while (ftp.DoDownload() != 0) { progressBar1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { progressBar1.Value = 100 * (float)ftp.BytesTotal / (float)ftp.FileSize; })); } label2.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { label2.Content = "INSTALLING"; })); if (File.Exists(System.IO.Path.GetTempPath() + "PloobsEngine//setup.exe")) { File.Delete(System.IO.Path.GetTempPath() + "PloobsEngine//setup.exe"); } if (Directory.Exists(System.IO.Path.GetTempPath() + "PloobsEngine/")) { Directory.Delete(System.IO.Path.GetTempPath() + "PloobsEngine/", true); } RarArchive.WriteToDirectory(temppath, System.IO.Path.GetTempPath(), NUnrar.Common.ExtractOptions.ExtractFullPath); temppath = System.IO.Path.GetTempPath() + "PloobsEngine//setup.exe"; System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = temppath; process.Start(); process.WaitForExit(); packageName = sitem; GetVersionOnRegistry(); label2.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { label2.Content = "Current Version: " + packageName; })); MySqlCommonConnection.WriteClientToDB(sitem); } catch (Exception ex) { MessageBox.Show(ex.ToString()); label2.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { label2.Content = "ERROR"; })); } finally { button1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { button1.IsEnabled = true; })); if (packageName != null) { label2.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { label2.Content = "CurrentVersion: " + packageName; })); } } } ); } else { MessageBox.Show("You already have this version installed, Unistall it first clicking on Remove Current Version"); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } isDownloading = false; this.remove.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { remove.IsEnabled = true; })); }
static void Main(string[] args) { List <string> directories = FTP.GetDirectory(Constants.Location.FTP.BaseUrl); List <Student> students = new List <Student>(); foreach (var directory in directories) { Console.WriteLine("\n"); Console.WriteLine("Directory - " + directory); Student student = new Student() { AbsoluteUrl = Constants.Location.FTP.BaseUrl }; student.FromDirectory(directory); string infoFilePath = student.FullPathUrl + "/" + Constants.Location.InfoFile; //File Exist bool fileExists = FTP.FileExists(infoFilePath); if (fileExists == true) { Console.WriteLine("Info File Found"); string firstname = student.FirstName; if (student.StudentId == "200447599") { student.MyRecord = true; } else { student.MyRecord = false; } var infoBytes = FTP.DownloadFileBytes(infoFilePath); string csv = Encoding.Default.GetString(infoBytes); string[] csv_content = csv.Split("\r\n", StringSplitOptions.RemoveEmptyEntries); if (csv_content.Length != 2) { Console.WriteLine("Error in CSV format"); } else { student.FromCSV(csv_content[1]); } } else { Console.WriteLine("Info File Not Found"); try { if (student.StudentId == "200447599") { student.MyRecord = true; } else { student.MyRecord = false; } } catch (Exception e) { student.ImageData = "File Not Found"; } } Console.WriteLine("File Path Information - " + infoFilePath); string imageFilePath = student.FullPathUrl + "/" + Constants.Location.ImageFile; bool imageFileExists = FTP.FileExists(imageFilePath); if (imageFileExists == true) { Console.WriteLine("Image file Found"); if ((student.ImageData) == null || student.ImageData.Length < 2) { Console.WriteLine("Image Data Not Found"); try { var ImageBytes = FTP.DownloadFileBytes(imageFilePath); string base64String = Convert.ToBase64String(ImageBytes); student.ImageData = base64String; } catch (Exception e) { student.ImageData = "Image Data Not Found"; } } } else { Console.WriteLine("No Image File"); try { student.ImageData = "Data Not Found"; } catch (Exception e) { student.ImageData = "Data Not Found"; } } Console.WriteLine("File Path of Image - " + imageFilePath); students.Add(student); } using (StreamWriter sw = new StreamWriter(Constants.Location.StudentCSVFile)) { sw.WriteLine((nameof(Student.StudentId)) + ',' + (nameof(Student.FirstName)) + ',' + (nameof(Student.LastName)) + ',' + (nameof(Student.Age)) + ',' + (nameof(Student.DateOfBirth)) + ',' + (nameof(Student.ImageData)) + ',' + (nameof(Student.MyRecord))); foreach (var student in students) { sw.WriteLine(student.ToCSV()); Console.WriteLine("\n"); Console.WriteLine("To CSV - " + student.ToCSV()); Console.WriteLine("\n"); Console.WriteLine("To String - " + student.ToString()); Console.WriteLine("\n"); } } //CSV var csv_lines = File.ReadAllLines(Constants.Location.StudentCSVFile); string[] headers = csv_lines[0].Split(',').Select(x => x.Trim('\"')).ToArray(); //JSON String json_converter = ConvertCsvFileToJsonObject(Constants.Location.StudentCSVFile); File.WriteAllText(Constants.Location.StudentJSONFile, json_converter); //XML var xml_converter = new XElement("root", csv_lines.Where((line, index) => index > 0).Select(line => new XElement("row", line.Split(',').Select((column, index) => new XElement(headers[index], column))))); xml_converter.Save(Constants.Location.StudentXMLFile); /*Aggregation*/ Aggregate.Functions(students); /*Upload the CSV, XML & JSON file to FTP*/ UploadFile.uploadFile(Constants.Location.StudentCSVFile, Constants.Location.FTP.CSVUploadLocation); Console.WriteLine("CSV Uploaded to to my directory in FTP..! \n"); UploadFile.uploadFile(Constants.Location.StudentJSONFile, Constants.Location.FTP.JSONUploadLocation); Console.WriteLine("JSON Uploaded to to my directory in FTP..! \n"); UploadFile.uploadFile(Constants.Location.StudentXMLFile, Constants.Location.FTP.XMLUploadLocation); Console.WriteLine("XML Uploaded to to my directory in FTP..! \n"); return; }
/// <summary> /// 普通FTP上传文件 /// </summary> /// <param name="file">要FTP上传的文件</param> /// <returns>上传是否成功</returns> public bool UpLoadFile(string path, string file, FTPUploadEnum ftpuploadname) { FTP ftpupload = new FTP(); //转换路径分割符为"/" path = path.Replace("\\", "/"); path = path.StartsWith("/") ? path : "/" + path; //删除file参数文件 bool delfile = true; //根据上传名称确定上传的FTP服务器 switch (ftpuploadname) { //论坛附件 case FTPUploadEnum.ForumAttach: { ftpupload = new FTP(m_forumattach.Serveraddress, m_forumattach.Serverport, m_forumattach.Username, m_forumattach.Password, m_forumattach.Timeout); path = m_forumattach.Uploadpath + path; delfile = (m_forumattach.Reservelocalattach == 1) ? false : true; break; } //空间附件 case FTPUploadEnum.SpaceAttach: { ftpupload = new FTP(m_spaceattach.Serveraddress, m_spaceattach.Serverport, m_spaceattach.Username, m_spaceattach.Password, m_spaceattach.Timeout); path = m_spaceattach.Uploadpath + path; delfile = (m_spaceattach.Reservelocalattach == 1) ? false : true; break; } //相册附件 case FTPUploadEnum.AlbumAttach: { ftpupload = new FTP(m_albumattach.Serveraddress, m_albumattach.Serverport, m_albumattach.Username, m_albumattach.Password, m_albumattach.Timeout); path = m_albumattach.Uploadpath + path; delfile = (m_albumattach.Reservelocalattach == 1) ? false : true; break; } //商城附件 case FTPUploadEnum.MallAttach: { ftpupload = new FTP(m_mallattach.Serveraddress, m_mallattach.Serverport, m_mallattach.Username, m_mallattach.Password, m_mallattach.Timeout); path = m_mallattach.Uploadpath + path; delfile = (m_mallattach.Reservelocalattach == 1) ? false : true; break; } } //切换到指定路径下,如果目录不存在,将创建 if (!ftpupload.ChangeDir(path)) { //ftpupload.MakeDir(path); foreach (string pathstr in path.Split('/')) { if (pathstr.Trim() != "") { ftpupload.MakeDir(pathstr); ftpupload.ChangeDir(pathstr); } } } ftpupload.Connect(); if (!ftpupload.IsConnected) { return(false); } int perc = 0; //绑定要上传的文件 if (!ftpupload.OpenUpload(file, System.IO.Path.GetFileName(file))) { ftpupload.Disconnect(); return(false); } //开始进行上传 while (ftpupload.DoUpload() > 0) { perc = (int)(((ftpupload.BytesTotal) * 100) / ftpupload.FileSize); } ftpupload.Disconnect(); //(如存在)删除指定目录下的文件 if (delfile && Utils.FileExists(file)) { System.IO.File.Delete(file); } if (perc >= 100) { return(true); } else { return(false); } }
/// <summary> ///南充社保接口 /// </summary> /// <param name="XmlPara01">交易编号</param> /// <returns>WS返回字符串</returns> public static string yhcall(string XmlPara01, ref string retcode) { string Astr_jyh, Astr_jylsh, Astr_lydz, Astr_ydz, errinfo = "", strRecvXml = ""; byte[] Astr_jyjg = new byte[128], Astr_clxx = new byte[128], Astr_jysj = new byte[128]; int Aint_clbz = 0; if (!init()) { Service_NCSB.WriteLog("init 错误"); strRecvXml = ""; retcode = "0998"; return(strRecvXml); } XmlPara01 = "<Para01>" + XmlPara01 + "</Para01>"; Service_NCSB.WriteLog("XmlPara01[" + XmlPara01 + "]"); XmlDocument xReqPara = new XmlDocument(); try { xReqPara.InnerXml = XmlPara01; Astr_jyh = xReqPara.SelectSingleNode("Para01/Astr_jyh").InnerText; //Service_NCSB.WriteLog("Astr_jyh[" + Astr_jyh + "]"); Astr_jylsh = xReqPara.SelectSingleNode("Para01/Astr_jylsh").InnerText; //Service_NCSB.WriteLog("Astr_jylsh[" + Astr_jylsh + "]"); Astr_lydz = xReqPara.SelectSingleNode("Para01/Astr_lydz").InnerText; //Service_NCSB.WriteLog("Astr_lydz[" + Astr_lydz + "]"); Astr_ydz = xReqPara.SelectSingleNode("Para01/Astr_ydz").InnerText; //Service_NCSB.WriteLog("Astr_ydz[" + Astr_ydz + "]"); if (Astr_jyh == "003" || Astr_jyh == "004") {//处理性交易,需要申请流水号 //Astr_jylsh = getjylsh(Astr_lydz, Astr_ydz); if (Astr_jylsh == "") { Service_NCSB.WriteLog("申请交易流水号不能为空:[" + Astr_lydz + "|" + Astr_ydz + "]"); strRecvXml = ""; retcode = "0998"; return(strRecvXml); } Service_NCSB.WriteLog("jylsh=[" + jylsh + "]"); } Astr_jysj = Encoding.Default.GetBytes(xReqPara.SelectSingleNode("Para01/Astr_jysj").InnerXml); } catch (Exception err) { Service_NCSB.WriteLog("Exception:[" + err.Message + "]"); strRecvXml = ""; retcode = "0998"; return(strRecvXml); } if (Astr_jyh == "998")//对帐文件上传成功,可以对帐 { string jysj, wjdx; string wjmc = xReqPara.SelectSingleNode("Para01/Astr_jysj/jysj/wjmc").InnerText; if (!File.Exists(cfg_NCSB.ftp_localpath + "\\" + wjmc)) { Service_NCSB.WriteLog("ftp文件不存在!"); strRecvXml = ""; retcode = "9989"; return(strRecvXml); } if (!Func.StrFile2XmlFile(cfg_NCSB.ftp_localpath + "/" + wjmc, cfg_NCSB.ftp_localpath + "\\NCSB\\" + wjmc + ".txt", out strRecvXml)) { Service_NCSB.WriteLog(strRecvXml); strRecvXml = ""; retcode = "9989"; return(strRecvXml); } Service_NCSB.WriteLog("StrFile2XmlFile end."); FileInfo fi = new FileInfo(cfg_NCSB.ftp_localpath + "\\NCSB\\" + wjmc + ".txt"); Astr_jysj = Encoding.Default.GetBytes("<jysj><wjmc>" + wjmc + "</wjmc><wjdx>" + fi.Length + "</wjdx></jysj>"); try { FTP ftpObj; Service_NCSB.WriteLog("ftp_ip=[" + cfg_NCSB.ftp_ip + "]"); ftpObj = new FTP(cfg_NCSB.ftp_ip, cfg_NCSB.ftp_user, cfg_NCSB.ftp_passwd); Service_NCSB.WriteLog("FTP Create !"); if (!ftpObj.Put("", cfg_NCSB.ftp_localpath + "\\NCSB\\" + wjmc + ".txt", out errinfo)) { Service_NCSB.WriteLog("Exception:[" + errinfo + "]"); strRecvXml = ""; retcode = "0998"; return(strRecvXml); } } catch (Exception err) { Service_NCSB.WriteLog(err.Message); strRecvXml = ""; retcode = "0998"; return(strRecvXml); } } Service_NCSB.WriteLog("Astr_jyh[" + Astr_jyh + "]"); Service_NCSB.WriteLog("Astr_jylsh[" + Astr_jylsh + "]"); Service_NCSB.WriteLog("Astr_jysj[" + Encoding.Default.GetString(Astr_jysj) + "]"); Service_NCSB.WriteLog("Astr_lydz[" + Astr_lydz + "]"); Service_NCSB.WriteLog("Astr_ydz[" + Astr_ydz + "]"); try { webService.yhcall(Astr_jyh, Astr_jylsh, Astr_jysj, Astr_lydz, Astr_ydz, ref Astr_jyjg, ref Aint_clbz, ref Astr_clxx); strRecvXml = "\r\n<Astr_jyjg>" + Encoding.Default.GetString(Astr_jyjg) + "</Astr_jyjg>\r\n"; strRecvXml += "<Aint_clbz>" + Aint_clbz + "</Aint_clbz>\r\n"; string strTmp = Encoding.Default.GetString(Astr_clxx); Service_NCSB.WriteLog("Astr_clxx=[" + strTmp + "]"); if (strTmp.Length >= 32) { strTmp = strTmp.Substring(0, 32); } strRecvXml += "<Astr_clxx>" + strTmp + "</Astr_clxx>\r\n"; //int iTmp = strTmp.IndexOf("jysj:<jysj>"); //if (iTmp>0) // strRecvXml += "<Astr_clxx>" + strTmp.Substring(0, strTmp.IndexOf("jysj:<jysj>") + 4) + "</Astr_clxx>\r\n"; //else // strRecvXml += "<Astr_clxx>" + strTmp + "</Astr_clxx>\r\n"; //Service_NCSB.WriteLog("strRecvXml:[" + strRecvXml + "]"); } catch (Exception err) { Service_NCSB.WriteLog("err=[" + err.Message + "]"); retcode = "9989"; strRecvXml = ""; return(strRecvXml); } //if (Aint_clbz <= 0 ) //{ // Service_NCSB.WriteLog("yhcall失败:[" + Astr_jyh + "|" + Astr_jylsh + "]"); // Service_NCSB.WriteLog(Encoding.Default.GetString(Astr_clxx)); // strRecvXml = ""; // retcode = "0998"; // return strRecvXml; //} //strRecvXml = Encoding.Default.GetString(Astr_jyjg); retcode = "0000"; return(strRecvXml); }
public ActionResult Create(PromotionModels model) { try { byte[] photoByte = null; PropertyReject(); //# Image if (model.PictureUpload != null && model.PictureUpload.ContentLength > 0) { Byte[] imgByte = new Byte[model.PictureUpload.ContentLength]; model.PictureUpload.InputStream.Read(imgByte, 0, model.PictureUpload.ContentLength); model.PictureByte = imgByte; model.ImageURL = Guid.NewGuid() + Path.GetExtension(model.PictureUpload.FileName); model.PictureUpload = null; photoByte = imgByte; } //# Unlimited Maximum Aearn Amout if (model.IsLimited.HasValue) { if (model.IsLimited.Value) { model.MaximumEarnAmount = null; } else { if (model.MaximumEarnAmount < 0) { ModelState.AddModelError("MaximumEarnAmount", CurrentUser.GetLanguageTextFromKey("Please enter a value greater than or equal to 0")); } } } //# Apply From if (model.FromDate.Value > model.ToDate.Value) { ModelState.AddModelError("FromDate", CurrentUser.GetLanguageTextFromKey("From Date must be less than To Date.")); } //# Unlimited Promotion Time if (model.IsLimitedTime) { model.FromTime = null; model.ToTime = null; } else { model.FromTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, model.TStartTime.Hours, model.TStartTime.Minutes, model.TStartTime.Days); model.ToTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, model.TEndTime.Hours, model.TEndTime.Minutes, model.TEndTime.Days); //========== //if (model.FromDate.Value.Date == model.ToDate.Value.Date) { if (model.FromTime.Value.TimeOfDay >= model.ToTime.Value.TimeOfDay) { ModelState.AddModelError("IsLimitedTime", CurrentUser.GetLanguageTextFromKey("From time must be less than To time")); } } } //# Promotion Date Type if (model.RepeatType == (byte)Commons.ERepeatType.DayOfWeek) { if (model.ListWeekDayV2.Count(x => x.Status == (byte)Commons.EStatus.Deleted) == 7) { ModelState.AddModelError("RepeatType", CurrentUser.GetLanguageTextFromKey("Please select specific days in a week")); } else { model.DateOfWeek = string.Join("-", model.ListWeekDayV2.Where(x => x.Status != (byte)Commons.EStatus.Deleted).Select(x => x.Index).ToList()); } } else if (model.RepeatType == (byte)Commons.ERepeatType.DayOfMonth) { if (model.ListMonthDayV2.Count(x => x.Status == (byte)Commons.EStatus.Deleted) == 31) { ModelState.AddModelError("RepeatType", CurrentUser.GetLanguageTextFromKey("Please select specific days in a month")); } else { model.DateOfMonth = string.Join("-", model.ListMonthDayV2.Where(x => x.Status != (byte)Commons.EStatus.Deleted).Select(x => x.Index).ToList()); } } //# Spending if (model.ListSpendingRule != null) { model.ListSpendingRule = model.ListSpendingRule.Where(x => x.Status != (byte)Commons.EStatus.Deleted).ToList(); if (model.ListSpendingRule.Count > 1) { model.isSpendOperatorAnd = CurrentUser.GetLanguageTextFromKey(model.ListSpendingRule.LastOrDefault().Condition).Equals(CurrentUser.GetLanguageTextFromKey("AND")) ? true : false; } int index = 1; foreach (var item in model.ListSpendingRule) { if (item.SpendOnType == (byte)Commons.ESpendOnType.SpecificItem) { if (item.ListProduct.Count == 0) { ModelState.AddModelError("Spending", CurrentUser.GetLanguageTextFromKey("Please select specific items in item detail for spending rule no.") + index); break; } } if (item.Amount < 0) { ModelState.AddModelError("Spending", CurrentUser.GetLanguageTextFromKey("Please enter value of Quantity/Amount for spending rule no.") + index + ""); break; } else { item.Amount = Math.Round(item.Amount, 2); } index++; } } else { ModelState.AddModelError("Spending", CurrentUser.GetLanguageTextFromKey("The Promotion must have at least one spending rule")); } //# Earning if (model.ListEarningRule != null) { model.ListEarningRule = model.ListEarningRule.Where(x => x.Status != (byte)Commons.EStatus.Deleted).ToList(); if (model.ListEarningRule.Count > 1) { model.isEarnOperatorAnd = CurrentUser.GetLanguageTextFromKey(model.ListEarningRule.LastOrDefault().Condition).Equals(CurrentUser.GetLanguageTextFromKey("AND")) ? true : false; } int index = 1; foreach (var item in model.ListEarningRule) { if (item.EarnType == (byte)Commons.EEarnType.SpecificItem) { if (item.ListProduct.Count == 0) { ModelState.AddModelError("Earning", CurrentUser.GetLanguageTextFromKey("Please select specific items in item detail for earning rule no.") + index); break; } } //======= if (item.bDiscountType == (byte)Commons.EValueType.Percent) { if (item.DiscountValue < 0 || item.DiscountValue > 100) { ModelState.AddModelError("Earning", CurrentUser.GetLanguageTextFromKey("Discount Percent could not larger than 100%")); break; } } else { if (item.DiscountValue < 0) { ModelState.AddModelError("Earning", CurrentUser.GetLanguageTextFromKey("Please enter value of Percent/Value for earning rule no.") + index + ""); break; } else { item.DiscountValue = Math.Round(item.DiscountValue, 2); } } if (item.Quantity < 0) { ModelState.AddModelError("Earning", CurrentUser.GetLanguageTextFromKey("Please enter value of Quantity for earning rule no.") + index + ""); break; } //===== item.DiscountType = item.bDiscountType == (byte)Commons.EValueType.Percent ? false : true; index++; } } else { ModelState.AddModelError("Earning", CurrentUser.GetLanguageTextFromKey("The Promotion must have at least one earnin rule")); } //============ if (!ModelState.IsValid) { if ((ModelState["PictureUpload"]) != null && (ModelState["PictureUpload"]).Errors.Count > 0) { model.ImageURL = ""; } return(View(model)); } //==================== string msg = ""; bool result = _factory.InsertOrUpdatePromotion(model, ref msg); if (result) { //Save Image on Server if (!string.IsNullOrEmpty(model.ImageURL) && model.PictureByte != null) { var originalDirectory = new DirectoryInfo(string.Format("{0}Uploads\\", Server.MapPath(@"\"))); var path = string.Format("{0}{1}", originalDirectory, model.ImageURL); MemoryStream ms = new MemoryStream(photoByte, 0, photoByte.Length); ms.Write(photoByte, 0, photoByte.Length); System.Drawing.Image imageTmp = System.Drawing.Image.FromStream(ms, true); ImageHelper.Me.SaveCroppedImage(imageTmp, path, model.ImageURL, ref photoByte); model.PictureByte = photoByte; FTP.Upload(model.ImageURL, model.PictureByte); ImageHelper.Me.TryDeleteImageUpdated(path); } return(RedirectToAction("Index")); } else { ModelState.AddModelError("Name", msg); return(View(model)); } } catch (Exception ex) { _logger.Error("Promotion_Create: " + ex); return(new HttpStatusCodeResult(400, ex.Message)); } }
public static void TestFTPAccount(FTPAccount account, bool silent) { string msg = string.Empty; string sfp = account.GetSubFolderPath(); switch (account.Protocol) { case FTPProtocol.SFTP: SFTP sftp = new SFTP(account); if (!sftp.IsInstantiated) { msg = "An SFTP client couldn't be instantiated, not enough information.\nCould be a missing key file."; } else if (sftp.Connect()) { List<string> createddirs = new List<string>(); if (!sftp.DirectoryExists(sfp)) { createddirs = sftp.CreateMultipleDirectorys(FTPHelpers.GetPaths(sfp)); } if (sftp.IsConnected) { msg = (createddirs.Count == 0) ? "Connected!" : "Conected!\nCreated folders;\n"; for (int x = 0; x <= createddirs.Count - 1; x++) { msg += createddirs[x] + "\n"; } msg += " \n\nPing results:\n " + SendPing(account.Host, 3); sftp.Disconnect(); } } break; default: using (FTP ftpClient = new FTP(account)) { try { //DateTime time = DateTime.Now; ftpClient.Test(sfp); msg = "Success!"; } catch (Exception e) { if (e.Message.StartsWith("Could not change working directory to")) { try { ftpClient.MakeMultiDirectory(sfp); ftpClient.Test(sfp); msg = "Success!\nAuto created folders: " + sfp; } catch (Exception e2) { msg = e2.Message; } } else { msg = e.Message; } } } if (!string.IsNullOrEmpty(msg)) { string ping = SendPing(account.Host, 3); if (!string.IsNullOrEmpty(ping)) { msg += "\n\nPing results:\n" + ping; } if (silent) { // Engine.MyLogger.WriteLine(string.Format("Tested {0} sub-folder path in {1}", sfp, account.ToString())); } else { //MessageBox.Show(msg, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); } } break; } if (silent) { DebugHelper.WriteLine(string.Format("Tested {0} sub-folder path in {1}", sfp, account.ToString())); } else { MessageBox.Show(msg, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); } }
static void Main(string[] args) { List <string> directories = FTP.GetDirectory(Constants.FTP.BaseUrl); foreach (var directory in directories) { Student student = new Student() { AbsoluteUrl = Constants.FTP.BaseUrl }; student.FromDirectory(directory); Console.WriteLine(student); string infoFilePath = student.FullPathUrl + "/" + Constants.Locations.InfoFile; bool fileExists = FTP.FileExists(infoFilePath); if (fileExists == true) { Console.WriteLine("Found info file:"); } else { Console.WriteLine("Could not find info file:"); } Console.WriteLine("\t" + infoFilePath); string imageFilePath = student.FullPathUrl + "/" + Constants.Locations.ImageFile; bool imageFileExists = FTP.FileExists(imageFilePath); if (imageFileExists == true) { Console.WriteLine("Found image file:"); } else { Console.WriteLine("Could not find image file:"); } Console.WriteLine("\t" + imageFilePath); //Console.WriteLine(directory); } return; //string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); //string exePath = Environment.CurrentDirectory; //string dataFolder = $"{exePath}\\..\\..\\..\\Content\\Data"; //string imagesFolder = $"{exePath}\\..\\..\\..\\Content\\Images"; //string filePath = $@"{Constants.Locations.DataFolder}\{Constants.Locations.InfoFile}"; //string fileContents; //using (StreamReader stream = new StreamReader(filePath)) //{ // fileContents = stream.ReadToEnd(); //} //List<string> entries = new List<string>(); //entries = fileContents.Split("\r\n", StringSplitOptions.RemoveEmptyEntries).ToList(); //Student student = new Student(); //student.FromCSV(entries[1]); //string[] data = entries[1].Split(",", StringSplitOptions.None); //Student student = new Student(); //student.StudentId = data[0]; //student.FirstName = data[1]; //student.LastName = data[2]; //student.DateOfBirth = data[3]; //student.ImageData = data[4]; //Console.WriteLine(student.ToCSV()); //Console.WriteLine(student.ToString()); //string imagefilePath = $"{Constants.Locations.ImagesFolder}\\{Constants.Locations.ImageFile}"; //Image image = Image.FromFile(imagefilePath); //string base64Image = Imaging.ImageToBase64(image, ImageFormat.Jpeg); //student.ImageData = base64Image; //string newfilePath = $"{Constants.Locations.DesktopPath}\\{student.ToString()}.jpg"; //FileInfo newfileinfo = new FileInfo(newfilePath); //Image studentImage = Imaging.Base64ToImage(student.ImageData); //studentImage.Save(newfileinfo.FullName, ImageFormat.Jpeg); }
public async Task <IActionResult> Upload(string Token) { var TokenApi = new Token { TokenDef = _config.GetValue <string>("Token:TokenDef") }; if (TokenApi.TokenDef != Token) { return(this.StatusCode(StatusCodes.Status401Unauthorized, $"O Token informado não é autorizado.")); } try { var file = Request.Form.Files[0]; var dict = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString()); var tipoUpload = dict["TipoUpload"]; var idReferencia = dict["IdReferencia"]; if (Convert.ToInt32(tipoUpload) > 9) { return(this.StatusCode(StatusCodes.Status401Unauthorized, "Favor informar um Tipo de UPLOAD Válido (1.Edificio, 2.Imovel, 3.Vendedor)")); } else if (Convert.ToInt32(tipoUpload) <= 0) { return(this.StatusCode(StatusCodes.Status401Unauthorized, "Favor informar um Tipo de UPLOAD Válido (1.Edificio, 2.Imovel, 3.Vendedor)")); } if (Convert.ToInt64(idReferencia) <= 0) { return(this.StatusCode(StatusCodes.Status401Unauthorized, "Favor informar um Id de Referência Válido.")); } var folderName = ""; //var pathToSave = "C:\\Projetos\\reclameaqui\\ReclameAquiAdmin\\src\\assets"; var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), "Resources"); //var pathToSave = "C:\\Users\\evito\\projetos\\WAIH\\smartimoveis\\smartimoveisAdmin\\src\\assets"; string[] extensoesImagens = new string[] { ".jpg", ".png", ".jpeg" }; if (file.Length > 0) { var nameTipoArquivo = ""; var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var extension = Path.GetExtension(fileName); if (extensoesImagens.Contains(extension)) { folderName = "Image"; nameTipoArquivo = DateTime.Now.ToString().Replace(":", "-").Replace(" ", "").Replace("/", "-") + "-IDR-" + idReferencia + "-TU-" + tipoUpload + extension; } else { return(this.StatusCode(StatusCodes.Status401Unauthorized, "Só é permitido UPLOAD de Imagens.")); } pathToSave = Path.Combine(pathToSave, folderName); var fullPath = Path.Combine(pathToSave, fileName); var fullPathNew = Path.Combine(pathToSave, nameTipoArquivo); //var dbPath = Path.Combine("assets", folderName, nameTipoArquivo); var dbPath = Path.Combine(folderName, nameTipoArquivo); using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } System.IO.File.Move(fullPath, fullPathNew); if (Convert.ToInt32(tipoUpload) == 1) //Edificio { var listFotoEdificio = await _repo.GetFotosEdificioByIdAsync(Convert.ToInt64(idReferencia)); var ordemFinal = 1; if (listFotoEdificio.Count() > 0) { var fotoF = listFotoEdificio.OrderByDescending(x => x.Ordem).FirstOrDefault(); ordemFinal = fotoF.Ordem + 1; } var oFoto = new FotoEdificio(); dbPath = dbPath.Replace("\\", "/"); oFoto.NomeFoto = nameTipoArquivo; oFoto.Caminho = dbPath; oFoto.Ordem = Convert.ToInt32(ordemFinal); oFoto.EdificioId = Convert.ToInt64(idReferencia); _repo.Add(oFoto); } else if (Convert.ToInt32(tipoUpload) == 2) //Imovel { var listFotoEdificio = await _repo.GetFotosImovelByIdAsync(Convert.ToInt64(idReferencia)); var ordemFinal = 1; if (listFotoEdificio.Count() > 0) { var fotoF = listFotoEdificio.OrderByDescending(x => x.Ordem).FirstOrDefault(); ordemFinal = fotoF.Ordem + 1; } var oFoto = new FotoImovel(); dbPath = dbPath.Replace("\\", "/"); oFoto.NomeFoto = nameTipoArquivo; oFoto.Caminho = dbPath; oFoto.Ordem = Convert.ToInt32(ordemFinal); oFoto.ImovelId = Convert.ToInt64(idReferencia); _repo.Add(oFoto); } else if (Convert.ToInt32(tipoUpload) == 3) //Vendedor { var oVendedor = await _repo.GetVendedorByIdAsync(Convert.ToInt64(idReferencia)); oVendedor.Foto = dbPath; _repo.Update(oVendedor); } else if (Convert.ToInt32(tipoUpload) == 4) //FotoAreaEdificio { var listFotoEdificio = await _repo.GetFotosAreaEdificioByIdAsync(Convert.ToInt64(idReferencia)); var ordemFinal = 1; if (listFotoEdificio.Count() > 0) { var fotoF = listFotoEdificio.OrderByDescending(x => x.Ordem).FirstOrDefault(); ordemFinal = fotoF.Ordem + 1; } var oFoto = new FotoAreaEdificio(); dbPath = dbPath.Replace("\\", "/"); oFoto.NomeFoto = nameTipoArquivo; oFoto.Caminho = dbPath; oFoto.Ordem = Convert.ToInt32(ordemFinal); oFoto.EdificioId = Convert.ToInt64(idReferencia); _repo.Add(oFoto); } else if (Convert.ToInt32(tipoUpload) == 5) //FotoPlantaEdificio { var listFotoEdificio = await _repo.GetFotosPlantaEdificioByIdAsync(Convert.ToInt64(idReferencia)); var ordemFinal = 1; if (listFotoEdificio.Count() > 0) { var fotoF = listFotoEdificio.OrderByDescending(x => x.Ordem).FirstOrDefault(); ordemFinal = fotoF.Ordem + 1; } var oFoto = new FotoPlantaEdificio(); dbPath = dbPath.Replace("\\", "/"); oFoto.NomeFoto = nameTipoArquivo; oFoto.Caminho = dbPath; oFoto.Ordem = Convert.ToInt32(ordemFinal); oFoto.EdificioId = Convert.ToInt64(idReferencia); _repo.Add(oFoto); } else if (Convert.ToInt32(tipoUpload) == 6) //FotoAreaImovel { var listFotoEdificio = await _repo.GetFotosAreaImovelByIdAsync(Convert.ToInt64(idReferencia)); var ordemFinal = 1; if (listFotoEdificio.Count() > 0) { var fotoF = listFotoEdificio.OrderByDescending(x => x.Ordem).FirstOrDefault(); ordemFinal = fotoF.Ordem + 1; } var oFoto = new FotoAreaImovel(); dbPath = dbPath.Replace("\\", "/"); oFoto.NomeFoto = nameTipoArquivo; oFoto.Caminho = dbPath; oFoto.Ordem = Convert.ToInt32(ordemFinal); oFoto.ImovelId = Convert.ToInt64(idReferencia); _repo.Add(oFoto); } else if (Convert.ToInt32(tipoUpload) == 7) //FotoPlantaImovel { var listFotoEdificio = await _repo.GetFotosPlantaImovelByIdAsync(Convert.ToInt64(idReferencia)); var ordemFinal = 1; if (listFotoEdificio.Count() > 0) { var fotoF = listFotoEdificio.OrderByDescending(x => x.Ordem).FirstOrDefault(); ordemFinal = fotoF.Ordem + 1; } var oFoto = new FotoPlantaImovel(); dbPath = dbPath.Replace("\\", "/"); oFoto.NomeFoto = nameTipoArquivo; oFoto.Caminho = dbPath; oFoto.Ordem = Convert.ToInt32(ordemFinal); oFoto.ImovelId = Convert.ToInt64(idReferencia); _repo.Add(oFoto); } else if (Convert.ToInt32(tipoUpload) == 8) //Foto Padrão Imovel { var listFotoEdificio = _repo.GetFotosEdificioByIdAsync(Convert.ToInt64(idReferencia)); var oFoto = await _repo.GetFotosImovelByIdAsync(Convert.ToInt64(idReferencia)); dbPath = dbPath.Replace("\\", "/"); var oFotoF = oFoto.Where(x => x.Ordem == 0).FirstOrDefault(); if (oFotoF == null) { oFotoF = new FotoImovel(); oFotoF.NomeFoto = nameTipoArquivo; oFotoF.Caminho = dbPath; oFotoF.Ordem = 0; oFotoF.ImovelId = Convert.ToInt64(idReferencia); _repo.Add(oFotoF); } else { oFotoF.NomeFoto = nameTipoArquivo; oFotoF.Caminho = dbPath; oFotoF.Ordem = 0; _repo.Update(oFotoF); } } else if (Convert.ToInt32(tipoUpload) == 9) //Foto Padrão Edificio { var oFoto = await _repo.GetFotosEdificioByIdAsync(Convert.ToInt64(idReferencia)); dbPath = dbPath.Replace("\\", "/"); var oFotoF = oFoto.Where(x => x.Ordem == 0).FirstOrDefault(); if (oFotoF == null) { oFotoF = new FotoEdificio(); oFotoF.NomeFoto = nameTipoArquivo; oFotoF.Caminho = dbPath; oFotoF.Ordem = 0; oFotoF.EdificioId = Convert.ToInt64(idReferencia); _repo.Add(oFotoF); } else { oFotoF.NomeFoto = nameTipoArquivo; oFotoF.Caminho = dbPath; oFotoF.Ordem = 0; _repo.Update(oFotoF); } } if (await _repo.SaveChangesAsync()) { var ftpApi = new FTP { Host = _config.GetValue <string>("FTP:Host"), Login = _config.GetValue <string>("FTP:Login"), Senha = _config.GetValue <string>("FTP:Senha") }; using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential(ftpApi.Login, ftpApi.Senha); var caminhoftp = $"ftp://{ftpApi.Host}/{dbPath}"; client.UploadFile(caminhoftp, WebRequestMethods.Ftp.UploadFile, fullPathNew); } return(Ok(new { dbPath })); } } else { return(BadRequest()); } } catch (Exception ex) { return(StatusCode(500, $"Internal server error: {ex.Message}")); } return(BadRequest()); }
private UploadResult UploadFile(string ssPath) { FileUploader fileUploader = null; switch (App.Settings.ProfileActive.ImageFileUploaderType) { case FileDestination.Dropbox: fileUploader = new Dropbox(App.UploadersConfig.DropboxOAuth2Info, App.UploadersConfig.DropboxAccountInfo) { UploadPath = NameParser.Parse(NameParserType.URL, Dropbox.TidyUploadPath(App.UploadersConfig.DropboxUploadPath)), AutoCreateShareableLink = App.UploadersConfig.DropboxAutoCreateShareableLink, ShareURLType = App.UploadersConfig.DropboxURLType }; break; case FileDestination.Copy: fileUploader = new Copy(App.UploadersConfig.CopyOAuthInfo, App.UploadersConfig.CopyAccountInfo) { UploadPath = NameParser.Parse(NameParserType.URL, Copy.TidyUploadPath(App.UploadersConfig.CopyUploadPath)), URLType = App.UploadersConfig.CopyURLType }; break; case FileDestination.GoogleDrive: fileUploader = new GoogleDrive(App.UploadersConfig.GoogleDriveOAuth2Info) { IsPublic = App.UploadersConfig.GoogleDriveIsPublic, FolderID = App.UploadersConfig.GoogleDriveUseFolder ? App.UploadersConfig.GoogleDriveFolderID : null }; break; case FileDestination.SendSpace: fileUploader = new SendSpace(APIKeys.SendSpaceKey); switch (App.UploadersConfig.SendSpaceAccountType) { case AccountType.Anonymous: SendSpaceManager.PrepareUploadInfo(APIKeys.SendSpaceKey); break; case AccountType.User: SendSpaceManager.PrepareUploadInfo(APIKeys.SendSpaceKey, App.UploadersConfig.SendSpaceUsername, App.UploadersConfig.SendSpacePassword); break; } break; case FileDestination.Minus: fileUploader = new Minus(App.UploadersConfig.MinusConfig, App.UploadersConfig.MinusOAuth2Info); break; case FileDestination.Box: fileUploader = new Box(App.UploadersConfig.BoxOAuth2Info) { FolderID = App.UploadersConfig.BoxSelectedFolder.id, Share = App.UploadersConfig.BoxShare }; break; case FileDestination.Gfycat: fileUploader = new GfycatUploader(); break; case FileDestination.Ge_tt: fileUploader = new Ge_tt(APIKeys.Ge_ttKey) { AccessToken = App.UploadersConfig.Ge_ttLogin.AccessToken }; break; case FileDestination.Localhostr: fileUploader = new Hostr(App.UploadersConfig.LocalhostrEmail, App.UploadersConfig.LocalhostrPassword) { DirectURL = App.UploadersConfig.LocalhostrDirectURL }; break; case FileDestination.CustomFileUploader: if (App.UploadersConfig.CustomUploadersList.IsValidIndex(App.UploadersConfig.CustomFileUploaderSelected)) { fileUploader = new CustomFileUploader(App.UploadersConfig.CustomUploadersList[App.UploadersConfig.CustomFileUploaderSelected]); } break; case FileDestination.FTP: FTPAccount account = App.UploadersConfig.FTPAccountList.ReturnIfValidIndex(App.UploadersConfig.FTPSelectedImage); if (account != null) { if (account.Protocol == FTPProtocol.FTP || account.Protocol == FTPProtocol.FTPS) { fileUploader = new FTP(account); } else if (account.Protocol == FTPProtocol.SFTP) { fileUploader = new SFTP(account); } } break; case FileDestination.SharedFolder: int idLocalhost = App.UploadersConfig.LocalhostSelectedImages; if (App.UploadersConfig.LocalhostAccountList.IsValidIndex(idLocalhost)) { fileUploader = new SharedFolderUploader(App.UploadersConfig.LocalhostAccountList[idLocalhost]); } break; case FileDestination.Email: using (EmailForm emailForm = new EmailForm(App.UploadersConfig.EmailRememberLastTo ? App.UploadersConfig.EmailLastTo : string.Empty, App.UploadersConfig.EmailDefaultSubject, App.UploadersConfig.EmailDefaultBody)) { emailForm.Icon = ShareXResources.Icon; if (emailForm.ShowDialog() == DialogResult.OK) { if (App.UploadersConfig.EmailRememberLastTo) { App.UploadersConfig.EmailLastTo = emailForm.ToEmail; } fileUploader = new Email { SmtpServer = App.UploadersConfig.EmailSmtpServer, SmtpPort = App.UploadersConfig.EmailSmtpPort, FromEmail = App.UploadersConfig.EmailFrom, Password = App.UploadersConfig.EmailPassword, ToEmail = emailForm.ToEmail, Subject = emailForm.Subject, Body = emailForm.Body }; } } break; case FileDestination.Jira: fileUploader = new Jira(App.UploadersConfig.JiraHost, App.UploadersConfig.JiraOAuthInfo, App.UploadersConfig.JiraIssuePrefix); break; case FileDestination.Mega: fileUploader = new Mega(App.UploadersConfig.MegaAuthInfos, App.UploadersConfig.MegaParentNodeId); break; case FileDestination.AmazonS3: fileUploader = new AmazonS3(App.UploadersConfig.AmazonS3Settings); break; case FileDestination.OwnCloud: fileUploader = new OwnCloud(App.UploadersConfig.OwnCloudHost, App.UploadersConfig.OwnCloudUsername, App.UploadersConfig.OwnCloudPassword) { Path = App.UploadersConfig.OwnCloudPath, CreateShare = App.UploadersConfig.OwnCloudCreateShare, DirectLink = App.UploadersConfig.OwnCloudDirectLink, IgnoreInvalidCert = App.UploadersConfig.OwnCloudIgnoreInvalidCert }; break; case FileDestination.Pushbullet: fileUploader = new Pushbullet(App.UploadersConfig.PushbulletSettings); break; case FileDestination.MediaFire: fileUploader = new MediaFire(APIKeys.MediaFireAppId, APIKeys.MediaFireApiKey, App.UploadersConfig.MediaFireUsername, App.UploadersConfig.MediaFirePassword) { UploadPath = NameParser.Parse(NameParserType.URL, App.UploadersConfig.MediaFirePath), UseLongLink = App.UploadersConfig.MediaFireUseLongLink }; break; } if (fileUploader != null) { ReportProgress(ProgressType.UPDATE_STATUSBAR_DEBUG, string.Format("Uploading {0}.", Path.GetFileName(ssPath))); return fileUploader.Upload(ssPath); } return null; }
public ActionResult Index(RegisterModels model) { try { string msg = ""; byte[] photoByte1 = null; byte[] photoByte2 = null; //Customer Image if (!string.IsNullOrEmpty(model.CustomerDetail.ImageURL)) { model.CustomerDetail.ImageURL = model.CustomerDetail.ImageURL.Replace(CommonHelper.PublicImages, "").Replace(Commons.Image200_200, ""); } if (model.CustomerDetail.PictureUpload != null && model.CustomerDetail.PictureUpload.ContentLength > 0) { Byte[] imgByte1 = new Byte[model.CustomerDetail.PictureUpload.ContentLength]; model.CustomerDetail.PictureUpload.InputStream.Read(imgByte1, 0, model.CustomerDetail.PictureUpload.ContentLength); model.CustomerDetail.PictureByte = imgByte1; model.CustomerDetail.ImageURL = Guid.NewGuid() + Path.GetExtension(model.CustomerDetail.PictureUpload.FileName); model.CustomerDetail.PictureUpload = null; photoByte1 = imgByte1; } //Merchant Image if (!string.IsNullOrEmpty(model.MerchantDetail.ImageURL)) { model.MerchantDetail.ImageURL = model.MerchantDetail.ImageURL.Replace(CommonHelper.PublicImages, "").Replace(Commons.Image200_200, ""); } if (model.MerchantDetail.PictureUpload != null && model.MerchantDetail.PictureUpload.ContentLength > 0) { Byte[] imgByte2 = new Byte[model.MerchantDetail.PictureUpload.ContentLength]; model.MerchantDetail.PictureUpload.InputStream.Read(imgByte2, 0, model.MerchantDetail.PictureUpload.ContentLength); model.MerchantDetail.PictureByte = imgByte2; model.MerchantDetail.ImageURL = Guid.NewGuid() + Path.GetExtension(model.MerchantDetail.PictureUpload.FileName); model.MerchantDetail.PictureUpload = null; photoByte2 = imgByte2; } bool result = _factory.Create(model, ref msg); if (result) { if (!string.IsNullOrEmpty(model.CustomerDetail.ImageURL) && photoByte1 != null) { var originalDirectory = new DirectoryInfo(string.Format("{0}Uploads\\", Server.MapPath(@"\"))); var path = string.Format("{0}{1}", originalDirectory, model.CustomerDetail.ImageURL); MemoryStream ms = new MemoryStream(photoByte1, 0, photoByte1.Length); ms.Write(photoByte1, 0, photoByte1.Length); System.Drawing.Image imageTmp = System.Drawing.Image.FromStream(ms, true); ImageHelper.Me.SaveCroppedImage(imageTmp, path, model.CustomerDetail.ImageURL, ref photoByte1); FTP.UploadClient(model.CustomerDetail.ImageURL, photoByte1); ImageHelper.Me.TryDeleteImageUpdated(path); } if (!string.IsNullOrEmpty(model.MerchantDetail.ImageURL) && photoByte2 != null) { var originalDirectory = new DirectoryInfo(string.Format("{0}Uploads\\", Server.MapPath(@"\"))); var path = string.Format("{0}{1}", originalDirectory, model.MerchantDetail.ImageURL); MemoryStream ms = new MemoryStream(photoByte2, 0, photoByte2.Length); ms.Write(photoByte2, 0, photoByte2.Length); System.Drawing.Image imageTmp = System.Drawing.Image.FromStream(ms, true); ImageHelper.Me.SaveCroppedImage(imageTmp, path, model.MerchantDetail.ImageURL, ref photoByte2); FTP.UploadClient(model.MerchantDetail.ImageURL, photoByte2); ImageHelper.Me.TryDeleteImageUpdated(path); } VerificationModels models = new VerificationModels(); models.ReSendEmail = model.CustomerDetail.Email; return(new HttpStatusCodeResult(HttpStatusCode.OK)); } else { //ModelState.AddModelError("CustomerDetail.Email", msg); model.CustomerDetail.ImageURL = ""; model.MerchantDetail.ImageURL = ""; Response.StatusCode = (int)HttpStatusCode.BadRequest; return(View(model)); } } catch (Exception ex) { NSLog.Logger.Error("RegisterCreate: ", ex); return(new HttpStatusCodeResult(400, ex.Message)); } }
/// <summary> /// This function tests the FTP connection if valid values are given /// </summary> private void ftpTestConnButton_Click(object sender, EventArgs e) { try { FTP f = new FTP(mySettings.ftphostSetting.ToString(), ".", mySettings.ftpusernameSetting, mySettings.ftppasswordSetting, mySettings.ftpportSetting); f.ChangeDirectory(mySettings.ftpdirectorySetting); mySettings.ftpOKsettings = true; mySettings.Save(); utilities.ShowMessage("Test Successfull", "FTP Test"); } catch(Exception ex) { mySettings.ftpOKsettings = false; mySettings.Save(); utilities.ShowMessage(ex.Message + Environment.NewLine + "Test Failed", "Failed"); } }
protected void Page_Load(object sender, EventArgs e) { IFTP ftpClient = new FTP("ftp.msent.co.uk", "/", "extranet", "Extranet1"); try { ftpClient.connect(); ftpClient.uploadFile(@"C:\nexus 7\test.csv"); } catch (Exception ex) { } if (HttpContext.Current.User.Identity.Name.ToString() == "appleadmin1") { this.pnlAdmin.Visible = true; this.oustandingFileCounts(); } this.oracleExportDates(); if (this.IsPostBack) return; this.bindSafetyData(); }
private void ShowRLCServerFileViewer() { ListViewItem lvi; ListViewItem.ListViewSubItem lvsi; lstItems.Items.Clear(); FTP clsFTP = new FTP(); clsFTP.Connect(CONFIG.FTPIPAddress, CONFIG.FTPUsername, CONFIG.FTPPassword); if (CONFIG.FTPDirectory != null && CONFIG.FTPDirectory != string.Empty) clsFTP.ChangeDirectory(CONFIG.FTPDirectory); grpRLC.Text = "RLC File Server Management: [DOUBLE CLICK TO RELOAD] : " + CONFIG.FTPDirectory; try { foreach (FTP.File strFile in clsFTP.Files) { if (strFile.ToString() != string.Empty) { lvi = new ListViewItem(); lvi.Text = strFile.FileName; //lvi.ImageIndex = 0; lvi.Tag = strFile.ToString(); lvsi = new ListViewItem.ListViewSubItem(); lvsi.Text = strFile.FileSize.ToString() + " kb"; lvi.SubItems.Add(lvsi); lvsi = new ListViewItem.ListViewSubItem(); lvsi.Text = strFile.FileDate.ToString("MM/dd/yyyy hh:mm tt"); lvi.SubItems.Add(lvsi); lstItems.Items.Add(lvi); } } } catch (Exception ex) { MessageBox.Show("Error encountered while loading file list. " + Environment.NewLine + "Err #: " + ex.Message, "RetailPlus", MessageBoxButtons.OK); } clsFTP.Disconnect(); clsFTP = null; }
private int SendToFtp(string ftpDir, string ftpurl, string username, string password, string pathCss, string pathHtml, string pathImg, string pathJs) { int res = 0; try { var url = ftpurl; if (!string.IsNullOrEmpty(ftpDir)) { url = ftpurl + "/" + ftpDir; } /*Create directory*/ FTP ftpClient = new FTP(@"ftp://" + url + "/", username, password); /* Create a New Directory */ ftpClient.createDirectory("/css"); ftpClient.createDirectory("/img"); ftpClient = null; string[] htmlPaths = Directory.GetFiles(pathHtml, "*.html"); var imgPaths = Directory.EnumerateFiles(pathImg, "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".jpg") || s.EndsWith(".jpeg") || s.EndsWith(".svg") || s.EndsWith(".gif") || s.EndsWith(".png") || s.EndsWith(".bmp") || s.EndsWith(".tiff") || s.EndsWith(".tif")); var pathCssfiles = Directory.EnumerateFiles(pathCss, "*.*", SearchOption.AllDirectories); using (WebClient client = new WebClient()) { foreach (var html in htmlPaths) { client.Credentials = new NetworkCredential(username, password); client.UploadFile( "ftp://" + url + "/" + Path.GetFileName(html), html); } foreach (var img in imgPaths) { client.Credentials = new NetworkCredential(username, password); client.UploadFile( "ftp://" + url + "/img/" + Path.GetFileName(img), img); } foreach (var pcss in pathCssfiles) { client.Credentials = new NetworkCredential(username, password); client.UploadFile( "ftp://" + url + "/css/" + Path.GetFileName(pcss), pcss); } if (Session["TemplateName"] != null && Session["TemplateName"].ToString() == "Theme3") { ftpClient = new FTP(@"ftp://" + url + "/", username, password); ftpClient.createDirectory("/js"); ftpClient = null; var pathJsfiles = Directory.EnumerateFiles(pathJs, "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".js")); foreach (var pJs in pathJsfiles) { client.Credentials = new NetworkCredential(username, password); client.UploadFile( "ftp://" + url + "/js/" + Path.GetFileName(pJs), pJs); } } } } catch (Exception ex) { res = 1; } return(res); }
public static void TestFTPAccount(FTPAccount account) { string msg = string.Empty; string remotePath = account.GetSubFolderPath(); List<string> directories = new List<string>(); try { if (account.Protocol == FTPProtocol.FTP || account.Protocol == FTPProtocol.FTPS) { using (FTP ftp = new FTP(account)) { if (ftp.Connect()) { if (!ftp.DirectoryExists(remotePath)) { directories = ftp.CreateMultiDirectory(remotePath); } if (ftp.IsConnected) { if (directories.Count > 0) { msg = "Connected!\r\nCreated folders:\r\n" + string.Join("\r\n", directories); } else { msg = "Connected!"; } } } } } else if (account.Protocol == FTPProtocol.SFTP) { using (SFTP sftp = new SFTP(account)) { if (sftp.Connect()) { if (!sftp.DirectoryExists(remotePath)) { directories = sftp.CreateMultiDirectory(remotePath); } if (sftp.IsConnected) { if (directories.Count > 0) { msg = "Connected!\r\nCreated folders:\r\n" + string.Join("\r\n", directories); } else { msg = "Connected!"; } } } } } } catch (Exception e) { msg = e.Message; } MessageBox.Show(msg, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); }
private void FTPUpload_Plugins() { if (nonUploadedFiles.Count <= 0) { return; } var c = Program.Configs[Program.SelectedConfig]; if (string.IsNullOrWhiteSpace(c.FTPHost) || string.IsNullOrWhiteSpace(c.FTPUser)) { return; } var stringOutput = new StringBuilder(); try { var ftp = new FTP(c.FTPHost, c.FTPUser, c.FTPPassword); foreach (var file in nonUploadedFiles) { var fileInfo = new FileInfo(file); if (fileInfo.Exists) { string uploadDir; if (string.IsNullOrWhiteSpace(c.FTPDir)) { uploadDir = fileInfo.Name; } else { uploadDir = c.FTPDir.TrimEnd('/') + "/" + fileInfo.Name; } try { ftp.Upload(uploadDir, file); stringOutput.AppendLine($"{Program.Translations.GetLanguage("Uploaded")}: " + file); } catch (Exception e) { stringOutput.AppendLine(string.Format(Program.Translations.GetLanguage("ErrorUploadFile"), file, uploadDir)); stringOutput.AppendLine($"{Program.Translations.GetLanguage("Details")}: " + e.Message); } } } } catch (Exception e) { stringOutput.AppendLine(Program.Translations.GetLanguage("ErrorUpload")); stringOutput.AppendLine($"{Program.Translations.GetLanguage("Details")}: " + e.Message); } stringOutput.AppendLine(Program.Translations.GetLanguage("Done")); Dispatcher.Invoke(() => { CompileOutput.Text = stringOutput.ToString(); if (CompileOutputRow.Height.Value < 11.0) { CompileOutputRow.Height = new GridLength(200.0); } }); }
public UploadResult UploadFile(Stream stream, string fileName) { FileUploader fileUploader = null; FileDestination fileDestination; switch (Info.DataType) { case EDataType.Image: fileDestination = Info.TaskSettings.ImageFileDestination; break; case EDataType.Text: fileDestination = Info.TaskSettings.TextFileDestination; break; default: case EDataType.File: fileDestination = Info.TaskSettings.FileDestination; break; } switch (fileDestination) { case FileDestination.Dropbox: fileUploader = new Dropbox(Program.UploadersConfig.DropboxOAuth2Info, Program.UploadersConfig.DropboxAccountInfo) { UploadPath = NameParser.Parse(NameParserType.URL, Dropbox.TidyUploadPath(Program.UploadersConfig.DropboxUploadPath)), AutoCreateShareableLink = Program.UploadersConfig.DropboxAutoCreateShareableLink, ShareURLType = Program.UploadersConfig.DropboxURLType }; break; case FileDestination.OneDrive: fileUploader = new OneDrive(Program.UploadersConfig.OneDriveOAuth2Info); break; case FileDestination.Copy: fileUploader = new Copy(Program.UploadersConfig.CopyOAuthInfo, Program.UploadersConfig.CopyAccountInfo) { UploadPath = NameParser.Parse(NameParserType.URL, Copy.TidyUploadPath(Program.UploadersConfig.CopyUploadPath)), URLType = Program.UploadersConfig.CopyURLType }; break; case FileDestination.GoogleDrive: fileUploader = new GoogleDrive(Program.UploadersConfig.GoogleDriveOAuth2Info) { IsPublic = Program.UploadersConfig.GoogleDriveIsPublic, FolderID = Program.UploadersConfig.GoogleDriveUseFolder ? Program.UploadersConfig.GoogleDriveFolderID : null }; break; case FileDestination.RapidShare: fileUploader = new RapidShare(Program.UploadersConfig.RapidShareUsername, Program.UploadersConfig.RapidSharePassword, Program.UploadersConfig.RapidShareFolderID); break; case FileDestination.SendSpace: fileUploader = new SendSpace(APIKeys.SendSpaceKey); switch (Program.UploadersConfig.SendSpaceAccountType) { case AccountType.Anonymous: SendSpaceManager.PrepareUploadInfo(APIKeys.SendSpaceKey); break; case AccountType.User: SendSpaceManager.PrepareUploadInfo(APIKeys.SendSpaceKey, Program.UploadersConfig.SendSpaceUsername, Program.UploadersConfig.SendSpacePassword); break; } break; case FileDestination.Minus: fileUploader = new Minus(Program.UploadersConfig.MinusConfig, Program.UploadersConfig.MinusOAuth2Info); break; case FileDestination.Box: fileUploader = new Box(Program.UploadersConfig.BoxOAuth2Info) { FolderID = Program.UploadersConfig.BoxSelectedFolder.id, Share = Program.UploadersConfig.BoxShare }; break; case FileDestination.Gfycat: fileUploader = new GfycatUploader(); break; case FileDestination.Ge_tt: fileUploader = new Ge_tt(APIKeys.Ge_ttKey) { AccessToken = Program.UploadersConfig.Ge_ttLogin.AccessToken }; break; case FileDestination.Localhostr: fileUploader = new Hostr(Program.UploadersConfig.LocalhostrEmail, Program.UploadersConfig.LocalhostrPassword) { DirectURL = Program.UploadersConfig.LocalhostrDirectURL }; break; case FileDestination.CustomFileUploader: if (Program.UploadersConfig.CustomUploadersList.IsValidIndex(Program.UploadersConfig.CustomFileUploaderSelected)) { fileUploader = new CustomFileUploader(Program.UploadersConfig.CustomUploadersList[Program.UploadersConfig.CustomFileUploaderSelected]); } break; case FileDestination.FTP: int index; if (Info.TaskSettings.OverrideFTP) { index = Info.TaskSettings.FTPIndex.BetweenOrDefault(0, Program.UploadersConfig.FTPAccountList.Count - 1); } else { index = Program.UploadersConfig.GetFTPIndex(Info.DataType); } FTPAccount account = Program.UploadersConfig.FTPAccountList.ReturnIfValidIndex(index); if (account != null) { if (account.Protocol == FTPProtocol.FTP || account.Protocol == FTPProtocol.FTPS) { fileUploader = new FTP(account); } else if (account.Protocol == FTPProtocol.SFTP) { fileUploader = new SFTP(account); } } break; case FileDestination.SharedFolder: int idLocalhost = Program.UploadersConfig.GetLocalhostIndex(Info.DataType); if (Program.UploadersConfig.LocalhostAccountList.IsValidIndex(idLocalhost)) { fileUploader = new SharedFolderUploader(Program.UploadersConfig.LocalhostAccountList[idLocalhost]); } break; case FileDestination.Email: using (EmailForm emailForm = new EmailForm(Program.UploadersConfig.EmailRememberLastTo ? Program.UploadersConfig.EmailLastTo : string.Empty, Program.UploadersConfig.EmailDefaultSubject, Program.UploadersConfig.EmailDefaultBody)) { emailForm.Icon = ShareXResources.Icon; if (emailForm.ShowDialog() == DialogResult.OK) { if (Program.UploadersConfig.EmailRememberLastTo) { Program.UploadersConfig.EmailLastTo = emailForm.ToEmail; } fileUploader = new Email { SmtpServer = Program.UploadersConfig.EmailSmtpServer, SmtpPort = Program.UploadersConfig.EmailSmtpPort, FromEmail = Program.UploadersConfig.EmailFrom, Password = Program.UploadersConfig.EmailPassword, ToEmail = emailForm.ToEmail, Subject = emailForm.Subject, Body = emailForm.Body }; } else { StopRequested = true; } } break; case FileDestination.Jira: fileUploader = new Jira(Program.UploadersConfig.JiraHost, Program.UploadersConfig.JiraOAuthInfo, Program.UploadersConfig.JiraIssuePrefix); break; case FileDestination.Mega: fileUploader = new Mega(Program.UploadersConfig.MegaAuthInfos, Program.UploadersConfig.MegaParentNodeId); break; case FileDestination.AmazonS3: fileUploader = new AmazonS3(Program.UploadersConfig.AmazonS3Settings); break; case FileDestination.OwnCloud: fileUploader = new OwnCloud(Program.UploadersConfig.OwnCloudHost, Program.UploadersConfig.OwnCloudUsername, Program.UploadersConfig.OwnCloudPassword) { Path = Program.UploadersConfig.OwnCloudPath, CreateShare = Program.UploadersConfig.OwnCloudCreateShare, DirectLink = Program.UploadersConfig.OwnCloudDirectLink }; break; case FileDestination.Pushbullet: fileUploader = new Pushbullet(Program.UploadersConfig.PushbulletSettings); break; case FileDestination.MediaCrush: fileUploader = new MediaCrushUploader(); break; case FileDestination.MediaFire: fileUploader = new MediaFire(APIKeys.MediaFireAppId, APIKeys.MediaFireApiKey, Program.UploadersConfig.MediaFireUsername, Program.UploadersConfig.MediaFirePassword) { UploadPath = NameParser.Parse(NameParserType.URL, Program.UploadersConfig.MediaFirePath), UseLongLink = Program.UploadersConfig.MediaFireUseLongLink }; break; } if (fileUploader != null) { PrepareUploader(fileUploader); return fileUploader.Upload(stream, fileName); } return null; }
void DownLoadProtocol() { try { int totalReadBytesCount = 0; string[] DosyaListesi; StringBuilder result = new StringBuilder(); FtpWebRequest FTP; FTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpdown)); // Dosya tranferinin Binary türden yapılacağını belirtiyoruz FTP.UseBinary = true; // Ftp bağlantısı için UserName ve Şifremizi belirtiyoruz FTP.Credentials = new NetworkCredential(kullanici, sifre); // Bu kısımda hangi işlemi yapacağımızı belirtiyoruz FTP.Method = WebRequestMethods.Ftp.ListDirectory; FTP.Method = WebRequestMethods.Ftp.ListDirectory; // Dosya listesini alıyoruz WebResponse response = FTP.GetResponse(); // Aldığımız listeyi StreamReader ile her satırını okuyup dosya isimlerini ayırıyoruz StreamReader reader = new StreamReader(response.GetResponseStream()); string line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf('\n'), 1); reader.Close(); response.Close(); DosyaListesi = result.ToString().Split('\n'); FtpWebResponse response5 = null; for (int x = 0; x < DosyaListesi.Count(); x++) { FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpdown + DosyaListesi[x].ToString())); request.Proxy = null; request.Credentials = new NetworkCredential(kullanici, sifre); request.Method = WebRequestMethods.Ftp.GetFileSize; response5 = (FtpWebResponse)request.GetResponse(); size += response5.ContentLength; } response5.Close(); progressBar1.Maximum = Convert.ToInt32(size); label2.Text = "Dosyalar İndiriliyor..."; for (int x = 0; x < DosyaListesi.Count(); x++) { int kntrl = 0; for (int i = 0; i < DosyaListesi[x].Length; i++) { if (DosyaListesi[x][i].ToString() == ".") { kntrl = 1; } } if (kntrl == 1) { FileStream SR = new FileStream(Application.StartupPath + "\\" + DosyaListesi[x].ToString(), FileMode.Create); FtpWebRequest FTPi0; FTPi0 = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpdown + DosyaListesi[x].ToString())); FTPi0.Credentials = new NetworkCredential(kullanici, sifre); FTPi0.Method = WebRequestMethods.Ftp.DownloadFile; FTPi0.UseBinary = true; FtpWebResponse response2 = (FtpWebResponse)FTPi0.GetResponse(); Stream ftpStream = response2.GetResponseStream(); long cl = response2.ContentLength; int bufferSize = 1024; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); progressBar1.Value += readCount; label1.Text = "Dosya İndiriliyor...: " + DosyaListesi[x].ToString(); while (readCount > 0) { SR.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); progressBar1.Value += readCount; } ftpStream.Close(); SR.Close(); response2.Close(); label1.Text = "Dosya İndi...: " + DosyaListesi[x].ToString(); } else { FtpWebRequest FTP2; Directory.CreateDirectory(Application.StartupPath + "\\" + DosyaListesi[x]); string[] DosyaListesi2; FTP2 = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpdown + DosyaListesi[x])); FTP2.UseBinary = true; FTP2.Credentials = new NetworkCredential(kullanici, sifre); StringBuilder result2 = new StringBuilder(); FTP2.Method = WebRequestMethods.Ftp.ListDirectory; WebResponse response3 = FTP2.GetResponse(); StreamReader reader3 = new StreamReader(response3.GetResponseStream()); string line3 = reader3.ReadLine(); while (line3 != null) { result2.Append(line3); result2.Append("\n"); line3 = reader3.ReadLine(); } result2.Remove(result2.ToString().LastIndexOf('\n'), 1); reader3.Close(); response3.Close(); DosyaListesi2 = result2.ToString().Split('\n'); for (int y = 0; y < DosyaListesi2.Length; y++) { kntrl = 0; for (int i = 0; i < DosyaListesi2[y].Length; i++) { if (DosyaListesi2[y][i].ToString() == ".") { kntrl = 1; } } if (kntrl == 1) { try { FileStream SR = new FileStream(Application.StartupPath + "\\" + DosyaListesi[x].ToString() + "\\" + DosyaListesi2[y].ToString(), FileMode.Create); FtpWebRequest FTPi0; FTPi0 = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpdown + DosyaListesi[x].ToString() + @"/" + DosyaListesi2[y].ToString())); FTPi0.Credentials = new NetworkCredential(kullanici, sifre); FTPi0.Method = WebRequestMethods.Ftp.DownloadFile; FTPi0.UseBinary = true; FTPi0.Method = WebRequestMethods.Ftp.DownloadFile; FTPi0.UseBinary = true; FtpWebResponse response2 = (FtpWebResponse)FTPi0.GetResponse(); Stream ftpStream2 = response2.GetResponseStream(); long cl = response2.ContentLength; int bufferSize = 1024; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream2.Read(buffer, 0, bufferSize); progressBar1.Value += readCount; label1.Text = "Dosya İndiriliyor...: " + DosyaListesi[x].ToString() + "\\" + DosyaListesi2[y].ToString(); while (readCount > 0) { SR.Write(buffer, 0, readCount); readCount = ftpStream2.Read(buffer, 0, bufferSize); progressBar1.Value += readCount; } ftpStream2.Close(); SR.Close(); response2.Close(); } catch {; } label1.Text = "Dosya İndi...: " + DosyaListesi[x].ToString() + "\\" + DosyaListesi2[y].ToString(); response3.Close(); response.Close(); } } } } System.Threading.Thread.Sleep(2000); } catch { MessageBox.Show("Sunucuya şuan bağlantı yapılamadı.Lütfen daha sonra tekrar deneyiniz", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } if (MessageBox.Show("Sisteminiz Güncellendi.Sisteminiz yeniden başlatılacaktır.Şimdi Başlatmak istiyor musunuz ?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { System.Diagnostics.Process.Start(Application.StartupPath + "\\JM Otobüs Yazılımı.exe"); Application.Exit(); } else { Application.Exit(); } }