private void Form1_Load(object sender, EventArgs e) { Assembly assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory.ToString() + @"\ListaTubeLe.exe"); var found = new AssemblyName(assembly.FullName); Versao = "Versão " + found.Version.Major + "." + found.Version.Minor + "." + found.Version.Build + "." + found.Version.Revision; // Puxar o XML atualizado do FTP try { using (Ftp client = new Ftp()) { client.Connect("ftp...."); client.Login("X", "Y"); string path = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + @"ListaTube.xml"; client.Download("/public_html/letube/FtpTrial-ListaTube.xml", path); dsResultado.ReadXml(path); NrVideos = dsResultado.Tables[0].Rows.Count; MostraVideo(0); } } catch (Exception ex) { loga("Erro no FTP"); throw; } }
private void god(string path, string dir) { using (Ftp client = new Ftp()) { try { // connect and login to the FTP client.Connect(path); client.Login("anonymous", "DONT-LOOK@MYCODE"); client.StateChanged += StateChanged; client.Traversing += Traversing; client.TransferProgressChanged += TransferProgressChanged; client.DeleteProgressChanged += DeleteProgressChanged; client.ProblemDetected += ProblemDetected; client.PutFile(dir, @"/user/app/temp.pkg"); client.SendCommand("installpkg"); var response = client.ReadResponse(); MessageBox.Show(response.Raw); SetText("Package Sent"); } catch (Exception ex) { MessageBox.Show(ex.Message); } client.Disconnect(); } }
/// <summary> /// ftp transfer /// </summary> /// <param name="content">ftp content</param> /// <param name="sftpSetting">ftp setting</param> /// <returns></returns> bool FTPTransfer(string content, SFTPSetting sftpSetting) { try { _logger.LogInformation($"ftp begin"); using (var ftp = new Ftp()) { ftp.Connect(sftpSetting.Host); ftp.Login(sftpSetting.UserName, sftpSetting.Password); ftp.Mode = FtpMode.Active; ftp.ChangeFolder(sftpSetting.TransferDirectory); var encoding = Encoding.GetEncoding(sftpSetting.FileEncoding); var response = ftp.Upload($"{sftpSetting.TransferFilePrefix}{sftpSetting.FileName}", 0, encoding.GetBytes(content)); if (response.Code.HasValue && (response.Code.Value == 226 || response.Code.Value == 200)) { ftp.Close(); _logger.LogInformation($"ftp uplodad success"); return(true); } else { _logger.LogError($"ftp uplodad failure,because:{response.Message}"); ftp.Close(); return(false); } } } catch (Exception exc) { _logger.LogCritical(exc, $"ftp uplodad failure:{exc.Message}"); return(false); } }
public void Supprimer(ITransfer transfer) { using (_monFtp = new Ftp()) { _monFtp.Connect(_maConfig.Host, _maConfig.Port); _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteChemin = MethodesGlobales.GetCheminServerSansRacinne(transfer.GetPath(), _maConfig.GetUriChaine()); if (string.IsNullOrEmpty(resteChemin)) { VariablesGlobales._leLog.LogCustom("Vous ne pouvez supprimer le répertoire racinne !"); MessageBox.Show("Vous ne pouvez supprimer le répertoire racinne !"); } else { if (transfer.EstUnDossier()) { _monFtp.DeleteFolder(resteChemin); } else { _monFtp.DeleteFile(resteChemin); } } _monFtp.Close(); } }
List <ITransfer> IClientFtp.ListFileFolder(string unDossier) { List <FtpItem> lesFtpElements = new List <FtpItem>(); List <ITransfer> lesElements = new List <ITransfer>(); using (Ftp monFtp = new Ftp()) { monFtp.Connect(_maConfig.Host, _maConfig.Port); // or ConnectSSL for SSL monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteChemin = MethodesGlobales.GetCheminServerSansRacinne(unDossier, _maConfig.GetUriChaine()); if (!string.IsNullOrEmpty(resteChemin)) { monFtp.ChangeFolder(resteChemin); } lesFtpElements = monFtp.GetList(); monFtp.Close(); } foreach (FtpItem unFtpItem in lesFtpElements) { if (unFtpItem.IsFile) { lesElements.Add(new ElementFile(unFtpItem, Path.Combine(unDossier, unFtpItem.Name))); } } return(lesElements); }
public static void UploadFolder(FtpParameters parameters, string targetFolder, string sourceFolder) { using (var ftp = new Ftp()) { long currentPercentage = 0; ftp.Connect(parameters.Address, parameters.Port); ftp.Login(parameters.UserName, parameters.Password); ftp.Progress += (sender, args) => { if (currentPercentage < args.Percentage) { Logger.LogInfo("Uploaded {0} of {1} bytes {2}%", args.TotalBytesTransferred, args.TotalBytesToTransfer, args.Percentage); currentPercentage = args.Percentage; } }; if (!ftp.FolderExists(targetFolder)) { ftp.CreateFolder(targetFolder); } Logger.LogInfo("Uploading from {0} to {1}...", sourceFolder, targetFolder); ftp.UploadFiles(targetFolder, sourceFolder); Logger.LogInfo("Move from {0} to {1}...Complete", sourceFolder, targetFolder); } }
private async void FtpConnect_Click(object sender, RoutedEventArgs e) { var dialog = new FtpDialog(); dialog.ShowDialog(); if (dialog.Address == "") { return; } var client = new Ftp(); IPHostEntry host; try { host = await Dns.GetHostEntryAsync(dialog.Address); } catch (SocketException) { MessageBox.Show("Invalid address."); return; } client.ReceiveTimeout = TimeSpan.FromSeconds(5); client.SendTimeout = TimeSpan.FromSeconds(5); try { await Task.Run(() => client.Connect(host.AddressList[0], 21, false)); } catch (FtpException) { MessageBox.Show("FTP Server didn't respond."); return; } try { if (dialog.Password != "" && dialog.Login != "") { await Task.Run(() => client.Login(dialog.Login, dialog.Password)); } else { await Task.Run(() => client.LoginAnonymous()); } } catch (FtpResponseException) { MessageBox.Show("Invalid login or password."); return; } var root = new FtpFolder(new MyPath("/"), client); var disk = new Disk(root, Repo, new FtpFileManager(root, client)) { Header = dialog.Address }; DiskTabs.Items.Add(disk); }
private static void RunParser(object sender, ElapsedEventArgs e, ConfigHandler configHandler) { _parseTimer.Stop(); DirectoryInfo replayDirectory = new DirectoryInfo(_replayFileDirectory); DirectoryInfo sentDirectory = new DirectoryInfo(_sentReplayDirectory); if (!replayDirectory.GetFiles().Any()) { logger.Trace($"No replay files found in directory."); } else { Stopwatch sw = new Stopwatch(); sw.Start(); logger.Trace("-----------------------------------------"); using (Ftp client = new Ftp()) { client.Connect(_ftpAddr); client.Login(_ftpUserName, _ftpPassword); foreach (var file in replayDirectory.GetFiles()) { try { logger.Trace("Sending replay file to server: " + file.Name); client.Upload(file.Name, file.FullName); logger.Trace("Finished sending replay file: " + file.Name); MoveFile(sentDirectory, file); } catch (Exception ex) { logger.Error("Error occurred on sending the following replay file: " + file.Name + Environment.NewLine); logger.Trace(ex + Environment.NewLine); } } client.Close(); } sw.Stop(); logger.Trace($"Replay send complete [Elapsed: {sw.Elapsed.TotalSeconds} seconds]"); } _consoleClearCounter++; if (_consoleClearCounter >= CONSOLE_CLEAR_DISPLAY_LIMIT) { _consoleClearCounter = 0; Console.Clear(); } _parseTimer.Start(); }
public void Upload() { using (Ftp ftp = new Ftp()) { ftp.Connect("ftp.ciotems.com"); ftp.Login("collector", "Cete@712"); ftp.ChangeFolder("logs"); ftp.Upload("logs.txt", @"D:\桌面\新建文件夹\log.txt.2"); ftp.Close(); } }
public void CreerDossier(string leNmDossierACreer, ElementFolder leDossierDistant) { using (_monFtp = new Ftp()) { _monFtp.Connect(_maConfig.Host, _maConfig.Port); _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteChemin = MethodesGlobales.GetCheminServerSansRacinne(leDossierDistant.GetPath(), _maConfig.GetUriChaine()); _monFtp.ChangeFolder(resteChemin); _monFtp.CreateFolder(leNmDossierACreer); _monFtp.Close(); } }
public void UploadDossier(ElementFolder dossierLocal, ElementFolder dossierDistant) { using (_monFtp = new Ftp()) { _monFtp.Connect(_maConfig.Host, _maConfig.Port); _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteChemin = MethodesGlobales.GetCheminServerSansRacinne(dossierDistant.GetPath(), _maConfig.GetUriChaine()); _monFtp.CreateFolder(MethodesGlobales.GetCheminDossierUploadSurServeur(resteChemin, dossierLocal.GetName())); LocalSearchOptions uneLocalSearchOption = new LocalSearchOptions("*", true); _monFtp.UploadFiles(MethodesGlobales.GetCheminDossierUploadSurServeur(resteChemin, dossierLocal.GetName()), dossierLocal.GetPath(), uneLocalSearchOption); _monFtp.Close(); } }
/// <summary> /// Adds a file to FTP /// </summary> /// <param name="opts">The options</param> /// <returns>The result</returns> int FTPAddFile(FTPAddFileOptions opts) { using (Ftp ftp = new Ftp()) { try { ftp.Connect(Properties.Settings.Default.FTPServer); ftp.Login(Properties.Settings.Default.FTPUsername, CommandLineSecurity.ToInsecureString(CommandLineSecurity.DecryptString(Properties.Settings.Default.FTPPassword))); } catch (Exception ex) { MessageBox.Show(new Form(), ex.Message, "Mist of Time Publisher", MessageBoxButtons.OK, MessageBoxIcon.Error); return(1); } try { if (!ftp.FolderExists("cdn")) { ftp.CreateFolder("cdn"); } } catch (Exception ex) { MessageBox.Show(new Form(), ex.Message, "Mist of Time Publisher", MessageBoxButtons.OK, MessageBoxIcon.Error); return(1); } try { if (!opts.ServerPath.StartsWith("/")) { opts.ServerPath = "/" + opts.ServerPath; } ftp.Upload("cdn" + opts.ServerPath, opts.LocalPath); string oldPath = Path.GetDirectoryName("cdn" + opts.ServerPath).Replace('\\', '/') + "/FtpTrial-" + Path.GetFileName("cdn" + opts.ServerPath); if (ftp.FileExists(oldPath)) { ftp.Rename(oldPath, "cdn" + opts.ServerPath); } } catch (Exception) { return(2); } } return(0); }
public bool Download(ElementFolder remoteFolder, ElementFile remoteFile, ElementFolder localFolder) { using (_monFtp = new Ftp()) { _monFtp.Connect(_maConfig.Host, _maConfig.Port); // or ConnectSSL for SSL _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteCheminFolder = remoteFolder.GetPath().Replace(_maConfig.GetUriChaine(), "").Replace(@"\", "/"); string resteCheminFichier = remoteFile.GetPath().Replace(_maConfig.GetUriChaine(), "").Replace(@"\", "/"); _monFtp.ChangeFolder(resteCheminFolder); _monFtp.Download(remoteFile.GetName(), Path.Combine(localFolder.GetPath(), remoteFile.GetName())); _monFtp.Close(); } return(true); }
public void DownloadDossier(ElementFolder dossierDistant, ElementFolder dossierLocal) { using (_monFtp = new Ftp()) { _monFtp.Connect(_maConfig.Host, _maConfig.Port); _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteChemin = MethodesGlobales.GetCheminServerSansRacinne(dossierDistant.GetPath(), _maConfig.GetUriChaine()); string cheminDossierADowloaded = MethodesGlobales.GetCheminDossierLocalDownload(dossierLocal.GetPath(), dossierDistant.GetName()); Directory.CreateDirectory(cheminDossierADowloaded); _monFtp.DownloadFiles(resteChemin, cheminDossierADowloaded, new RemoteSearchOptions("*", true)); _monFtp.Close(); } }
/// <summary> /// Deletes a directory from FTP /// </summary> /// <param name="opts">The options</param> /// <returns>The result</returns> int FTPDeleteDirectory(FTPDeleteDirectoryOptions opts) { using (Ftp ftp = new Ftp()) { try { ftp.Connect(Properties.Settings.Default.FTPServer); ftp.Login(Properties.Settings.Default.FTPUsername, CommandLineSecurity.ToInsecureString(CommandLineSecurity.DecryptString(Properties.Settings.Default.FTPPassword))); } catch (Exception ex) { MessageBox.Show(new Form(), ex.Message, "Mist of Time Publisher", MessageBoxButtons.OK, MessageBoxIcon.Error); return(1); } try { if (!ftp.FolderExists("cdn")) { ftp.CreateFolder("cdn"); } } catch (Exception ex) { MessageBox.Show(new Form(), ex.Message, "Mist of Time Publisher", MessageBoxButtons.OK, MessageBoxIcon.Error); return(1); } try { if (!opts.ServerPath.StartsWith("/")) { opts.ServerPath = "/" + opts.ServerPath; } ftp.DeleteFolder("cdn" + opts.ServerPath); } catch (Exception) { return(2); } } return(0); }
private static string _logFolder = "myLogs"; //Folder with logs on FTP server public static void Send(MemoryStream ms) { try// { Console.WriteLine("Start loading log on FTP."); byte[] bt = ms.GetBuffer(); FileStream fs = new FileStream("", FileMode.Create); fs.Write(bt, 0, bt.Length); Ftp ftp = new Ftp(); ftp.Connect(_ipAddress); ftp.Login(_login, _password); ftp.ChangeFolder(_logFolder); ftp.UploadUnique(ms); ftp.UploadUnique(bt); } catch { } }
public bool Upload(ElementFolder localFolder, ElementFile localFile, ElementFolder distantFolder) { FtpResponse maReponseFtp; using (_monFtp = new Ftp()) { _monFtp.Connect(_maConfig.Host, _maConfig.Port); _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteChemin = distantFolder.GetPath().Replace(_maConfig.GetUriChaine(), "").Replace(@"\", "/"); if (!string.IsNullOrEmpty(resteChemin)) { _monFtp.ChangeFolder(resteChemin); } maReponseFtp = _monFtp.Upload(localFile.GetName(), localFile.GetPath()); _monFtp.Close(); } return(true); }
private void FTPConnect(Ftp ftp) { //Limilabs.FTP.Log.Enabled = true; ftp.Connect(this.HostIP); log.Info(string.Format("Connected to FTP [{0}]", this.HostIP)); try { ftp.Login(this.UserName, this.Pass); log.Info(string.Format("Loggedin using [{0}] [{1}]", this.UserName, this.Pass)); } catch { ftp.LoginAnonymous(); log.Info("Login Anonymous"); } if (!string.IsNullOrEmpty(this.FolderPath)) { ftp.ChangeFolder(this.FolderPath); } }
void OnConnectFinish(IAsyncResult asyncResult) { try { _ftp.EndConnect(asyncResult); ConnectForm dlg = (ConnectForm)asyncResult.AsyncState; if (!_ftp.IsAuthenticated) { _ftp.Login(dlg.UserName, dlg.Password); } _rootServerDir = _ftp.GetCurrentDirectory(); tbxServerFolder.Text = _rootServerDir; PopulateServerList(_rootServerDir); SetConnectedState(true); if (dlg.SslMode == SslMode.None) { lblServerType.Text = "FTP"; } else { lblServerType.Text = "FTP " + dlg.SslMode; } } catch (Exception ex) { Log(ex); SetConnectedState(false); return; } }
public List <ITransfer> ListFolder(string cheminFTPDossier) { List <FtpItem> lesFtpElements = new List <FtpItem>(); List <ITransfer> lesElements = new List <ITransfer>(); //StatusCommand lesStatuts = new StatusCommand(EStatusCommand); using (_monFtp = new Ftp()) { VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeConnexion)); try { _monFtp.Connect(_maConfig.Host, _maConfig.Port); // or ConnectSSL for SSL VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.AReussieAjoindreHote)); } catch (Exception) { VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.ImpossibleDAtteindreServeurFtp)); } VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeAuthentification)); try { _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.AuthentificationReussie)); } catch (FtpResponseException e) { VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.AuthentificationReussie)); } string resteChemin = cheminFTPDossier.Replace(_maConfig.GetUriChaine(), "").Replace(@"\", "/"); if (resteChemin.Equals("")) { VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.RepertoireInexistant)); VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.RepertoireParDefautDefini)); VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeListDossier)); VariablesGlobales._leLog.LogCustom(string.Format("Demande de la liste des dossiers de : {0}", _maConfig.GetUriChaine()), true); lesFtpElements = _monFtp.GetList(); VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.ListeTrouvee)); } else { List <string> larbo = resteChemin.Split(new char[] { '/' }).ToList(); VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeChangementRepertoire)); if (larbo.Count > 0) { _monFtp.ChangeFolder(resteChemin); } else { _monFtp.ChangeFolder(resteChemin); } VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.ChangementRepertoireEffectue)); VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeListDossier)); VariablesGlobales._leLog.LogCustom(string.Format("Demande de la liste des dossiers de : {0}", resteChemin), true); lesFtpElements = _monFtp.GetList(); VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.ListeTrouvee)); } VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeFermetureFluxEchange)); _monFtp.Close(); VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.FermetureDuFluxReussie)); } VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.GenerationElementTransferables)); foreach (FtpItem unFtpItem in lesFtpElements) { if (unFtpItem.IsFolder) { lesElements.Add(new ElementFolder(unFtpItem, Path.Combine(cheminFTPDossier, unFtpItem.Name))); } } return(lesElements); }
protected override void OnCreate(Bundle savedInstanceState) { _context = this; //first check if there are permsions to access files ext bool checks = true; #region << Check For Permisions >> // Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) || ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) || Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.Internet) if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.Internet) != (int)Permission.Granted) { if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.Internet)) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.Internet, Manifest.Permission.Internet }, 1); // })).Show(); } while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.Internet) != (int)Permission.Granted) { Thread.Sleep(100); } } if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) != (int)Permission.Granted) { if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessWifiState)) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessWifiState, Manifest.Permission.AccessWifiState }, 1); // })).Show(); } while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) != (int)Permission.Granted) { Thread.Sleep(100); } } if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessNetworkState) != (int)Permission.Granted) { if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessNetworkState)) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessNetworkState, Manifest.Permission.AccessNetworkState }, 1); // })).Show(); } while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessNetworkState) != (int)Permission.Granted) { Thread.Sleep(100); } } if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted) { // Camera permission has not been granted RequestReadWirtePermission(); while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted) { Thread.Sleep(100); } } #endregion << Check For Permisions >> base.OnCreate(savedInstanceState); //request the app to be full screen RequestWindowFeature(WindowFeatures.NoTitle); this.Window.ClearFlags(Android.Views.WindowManagerFlags.Fullscreen); //to hide Rebex.Licensing.Key = "==AnKxIZnJ2NXyRRk/MrXLh5vsLbImP/JhMGERReY23qIk=="; SetContentView(Resource.Layout.installer); refreshui(); retrieveset(); LoadPkg.Click += async delegate { try { String[] types = new String[] { ".pkg" }; FileData fileData = await CrossFilePicker.Current.PickFile(types); if (fileData == null) { return; // user canceled file picking } //com.android.externalstorage.documents System.Console.WriteLine("File name " + fileData.FileName); new Thread(new ThreadStart(delegate { RunOnUiThread(() => { progress = new ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetMessage("Loading... Getting Path..."); progress.SetCancelable(false); progress.Show(); }); FindFileByName(fileData.FileName); System.Console.WriteLine("Found File, Path= " + PKGLocation); RunOnUiThread(() => { progress.Hide(); try { var pkgfile = PS4_Tools.PKG.SceneRelated.Read_PKG(PKGLocation); ImageView pbPkg = FindViewById <ImageView>(Resource.Id.PKGIcon); pbPkg.SetImageBitmap(BytesToBitmap(pkgfile.Icon)); TextView lblPackageInfo = FindViewById <TextView>(Resource.Id.txtPKGInfo); lblPackageInfo.Text = pkgfile.PS4_Title + "\n" + pkgfile.PKG_Type.ToString() + "\n" + pkgfile.Param.TitleID; } catch (Exception ex) { MessageBox.Show("Invaild Package! or Path\n\n Location: " + PKGLocation); // MessageBox.Show("Exception choosing file: " + ex.ToString() + " " + PKGLocation); } }); })).Start(); } catch (Exception ex) { MessageBox.Show("Invaild Package! or Path\n\n Location: " + PKGLocation); // MessageBox.Show("Exception choosing file: " + ex.ToString() + " " + PKGLocation); } }; set.Click += async delegate { try { PKGLocation = manpath.Text; var pkgfile = PS4_Tools.PKG.SceneRelated.Read_PKG(PKGLocation); ImageView pbPkg = FindViewById <ImageView>(Resource.Id.PKGIcon); pbPkg.SetImageBitmap(BytesToBitmap(pkgfile.Icon)); TextView lblPackageInfo = FindViewById <TextView>(Resource.Id.txtPKGInfo); lblPackageInfo.Text = pkgfile.PS4_Title + "\n" + pkgfile.PKG_Type.ToString() + "\n" + pkgfile.Param.TitleID; } catch (Exception ex) { MessageBox.Show("Invaild Package! or Path\n\n Location: " + PKGLocation); // MessageBox.Show("Exception choosing file: " + ex.ToString() + " " + PKGLocation); } }; SendPayloadBtn.Click += delegate { new Thread(new ThreadStart(delegate { using (Ftp client = new Ftp()) { Rebex.Licensing.Key = "==AnKxIZnJ2NXyRRk/MrXLh5vsLbImP/JhMGERReY23qIk=="; try { // TextView IPAddressTextBox = FindViewById<TextView>(Resource.Id.IPAddressTextBox); if (IPAddressTextBox.Text == "") { RunOnUiThread(() => { MessageBox.Show("Enter an IP Address"); }); return; } saveset(); // string paths = GetPathToImage("sa"); // connect and login to the FTP client.Connect(IPAddressTextBox.Text); //TextView FTPPassword = FindViewById<TextView>(Resource.Id.FTPPassword); //TextView FTPUsername = FindViewById<TextView>(Resource.Id.FTPUsername); if (FTPPassword.Text == "" && FTPUsername.Text == "") { client.Login("anonymous", "DONT-LOOK@MYCODE"); } else { client.Login(FTPUsername.Text, FTPPassword.Text); } client.Traversing += Traversing; client.TransferProgressChanged += TransferProgressChanged; client.DeleteProgressChanged += DeleteProgressChanged; client.ProblemDetected += ProblemDetected; if (!client.DirectoryExists(@"/user/app/")) { client.CreateDirectory(@"/user/app/"); } if (client.FileExists(@"/user/app/temp.pkg")) { client.Delete(@"/user/app/temp.pkg", TraversalMode.NonRecursive); } client.ChangeDirectory(@"/user/app/"); client.PutFile(PKGLocation, "temp.pkg"); try { client.SendCommand("installpkg"); } catch (Exception ex) { SetTex("installpkg Failed\n Are you sure your using Inifinx?"); } SetTex("Package Sent"); } catch (Exception ex) { RunOnUiThread(() => { MessageBox.Show(ex.Message); }); } RunOnUiThread(() => { Toast.MakeText(Application.Context, "Package Sent!", ToastLength.Short).Show(); }); client.Disconnect(); } })).Start(); }; /* } * else * { * SendPayloadBtn.Visibility = ViewStates.Invisible; * LoadPkg.Visibility = ViewStates.Invisible; * }*/ }
public FtpClient(string host, string user, string password, int port) { _ftp = new Ftp(); _ftp.ConnectSSL(host, port); _ftp.Login(user, password); }
protected override void OnCreate(Bundle savedInstanceState) { //first check if there are permsions to access files ext bool checks = true; _context = this; #region << Check For Permisions >> // Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) || ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) || Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.Internet) if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.Internet) != (int)Permission.Granted) { if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.Internet)) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.Internet, Manifest.Permission.Internet }, 1); // })).Show(); } while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.Internet) != (int)Permission.Granted) { Thread.Sleep(100); } } if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) != (int)Permission.Granted) { if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessWifiState)) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessWifiState, Manifest.Permission.AccessWifiState }, 1); // })).Show(); } while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) != (int)Permission.Granted) { Thread.Sleep(100); } } if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessNetworkState) != (int)Permission.Granted) { if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessNetworkState)) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessNetworkState, Manifest.Permission.AccessNetworkState }, 1); // })).Show(); } while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessNetworkState) != (int)Permission.Granted) { Thread.Sleep(100); } } if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted) { // Camera permission has not been granted RequestReadWirtePermission(); while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted) { Thread.Sleep(100); } } #endregion << Check For Permisions >> base.OnCreate(savedInstanceState); //request the app to be full screen RequestWindowFeature(WindowFeatures.NoTitle); this.Window.ClearFlags(Android.Views.WindowManagerFlags.Fullscreen); //to hide Rebex.Licensing.Key = "==AnKxIZnJ2NXyRRk/MrXLh5vsLbImP/JhMGERReY23qIk=="; SetContentView(Resource.Layout.plugin); refreshui(); retrieveset(); SendPayloadBtn.Click += delegate { new Thread(new ThreadStart(delegate { using (Ftp client = new Ftp()) { Rebex.Licensing.Key = "==AnKxIZnJ2NXyRRk/MrXLh5vsLbImP/JhMGERReY23qIk=="; try { // TextView IPAddressTextBox = FindViewById<TextView>(Resource.Id.IPAddressTextBox); if (IPAddressTextBox.Text == "") { RunOnUiThread(() => { MessageBox.Show("Enter an IP Address"); }); return; } saveset(); // connect and login to the FTP client.Connect(IPAddressTextBox.Text); //TextView FTPPassword = FindViewById<TextView>(Resource.Id.FTPPassword); //TextView FTPUsername = FindViewById<TextView>(Resource.Id.FTPUsername); if (FTPPassword.Text == "" && FTPUsername.Text == "") { client.Login("anonymous", "DONT-LOOK@MYCODE"); } else { client.Login(FTPUsername.Text, FTPPassword.Text); } client.Traversing += Traversing; client.TransferProgressChanged += TransferProgressChanged; client.DeleteProgressChanged += DeleteProgressChanged; client.ProblemDetected += ProblemDetected; string path = System.IO.Path.Combine(ApplicationContext.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath + @"/PayloadPlugin.prx"); // RunOnUiThread(() => { MessageBox.Show(path); }); bool exists = System.IO.Directory.Exists(System.IO.Path.Combine(ApplicationContext.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath)); if (!exists) { System.IO.Directory.CreateDirectory(System.IO.Path.Combine(ApplicationContext.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath)); } System.Console.WriteLine(path); SetTex("Downloading Plugin from DKS"); using (var clients = new WebClient()) { if (System.IO.Directory.Exists(path)) { System.IO.File.Delete(path); } clients.DownloadFile("https://psarchive.darksoftware.xyz/PayloadPlugin.prx", path); } if (!client.DirectoryExists(@"/user/app/")) { client.CreateDirectory(@"/user/app/"); } if (client.FileExists(@"/user/app/PayloadPlugin.prx")) { client.Delete(@"/user/app/PayloadPlugin.prx", TraversalMode.NonRecursive); } client.ChangeDirectory(@"/user/app/"); client.PutFile(path, @"PayloadPlugin.prx"); SetTex("Plugin Installed Successfully"); } catch (Exception ex) { RunOnUiThread(() => { MessageBox.Show(ex.Message); }); } RunOnUiThread(() => { Toast.MakeText(Application.Context, "Installed!", ToastLength.Short).Show(); }); client.Disconnect(); } })).Start(); }; /* } * else * { * SendPayloadBtn.Visibility = ViewStates.Invisible; * LoadPkg.Visibility = ViewStates.Invisible; * }*/ }
static void Main(string[] args) { if (args != null && args.Length > 0) { try { _operationId = Convert.ToInt32(args[0]); } catch { _operationId = 0; } if (args.Length == 2) { try { _action = Convert.ToString(args[1]); } catch { _action = ""; } } } // TODO: Add code to start application here // Testing -------------- //string svcPath; //string svcName; //string svcDispName; //path to the service that you want to install //const string SERVICE_PATH = @"D:\GitProjects\MagicUpdater\MagicUpdater\bin\Release\MagicUpdater.exe"; const string SERVICE_PATH = @"C:\SystemUtils\MagicUpdater\MagicUpdater.exe"; const string SERVICE_DISPLAY_NAME = "MagicUpdater"; const string SERVICE_NAME = "MagicUpdater"; const string MAGIC_UPDATER_PATH = @"C:\SystemUtils\MagicUpdater"; const string MAGIC_UPDATER_NEW_VER_PATH = @"C:\SystemUtils\MagicUpdaterNewVer"; const string SETTINGS_FILE_NAME = "settings.json"; ServiceInstaller serviceInstaller = new ServiceInstaller(); ServiceController service = new ServiceController(SERVICE_NAME); try { if (string.IsNullOrEmpty(_action)) { TimeSpan timeout = TimeSpan.FromMilliseconds(30000); Console.WriteLine("Тормозим старую службу..."); //Тормозим старую службу try { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); AddMessage($"Старая служба {SERVICE_NAME} - остановлена"); NLogger.LogDebugToHdd($"Старая служба {SERVICE_NAME} - остановлена"); Console.WriteLine("Старая служба остановлена"); } catch (Exception ex) { AddMessage(ex.Message); NLogger.LogDebugToHdd(ex.Message); Console.WriteLine(ex.Message); } Console.WriteLine("Удаляем старую службу..."); //Удаляем старую службу try { serviceInstaller.UnInstallService(SERVICE_NAME); Thread.Sleep(3000); NLogger.LogDebugToHdd($"Старая служба {SERVICE_NAME} - удалена"); AddMessage($"Старая служба {SERVICE_NAME} - удалена"); Console.WriteLine($"Старая служба {SERVICE_NAME} - удалена"); } catch (Exception ex) { AddMessage(ex.Message); NLogger.LogDebugToHdd(ex.Message); Console.WriteLine(ex.Message); } Console.WriteLine("Убиваем все процессы MagicUpdater..."); //Убиваем все процессы MagicUpdater Process[] procs = Process.GetProcessesByName(SERVICE_NAME); foreach (var proc in procs) { proc.Kill(); } Thread.Sleep(3000); NLogger.LogDebugToHdd($"Все процессы {SERVICE_NAME} - убиты"); AddMessage($"Все процессы {SERVICE_NAME} - убиты"); Console.WriteLine("Все процессы MagicUpdater завершены"); Console.WriteLine("Чистим реестр (автозагрузка MU как приложения в корне run)..."); //Чистим реестр (автозагрузка MU как приложения в корне run) #region Чистим реестр string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run"; using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true)) { if (key == null) { Console.WriteLine($"CurrentUser: Отсутствует путь в реестре {keyName}"); NLogger.LogErrorToHdd($"CurrentUser: Отсутствует путь в реестре {keyName}"); AddMessage($"CurrentUser: Отсутствует путь в реестре {keyName}"); } else { try { key.DeleteValue(SERVICE_NAME); Console.WriteLine($"CurrentUser: Значение реестра - {SERVICE_NAME} удалено"); NLogger.LogDebugToHdd($"CurrentUser: Значение реестра - {SERVICE_NAME} удалено"); AddMessage($"CurrentUser: Значение реестра - {SERVICE_NAME} удалено"); } catch (Exception ex) { NLogger.LogDebugToHdd($"CurrentUser: {ex.Message}"); Console.WriteLine($"CurrentUser: {ex.Message}"); AddMessage($"CurrentUser: {ex.Message}"); } } } using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName, true)) { if (key == null) { NLogger.LogErrorToHdd($"LocalMachine: Отсутствует путь в реестре {keyName}"); AddMessage($"LocalMachine: Отсутствует путь в реестре {keyName}"); } else { try { key.DeleteValue(SERVICE_NAME); Console.WriteLine($"LocalMachine: Значение реестра - {SERVICE_NAME} удалено"); NLogger.LogDebugToHdd($"LocalMachine: Значение реестра - {SERVICE_NAME} удалено"); AddMessage($"LocalMachine: Значение реестра - {SERVICE_NAME} удалено"); } catch (Exception ex) { Console.WriteLine($"LocalMachine: {ex.Message}"); NLogger.LogDebugToHdd($"LocalMachine: {ex.Message}"); AddMessage($"LocalMachine: {ex.Message}"); } } } #endregion Чистим реестр Console.WriteLine("Удаляем все из папок MagicUpdater и MagicUpdaterNewVer..."); //Удаляем все из папок MagicUpdater и MagicUpdaterNewVer #region Удаляем все из папок MagicUpdater и MagicUpdaterNewVer try { DirectoryInfo di = new DirectoryInfo(MAGIC_UPDATER_PATH); foreach (FileInfo file in di.GetFiles()) { if (file.Name.ToUpper() != SETTINGS_FILE_NAME.ToUpper()) { file.Delete(); } } foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); } Console.WriteLine($"Путь {MAGIC_UPDATER_PATH} - очищен"); NLogger.LogDebugToHdd($"Путь {MAGIC_UPDATER_PATH} - очищен"); AddMessage($"Путь {MAGIC_UPDATER_PATH} - очищен"); } catch (Exception ex) { Console.WriteLine(ex.Message); NLogger.LogErrorToHdd(ex.ToString()); AddMessage(ex.Message); } try { DirectoryInfo di = new DirectoryInfo(MAGIC_UPDATER_NEW_VER_PATH); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); } Console.WriteLine($"Путь {MAGIC_UPDATER_NEW_VER_PATH} - очищен"); NLogger.LogDebugToHdd($"Путь {MAGIC_UPDATER_NEW_VER_PATH} - очищен"); AddMessage($"Путь {MAGIC_UPDATER_NEW_VER_PATH} - очищен"); } catch (Exception ex) { Console.WriteLine(ex.Message); NLogger.LogErrorToHdd(ex.ToString()); AddMessage(ex.Message); } #endregion Удаляем все из папок MagicUpdater и MagicUpdaterNewVer Thread.Sleep(1000); Console.WriteLine("Скачиваем новую версию..."); //Копируем новый MagicUpdater целиком! #region Копируем новый MagicUpdater целиком! using (Ftp ftp = new Ftp()) { ftp.Connect("mskftp.sela.ru"); // or ConnectSSL for SSL ftp.Login("cis_obmen", "cisobmen836"); try { Directory.CreateDirectory(MAGIC_UPDATER_PATH); ftp.DownloadFiles("MagicUpdaterTest", MAGIC_UPDATER_PATH, new RemoteSearchOptions("*", true)); } finally { if (ftp.Connected) { ftp.Close(); } } } Console.WriteLine($"Закачка нового {SERVICE_NAME} - завешена"); NLogger.LogDebugToHdd($"Закачка нового {SERVICE_NAME} - завешена"); AddMessage($"Закачка нового {SERVICE_NAME} - завешена"); #endregion Копируем новый MagicUpdater целиком! //Устанавливаем службу с режимом автозапуска //Запускаем службу Thread.Sleep(3000); Console.WriteLine("Создаем задачу MuInstallService в планировщике для установки службы..."); NLogger.LogDebugToHdd("Создаем задачу MuInstallService в планировщике для установки службы..."); try { CreateMuInstallServiceSchedule("MuInstallService"); Console.WriteLine("Задача MuInstallService создана"); NLogger.LogDebugToHdd("Задача MuInstallService создана"); } catch (Exception ex) { Console.WriteLine($"Задача MuInstallService: {ex.Message}"); NLogger.LogErrorToHdd($"Задача MuInstallService: {ex.ToString()}"); } //string path = System.Reflection.Assembly.GetEntryAssembly().Location; //Process.Start(path, $"{_operationId.ToString()} restart"); } else if (_action == "restart") { serviceInstaller.InstallService(SERVICE_PATH, SERVICE_NAME, SERVICE_DISPLAY_NAME); Console.WriteLine($"Новая служба {SERVICE_NAME} - установлена и запущена"); NLogger.LogDebugToHdd($"Новая служба {SERVICE_NAME} - установлена и запущена"); AddMessage($"Новая служба {SERVICE_NAME} - установлена и запущена"); //serviceInstaller.UnInstallService(SERVICE_NAME); SendMessagesToOperation(true); DeleteSchedule("MuInstallService"); } else if (_action == "schedule") { CreateMuInstallServiceSchedule("MuInstallService"); } } catch (Exception ex) { Console.WriteLine(ex.Message); NLogger.LogErrorToHdd(ex.ToString()); AddMessage(ex.Message); SendMessagesToOperation(false); } //Console.Read(); }
public bool Process( string uploadPath, ConnectionSettings connection) { var processLog = new StringBuilder(); var uploadGroupPath = Path.Combine(uploadPath, _webLocationFolderName); if (!Directory.Exists(uploadGroupPath)) { Directory.CreateDirectory(uploadGroupPath); } var uploadSitePath = Path.Combine(uploadGroupPath, Path.GetFileName(_sourcePath)); var currentFolder = _sourcePath; bool completedSuccessFully; try { processLog.AppendLine(String.Format("iSpring tune process started at folder {0}", _sourcePath)); var webContentPath = Path.Combine(_sourcePath, WebContentFolderName); var convertedFolderName = (WebContentFolderName.Replace(" ", " ") .Replace(" ", " ") .Replace(" ", "_") .Replace("(", "") .Replace(")", "") + _id) .ToLower(); var destinationFolderPath = Path.Combine(_sourcePath, convertedFolderName); if (!String.Equals(webContentPath, destinationFolderPath, StringComparison.OrdinalIgnoreCase)) { try { Directory.Move(webContentPath, destinationFolderPath); } catch (Exception ex) { throw new UnauthorizedAccessException(String.Format("Error while change folder name with {0}{1}{2}", convertedFolderName, ex.Message, Environment.NewLine)); } } processLog.AppendLine(String.Format("Folder name changed with {0}", convertedFolderName)); var dataFolderPath = Path.Combine(destinationFolderPath, DataFolderName); if (!Directory.Exists(dataFolderPath)) { throw new FileNotFoundException(String.Format("Site Data folder {0} not found", dataFolderPath)); } File.WriteAllText(Path.Combine(dataFolderPath, JqueryFileName), Properties.Resources.JQueryFileContent); processLog.AppendLine(String.Format("File added {0}", JqueryFileName)); File.WriteAllText(Path.Combine(dataFolderPath, JsonFileName), Properties.Resources.JSonFileContent); processLog.AppendLine(String.Format("File added {0}", JsonFileName)); File.WriteAllText(Path.Combine(dataFolderPath, MetroNotificationScriptFileName), Properties.Resources.MetroNotificationScriptFileContent); processLog.AppendLine(String.Format("File added {0}", MetroNotificationScriptFileName)); File.WriteAllText(Path.Combine(dataFolderPath, MetroNotificationStyleFileName), Properties.Resources.MetroNotificationStyleFileContent); processLog.AppendLine(String.Format("File added {0}", MetroNotificationStyleFileName)); File.WriteAllText(Path.Combine(dataFolderPath, FontAwesomeStyleFileName), Properties.Resources.FontAwesomeStyleContent); processLog.AppendLine(String.Format("File added {0}", FontAwesomeStyleFileName)); var activityRegularFileContent = Properties.Resources.ActivityRegularFileContent; activityRegularFileContent = activityRegularFileContent.Replace(SitePathPlaceHolder, connection.Url); activityRegularFileContent = activityRegularFileContent.Replace(EmailPlaceHolder, String.Join(";", _emails)); activityRegularFileContent = activityRegularFileContent.Replace(AdvertiserPlaceHolder, _advertiserName.Replace("'", @"\'")); File.WriteAllText(Path.Combine(dataFolderPath, ActivityRegularFileName), activityRegularFileContent); processLog.AppendLine(String.Format("File added {0}", ActivityRegularFileName)); var activityLoginFileContent = Properties.Resources.ActivityLoginFileContent; activityLoginFileContent = activityLoginFileContent.Replace(AdvertiserPlaceHolder, _advertiserName.Replace("'", @"\'")); activityLoginFileContent = activityLoginFileContent.Replace(FileNamePlaceHolder, String.Format("{0}.pptx", Name)); File.WriteAllText(Path.Combine(dataFolderPath, ActivityLoginFileName), activityLoginFileContent); processLog.AppendLine(String.Format("File added {0}", ActivityLoginFileName)); File.WriteAllText(Path.Combine(destinationFolderPath, LoginIndexFileName), Properties.Resources.LoginIndexFileContent); processLog.AppendLine(String.Format("File added {0}", LoginIndexFileName)); var originalIndexFilePath = Path.Combine(destinationFolderPath, OriginalIndexFileName); var publicIndexFilePath = Path.Combine(destinationFolderPath, PublicIndexFileName); if (!File.Exists(originalIndexFilePath)) { throw new FileNotFoundException(String.Format("Site Index file not found")); } var indexFileContent = File.ReadAllText(originalIndexFilePath); File.Delete(originalIndexFilePath); var originalHeadContent = String.Empty; var matches = Regex.Matches(indexFileContent, @"<head>([.\S+\n\r\s]*?)<\/head>"); if (matches.Count > 0 && matches[0].Groups.Count > 1) { originalHeadContent = matches[0].Groups[1].Value; } if (!String.IsNullOrEmpty(originalHeadContent)) { if (!originalHeadContent.Contains(Properties.Resources.PublicIndexScriptIncludePart)) { var modifiedHeadContent = String.Format("{0}{2}{1}", originalHeadContent, Properties.Resources.PublicIndexScriptIncludePart, Environment.NewLine); File.WriteAllText(publicIndexFilePath, indexFileContent.Replace(originalHeadContent, modifiedHeadContent)); } } processLog.AppendLine("Web Folder html file new code added"); Directory.Move(_sourcePath, uploadSitePath); currentFolder = uploadSitePath; processLog.AppendLine(String.Format("CWL PACK Moved to Upload folder ({0})", uploadSitePath)); using (var ftp = new Ftp()) { ftp.Connect(connection.FtpUrl); ftp.Login(connection.Login, connection.Password); ftp.ChangeFolder(FtpRootFolder); ftp.CreateFolder(_webLocationFolderName); ftp.ChangeFolder(_webLocationFolderName); ftp.CreateFolder(convertedFolderName); ftp.UploadFiles(convertedFolderName, Path.Combine(uploadSitePath, convertedFolderName)); ftp.Close(); } processLog.AppendLine("Web Folder uploaded with web services to clientweblink.com"); OutlookHelper.Instance.SendMessage( String.Format("HTML5 presentation ready for {0}", _advertiserName), String.Format("Your HTML5 Web Link is ready for: {0}{3}{3}" + "Public URL{3}{1}{3}{3}" + "Client Login URL{3}{2}{3}{3}" + "*Please Note:{3}You will receive a confirmation email each time someone views this presentation.{3}{3}{3}" + "If you have any technical issues with your HTML5 web link, then email:{3}[email protected]", _advertiserName, String.Format("{0}/{1}/{2}/{3}/{4}", connection.Url, SiteRootFolder, _webLocationFolderName, convertedFolderName, PublicIndexFileName), String.Format("{0}/{1}/{2}/{3}/{4}", connection.Url, SiteRootFolder, _webLocationFolderName, convertedFolderName, LoginIndexFileName), Environment.NewLine), _emails); processLog.AppendLine(String.Format("Confirmation email with URL sent to {0}", String.Join(";", _emails))); processLog.AppendLine("iSpring tune process completed successfully"); completedSuccessFully = true; } catch (Exception ex) { processLog.AppendLine("iSpring tune process completed unsuccessfully"); processLog.AppendLine(ex.Message); processLog.AppendLine(ex.StackTrace); completedSuccessFully = false; } finally { var logFilePath = Path.Combine(currentFolder, LogFileName); File.WriteAllText(logFilePath, processLog.ToString()); } return(completedSuccessFully); }
public string GetFileFromFTP(string host, int port, string remoteFolderPath, string localFolderPath, string username, string password, List<string> userCodesList, string fileName) { //host="83.12.64.6"; //port = 12024; //username = "******"; //password="******"; //remoteFolderPath = "Test2"; //localFolderPath = @"C:\"; //remoteFolderPath = ""; //userCodesList = new List<string>(); //userCodesList.Add("PL0091"); try { using (Ftp client = new Ftp()) { client.Connect(host, port); // or ConnectSSL for SSL client.Login(username, password); client.ChangeFolder(remoteFolderPath); string filePath = localFolderPath + "\\" + fileName; if (!File.Exists(filePath)) { byte[] bytes = client.Download(fileName); MemoryStream stream = new MemoryStream(bytes); XElement xelement = XElement.Load(stream);//XElement.Parse(xelementString); xelement.Save(filePath); } client.Close(); } } catch(Exception ex) { return "error-"+ex.Message; } return "ok";//+ " plików dla kodów "+codesString; }
public List<string> GetFilesNamesFromFTP(string host, int port, string remoteFolderPath, string localFolderPath, string username, string password, List<string> userCodesList) { //host="83.12.64.6"; //port = 12024; //username = "******"; //password="******"; //remoteFolderPath = "Test2"; //localFolderPath = @"C:\"; //remoteFolderPath = ""; //userCodesList = new List<string>(); //userCodesList.Add("PL0091"); List<string> filesList = new List<string>(); try { using (Ftp client = new Ftp()) { client.Connect(host, port); // or ConnectSSL for SSL client.Login(username, password); //client.Download(@"reports\report.txt", @"c:\report.txt"); //client.DownloadFiles(remoteFolderPath, localFolderPath); //RemoteSearchOptions option = new RemoteSearchOptions("*.xml", true); //client.DeleteFiles(remoteFolderPath, option); //client.DeleteFolder(remoteFolderPath); //client.CreateFolder(remoteFolderPath); //byte[] bytes = client.Download(@"reports/report.txt"); //string report = Encoding.UTF8.GetString(bytes,0,bytes.Length); client.ChangeFolder(remoteFolderPath); List<FtpItem> items = client.GetList(); foreach (FtpItem item in items) { if (item.IsFile) { filesList.Add(item.Name); /* string filePath = localFolderPath + "\\" + item.Name; currentFileName = item.Name; if (!File.Exists(filePath)) { byte[] bytes = client.Download(item.Name); //string xelementString = Encoding.UTF8.GetString(bytes,0,bytes.Length); //xelementString = getRidOfUnprintablesAndUnicode(xelementString); MemoryStream stream = new MemoryStream(bytes); XElement xelement = XElement.Load(stream);//XElement.Parse(xelementString); xelement.Save(filePath); downloadedFilesCount++; } var sender = (from nm in xelement.Elements("Sender") select nm).FirstOrDefault(); string code = sender.Element("Code").Value; code = userCodesList.Where(c=>c==code).FirstOrDefault(); if (code != null) { xelement.Save(localFolderPath + "\\" + item.Name,); client.DeleteFile(item.Name); downloadedFilesCount++; } */ } } client.Close(); } } catch (Exception ex) { return new List<string> { "error-"+ex.Message}; } return filesList; }
public void Copy() { using (Ftp client = new Ftp()) { client.Connect("172.18.200.251"); client.Login("x25bejn", "bejn90"); var list = client.GetList("/user/BEJNUP/SURF/ST_DAY/"); List <string> citycodes = CityUtility.AllCodeList(); List <FtpItem> totalList = new List <FtpItem>(); foreach (string citycode in citycodes) { totalList.AddRange(list.Where(a => a.Name.Contains(citycode)).ToList()); } int fileSuccessCount = 0; File_Z_BLL bll = new File_Z_BLL(); foreach (FtpItem ftpItem in totalList) { string romoteName = @"user\BEJNUP\SURF\ST_DAY\" + ftpItem.Name; string month = ftpItem.Name.Substring(15, 6); string localPath = @"D:\市县一体化平台文档\检验\日z文件\" + month; if (!Directory.Exists(localPath)) { Directory.CreateDirectory(localPath); } string localName = localPath + @"\" + ftpItem.Name; try { client.Download(romoteName, localName); fileSuccessCount++; Console.WriteLine("成功复制:" + ftpItem.Name); ///存取数据库 string name = ftpItem.Name; string content = File.ReadAllText(localName); string[] contentLine = File.ReadAllLines(localName); string countrycode = contentLine[0].Substring(0, 5); string countryname = CityUtility.GetName(countrycode); DateTime date = DateTime.ParseExact(contentLine[1].Split(' ').ToList().ElementAt(0).Substring(0, 8), "yyyyMMdd", CultureInfo.InvariantCulture); string rain1_string = contentLine[1].Split(' ').ToList().ElementAt(1); string rain2_string = contentLine[1].Split(' ').ToList().ElementAt(2); decimal rain1 = 0; decimal rain2 = 0; if (rain1_string == ",,,,,") { rain1 = (decimal)0.01; } else { rain1 = decimal.Parse(rain1_string) / 10; } if (rain2_string == ",,,,,") { rain2 = (decimal)0.01; } else { rain2 = decimal.Parse(rain2_string) / 10; } File_Z model = bll.Get(a => a.Date == date && a.CountryCode == countrycode); if (model != null) { model.Twenty_Eight = rain1; model.Eight_Twenty = rain2; model.FileContent = content; model.FileName = name; model.CreateTime = DateTime.Now; bll.Update(model); } else { model = new File_Z() { FileID = Guid.NewGuid(), CountryCode = countrycode, CountryName = countryname, CreateTime = DateTime.Now, Date = date, Twenty_Eight = rain1, Eight_Twenty = rain2, FileContent = content, FileName = name }; bll.Add(model); } Console.WriteLine("成功入库:" + ftpItem.Name); } catch (Exception ex) { Console.WriteLine(ex); } } Console.WriteLine("成功复制:" + fileSuccessCount + "个文件,共有:" + totalList.Count() + "个文件。"); } }
private static void Main(string[] args) { string llo = "LampLightOnlineSharp"; var pre = Directory.GetCurrentDirectory() + @"\..\..\..\..\..\..\"; /* var projs = new[] { llo+@"\LampLightOnlineClient\", llo+@"\LampLightOnlineServer\", }; foreach (var proj in projs) { #if DEBUG var from = pre + proj + @"\bin\debug\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; #else var from = pre + proj + @"\bin\release\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; #endif var to = pre + llo + @"\output\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; if (File.Exists(to)) File.Delete(to); File.Copy(from, to); } */ //client happens in buildsite.cs var depends = new Dictionary<string, Application> { /*{ llo+@"\Servers\AdminServer\", new Application(true, "new AdminServer.AdminServer();", new List<string> { @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }*/ { "MM.ChatServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./ServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }, { "MM.GameServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./MMServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./CommonClientLibraries.js", @"./MMServer.js", @"./Games/ZombieGame/ZombieGame.Common.js", @"./Games/ZombieGame/ZombieGame.Server.js", @"./Models.js", @"./RawDeflate.js", }) {} }, { "MM.GatewayServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./ServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./MMServerAPI.js", @"./MMServer.js", @"./Games/ZombieGame/ZombieGame.Common.js", @"./Games/ZombieGame/ZombieGame.Server.js", @"./Models.js", }) }, { "MM.HeadServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./ServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }, { "SiteServer", new Application(true, new List<string> { @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }, {"Client", new Application(false, new List<string> {})}, {"CommonWebLibraries", new Application(false, new List<string> {})}, {"CommonLibraries", new Application(false, new List<string> {})}, {"CommonClientLibraries", new Application(false, new List<string> {})}, {"CommonServerLibraries", new Application(false, new List<string> {})}, {"MMServer", new Application(false, new List<string> {})}, {"MMServerAPI", new Application(false, new List<string> {})}, {"ClientAPI", new Application(false, new List<string> {})}, {"ServerAPI", new Application(false, new List<string> {})}, {"CommonAPI", new Application(false, new List<string> {})}, }; #if FTP string loc = ConfigurationSettings.AppSettings["web-ftpdir"]; Console.WriteLine("connecting ftp"); Ftp webftp = new Ftp(); webftp.Connect(ConfigurationSettings.AppSettings["web-ftpurl"]); webftp.Login(ConfigurationSettings.AppSettings["web-ftpusername"], ConfigurationSettings.AppSettings["web-ftppassword"]); Console.WriteLine("connected"); webftp.Progress += (e, c) => { var left = Console.CursorLeft; var top = Console.CursorTop; Console.SetCursorPosition(65, 5); Console.Write("|"); for (int i = 0; i < c.Percentage / 10; i++) { Console.Write("="); } for (int i = (int) ( c.Percentage / 10 ); i < 10; i++) { Console.Write("-"); } Console.Write("|"); Console.Write(c.Percentage + " % "); Console.WriteLine(); Console.SetCursorPosition(left, top); }; string serverloc = ConfigurationSettings.AppSettings["server-ftpdir"]; string serverloc2 = ConfigurationSettings.AppSettings["server-web-ftpdir"]; Console.WriteLine("connecting server ftp"); SftpClient client = new SftpClient(ConfigurationSettings.AppSettings["server-ftpurl"], ConfigurationSettings.AppSettings["server-ftpusername"], ConfigurationSettings.AppSettings["server-ftppassword"]); client.Connect(); Console.WriteLine("server connected"); #endif foreach (var depend in depends) { var to = pre + "\\" + llo + @"\output\" + depend.Key + ".js"; var output = ""; if (depend.Value.Node) output += "require('./mscorlib.debug.js');\r\n"; else { //output += "require('./mscorlib.debug.js');"; } foreach (var depe in depend.Value.IncludesAfter) { output += string.Format("require('{0}');\r\n", depe); } if (depend.Value.Postpend != null) output += depend.Value.Postpend + "\r\n"; var lines = new List<string>(); lines.Add(output); lines.AddRange(File.ReadAllLines(to).After(1)); //mscorlib string text = lines.Aggregate("", (a, b) => a + b + "\n"); File.WriteAllText(to, text); // lines.Add(depend.Value.After); var name = to.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries).Last(); // File.WriteAllText(to, text); #if FTP long length = new FileInfo(to).Length; if (!webftp.FileExists(loc + name) || webftp.GetFileSize(loc + name) != length) { Console.WriteLine("ftp start " + length.ToString("N0")); webftp.Upload(loc + name, to); Console.WriteLine("ftp complete " + to); } if (!client.Exists(serverloc + name) || client.GetAttributes(serverloc + name).Size != length) { Console.WriteLine("server ftp start " + length.ToString("N0")); var fileStream = new FileInfo(to).OpenRead(); client.UploadFile(fileStream, serverloc + name, true); fileStream.Close(); Console.WriteLine("server ftp complete " + to); } if (!client.Exists(serverloc2 + name) || client.GetAttributes(serverloc2 + name).Size != length) { Console.WriteLine("server ftp start " + length.ToString("N0")); var fileStream = new FileInfo(to).OpenRead(); client.UploadFile(fileStream, serverloc2 + name, true); fileStream.Close(); Console.WriteLine("server ftp complete " + to); } #endif } string[] games = {"ZombieGame" /*, "TowerD", "ZakGame" */}; foreach (var depend in games) { var to = pre + llo + @"\output\Games\" + depend + @"\"; string[] exts = {"Client", "Common", "Server"}; foreach (var ext in exts) { // lines.Add(depend.Value.After); string fm = to + depend + "." + ext + ".js"; string text = File.ReadAllText(fm); File.WriteAllText(fm, text); #if FTP Console.WriteLine("ftp start " + text.Length.ToString("N0")); webftp.Upload(loc + "Games/" + depend + "/" + depend + "." + ext + ".js", fm); Console.WriteLine("ftp complete " + fm); Console.WriteLine("server ftp start " + text.Length.ToString("N0")); var fileStream = new FileInfo(fm).OpenRead(); client.UploadFile(fileStream, serverloc + "Games/" + depend + "/" + depend + "." + ext + ".js", true); fileStream.Close(); fileStream = new FileInfo(fm).OpenRead(); client.UploadFile(fileStream, serverloc2 + "Games/" + depend + "/" + depend + "." + ext + ".js", true); fileStream.Close(); Console.WriteLine("server ftp complete " + fm); #endif } } }