Example #1
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);
            }
        }
Example #2
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);
            }
        }
Example #3
0
        public void DownloadFile(string InFileName, string InLocalDestinationPath)
        {
            Check.Require(!string.IsNullOrEmpty(InFileName));
            Check.Require(!string.IsNullOrEmpty(InLocalDestinationPath));

            Ftp ftp = null;

            try
            {
                using (ftp = new Ftp())
                {
                    this.FTPConnect(ftp);

                    var remoteFilePath = Path.Combine(this.FolderPath, InFileName);
                    log.Info(string.Format("Downloading from [{0}] to [{1}]", remoteFilePath, InLocalDestinationPath));
                    ftp.Download(InFileName, InLocalDestinationPath);
                }
            }
            catch (Exception ex)
            {
                log.Error((string.Format("Failed downloading file [{0}] to [{1}]", InFileName, InLocalDestinationPath)), ex);
                throw ex;
            }
            finally
            {
                if (ftp != null)
                {
                    ftp.Close();
                }
            }
        }
Example #4
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();
            }
        }
Example #5
0
        public void DownloadFiles(List <string> InFileNames, string InLocalDestinationFolderPath, bool InToDeleteOriginal)
        {
            Check.Require(InFileNames != null);
            Check.Require(!string.IsNullOrEmpty(InLocalDestinationFolderPath));

            Ftp ftp = null;

            try
            {
                using (ftp = new Ftp())
                {
                    this.FTPConnect(ftp);

                    foreach (var fileName in InFileNames)
                    {
                        try
                        {
                            var destinationFileNameFull = Path.Combine(InLocalDestinationFolderPath, fileName);
                            var remoteFilePath          = Path.Combine(this.FolderPath, fileName);

                            log.Info(string.Format("Downloading from [{0}] to [{1}]", remoteFilePath, destinationFileNameFull));

                            if (File.Exists(destinationFileNameFull)) //Clear the temp folder from previous attempts
                            {
                                File.Delete(destinationFileNameFull);
                            }

                            ftp.Download(fileName, destinationFileNameFull);
                            Check.Ensure(File.Exists(destinationFileNameFull), string.Format("File [{0}] should exist in [{1}]", fileName, InLocalDestinationFolderPath));

                            //Delete the original file if the file was copied to destination
                            if (InToDeleteOriginal)
                            {
                                try
                                {
                                    log.Info(string.Format("Deleting from [{0}]", remoteFilePath));
                                    ftp.DeleteFile(fileName);
                                }
                                catch (Exception ex)
                                {
                                    log.Error((string.Format("Failed deleting file [{0}]", remoteFilePath)), ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Error((string.Format("Failed downloading file [{0}] to [{1}]", fileName, InLocalDestinationFolderPath)), ex);
                            throw ex;
                        }
                    }
                }
            }
            finally
            {
                if (ftp != null)
                {
                    ftp.Close();
                }
            }
        }
Example #6
0
        public List <string> ListDirectory()
        {
            Ftp ftp = null;

            try
            {
                using (ftp = new Ftp())
                {
                    this.FTPConnect(ftp);

                    var list = ftp.GetList().ConvertAll <string>(s => s.Name);

                    log.Info(string.Format("Found in directory listing [{0}]", list.Count));
                    list.ForEach(l => log.Info(l + ';'));

                    return(list);
                }
            }
            catch (Exception ex)
            {
                log.Error((string.Format("Failed accessing FTP [{0}]", this.HostIP)), ex);
                throw ex;
            }
            finally
            {
                if (ftp != null)
                {
                    ftp.Close();
                }
            }
        }
Example #7
0
        /********************************************** Constructor, Load & Closing ************************************************/

        public FTPClient()
        {
            m_Settings = new Settings();
            m_Settings.Reload();

            try
            {
                m_Ftp             = new Ftp();
                m_Ftp.Server      = m_Settings.FTPServer;
                m_Ftp.UserName    = m_Settings.FTPUser;
                m_Ftp.Password    = m_Settings.FTPPass;
                m_Ftp.Port        = Convert.ToInt32(m_Settings.FTPPort);
                m_Ftp.PassiveMode = true;

                m_Ftp.Open();

                if (m_Ftp.Active)
                {
                    m_OK = true;

                    m_Ftp.ChangeCurrentDir(@"/httpdocs/Places");
                    m_Ftp.PutFile("places.sqlite", File.OpenRead(m_Settings.PlacesFile));

                    m_Ftp.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Example #8
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);
        }
Example #9
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();
     }
 }
Example #10
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();
        }
Example #11
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();
     }
 }
Example #12
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();
     }
 }
Example #13
0
        public void Destroy()
        {
            if (ftp != null && ftp.Connected)
            {
                try
                {
                    ftp.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                }

                ftp = null;
            }
        }
Example #14
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);
        }
Example #15
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();
            }
        }
Example #16
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);
        }
        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;
        }
Example #19
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();
        }
        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);
        }
Example #21
0
        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);
        }