Beispiel #1
0
        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;
            }
        }
Beispiel #2
0
        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();
            }
        }
Beispiel #3
0
        /// <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);
            }
        }
Beispiel #4
0
        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);
            }
        }
Beispiel #5
0
        public bool VerificarClave(string clave)
        {
            bool ret = false;

            clave += ".txt";

            Ftp FtpClient = new Ftp();

            FtpClient.HostAddress = Main.FTPHost;
            FtpClient.Port        = Main.FTPPort;
            FtpClient.Username    = Main.FTPName;
            FtpClient.Password    = Main.FTPPass;
            FtpClient.Timeout     = Main.FTPTimeOut;
            FtpClient.Connect();

            System.IO.FileInfo fi = new System.IO.FileInfo(System.Windows.Forms.Application.ExecutablePath);

            FtpClient.GetFile(clave, fi.Directory.ToString() + @"\" + clave); //fi.Directory.ToString())

            if (FtpClient.GetLastError == null)
            {
                FtpClient.Rename(clave, "OK_" + clave);
                ret = true;
            }
            FtpClient.Quit();

            if (ret)
            {
                Licenses.Instance.Activated = true;
            }

            return(ret);
        }
Beispiel #6
0
        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);
        }
Beispiel #7
0
        /// <summary>
        /// Ping le serveur
        /// </summary>
        /// <returns>Retourne l'état du serveur</returns>
        public override bool Ping()
        {
            Console.WriteLine("Connexion au serveur " + this.ServerType + "...");

            try
            {
                using (Ftp ftp = new Ftp())     // Initialisation de l'objet du FTP
                {
                    ftp.Connect(this.ServerIP); // Connection au FTP sans login

                    if (ftp.Connected)
                    {
                        ftp.Close();
                        return(true);
                    }
                    else
                    {
                        ftp.Close();
                        return(false);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
        }
        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();
            }
        }
        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);
        }
        public override void Remove()
        {
            Ftp ftp = new Ftp();

            ftp.Connect(FtpTargetPath);
            ftp.SetCredential(FtpUserName, FtpPassword);
            ftp.RemoveDirectoryRecursivelyAsync("./", false).Wait();
        }
Beispiel #11
0
        private Ftp CreateFtp()
        {
            var ftp = new Ftp();

            ftp.Connect("ftp://waws-prod-ch1-001.ftp.azurewebsites.windows.net");
            ftp.SetCredential(@"webstacktest01\hongyes", "Password01!");

            return(ftp);
        }
Beispiel #12
0
 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();
     }
 }
Beispiel #13
0
        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();
        }
Beispiel #14
0
 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();
     }
 }
Beispiel #15
0
 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();
     }
 }
        protected override void DeployCore(IDirectory source)
        {
            Ftp ftp = new Ftp();

            ftp.Connect(FtpTargetPath);
            ftp.SetCredential(FtpUserName, FtpPassword);

            if (CleanTargetDirectory)
            {
                ftp.RemoveDirectoryRecursivelyAsync("./", false).Wait();
            }

            ftp.UploadDirectoryRecursivelyAsync("./", source).Wait();
        }
        /// <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);
        }
Beispiel #18
0
 public void Init()
 {
     openFtpTask = Task.Create(p =>
     {
         ftp = new Ftp("10.10.65.77", "root", "123456");
         try
         {
             ftp.Connect();
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.StackTrace);
         }
     });
 }
Beispiel #19
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);
        }
Beispiel #20
0
        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);
        }
Beispiel #22
0
        public bool IsValidLicense()
        {
            if (!lastLicenseCheck.HasValue || lastLicenseCheck.Value.AddMonths(1) < DateTime.Today)
            {
                EmpresasBL empBL = new EmpresasBL();
                empBL.SetParameters(db);
                ComprobantesBL compBL = new ComprobantesBL();
                compBL.SetParameters(db);

                Empresas empresa = empBL.GetObject(GeneralSettings.Instance.IdEmpresaDefault) as Empresas;
                if (empresa != null)
                {
                    Ftp FtpClient = new Ftp();
                    FtpClient.HostAddress = FTPHost;
                    FtpClient.Port        = FTPPort;
                    FtpClient.Username    = FTPName;
                    FtpClient.Password    = FTPPass;
                    FtpClient.Timeout     = FTPTimeOut;
                    FtpClient.Connect();

                    string fileName = empresa.Cuit;

                    FtpClient.MoveDirectory("Licencias");
                    FtpItemCollection fic = new FtpItemCollection();
                    FtpClient.FileList(ref fic);
                    foreach (FtpItem item in fic)
                    {
                        if (item.Name.ToLower() == fileName.ToLower())
                        {
                            lastLicenseCheck = DateTime.Today;
                            return(true);
                        }
                    }
                    FtpClient.Quit();
                }

                return(false);
            }
            else
            {
                return(true);
            }
        }
Beispiel #23
0
        public void EnvioFTP()
        {
            EmpresasBL empBL = new EmpresasBL();

            empBL.SetParameters(db);
            ComprobantesBL compBL = new ComprobantesBL();

            compBL.SetParameters(db);

            Empresas empresa = empBL.GetObject(GeneralSettings.Instance.IdEmpresaDefault) as Empresas;

            if (empresa != null)
            {
                Ftp FtpClient = new Ftp();
                FtpClient.HostAddress = FTPHost;
                FtpClient.Port        = FTPPort;
                FtpClient.Username    = FTPName;
                FtpClient.Password    = FTPPass;
                FtpClient.Timeout     = FTPTimeOut;
                FtpClient.Connect();

                string       fileName = empresa.Cuit + "_" + DateTime.Now.ToString("yyyyMMdd_hhmm") + ".txt";
                StreamWriter tw       = File.CreateText(fileName);

                FtpClient.MoveDirectory(empresa.Cuit);
                int cantidadEmitidos = 0;
                foreach (Comprobantes comp in compBL.GetDataSource())
                {
                    if (comp.IsEmitido)
                    {
                        tw.Write(compBL.GetResumeStream(comp));
                        cantidadEmitidos++;
                    }
                }
                tw.Write("Cantidad de facturas emitidas: " + cantidadEmitidos.ToString() + "\r\n");
                tw.Close();

                FtpClient.PutFile(fileName);
                FtpClient.Quit();

                File.Delete(fileName);
            }
        }
Beispiel #24
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
            { }
        }
Beispiel #25
0
        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);
        }
Beispiel #26
0
        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);
            }
        }
        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;
        }
        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 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;
        }
Beispiel #30
0
        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;
             * }*/
        }
Beispiel #31
0
        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() + "个文件。");
            }
        }
Beispiel #32
0
        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();
        }
Beispiel #33
0
        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
                }
            }
        }