Exemplo n.º 1
0
        public void LoadIgnoreTree()
        {
            Stopwatch.Restart();

            try
            {
                m_ignoreTree = Utilities.XmlDeserializeObject <Tree <RemoteFileInfo> >(IgnoreCache);
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }

            if (m_ignoreTree == null)
            {
                LOG.WarnFormat("Ignore tree at {0} is not available", IgnoreCache);
            }

            if (PrintTrees)
            {
                PrintIgnoreChildren();
            }
            else
            {
                int numberOfFiles = Tree <RemoteFileInfo> .GetNumberOfChildren(m_ignoreTree, 0);

                LOG.DebugFormat("Loaded {0} ignored files", numberOfFiles);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// A simply rijndael aes decryption, can be used to store passwords
        /// </summary>
        /// <param name="EncryptedText">a base64 encoded rijndael encrypted string</param>
        /// <returns>Decrypeted text</returns>
        public static string Decrypt(this string EncryptedText)
        {
            string returnValue = EncryptedText;

            try
            {
                byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);
                using (MemoryStream ms = new MemoryStream())
                {
                    SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

                    byte[] rgbIV = Encoding.ASCII.GetBytes(RGBIV);
                    byte[] key   = Encoding.ASCII.GetBytes(KEY);

                    using (CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write))
                    {
                        cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);
                        cs.FlushFinalBlock();
                        returnValue = Encoding.ASCII.GetString(ms.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                LOG.ErrorFormat("Error decrypting {0}, error: ", EncryptedText, ex.Message);
            }

            return(returnValue);
        }
Exemplo n.º 3
0
        public int OpenSession(string _remoteRoot, string _localPath, string _ignoreCache)
        {
            RemoteRoot  = _remoteRoot;
            IgnoreCache = _ignoreCache;
            LocalPath   = _localPath;

            m_sessionInfo = new SessionInfo();
            m_sessionInfo.Load();

            try
            {
                m_session = new Session();
                m_session.ExecutablePath = "../../../External/winscp573automation/WinSCP.exe";
                m_session.Open(m_sessionInfo.SessionOptions);

                LOG.DebugFormat("Opened session at {0} with default settings", m_sessionInfo.SessionOptions.HostName);

                return(0);
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
                return(1);
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Retrieves the cursor location safely, accounting for DPI settings in Vista/Windows 7.
 /// </summary>
 /// <returns>Point with cursor location, relative to the origin of the monitor setup
 /// (i.e. negative coordinates arepossible in multiscreen setups)</returns>
 public static Point GetCursorLocation()
 {
     if (Environment.OSVersion.Version.Major >= 6 && _CanCallGetPhysicalCursorPos)
     {
         POINT cursorLocation;
         try
         {
             if (GetPhysicalCursorPos(out cursorLocation))
             {
                 return(new Point(cursorLocation.X, cursorLocation.Y));
             }
             else
             {
                 Win32Error error = Win32.GetLastErrorCode();
                 LOG.ErrorFormat("Error retrieving PhysicalCursorPos : {0}", Win32.GetMessage(error));
             }
         }
         catch (Exception ex)
         {
             LOG.Error("Exception retrieving PhysicalCursorPos, no longer calling this. Cause :", ex);
             _CanCallGetPhysicalCursorPos = false;
         }
     }
     return(new Point(Cursor.Position.X, Cursor.Position.Y));
 }
        /// <summary>
        /// A simply rijndael aes encryption, can be used to store passwords
        /// </summary>
        /// <param name="ClearText">the string to call upon</param>
        /// <returns>an encryped string in base64 form</returns>
        public static string Encrypt(this string ClearText)
        {
            string returnValue = ClearText;

            try
            {
                byte[]             clearTextBytes = Encoding.ASCII.GetBytes(ClearText);
                SymmetricAlgorithm rijn           = SymmetricAlgorithm.Create();

                using (MemoryStream ms = new MemoryStream())
                {
                    byte[]       rgbIV = Encoding.ASCII.GetBytes(RGBIV);
                    byte[]       key   = Encoding.ASCII.GetBytes(KEY);
                    CryptoStream cs    = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);

                    cs.Write(clearTextBytes, 0, clearTextBytes.Length);

                    cs.Close();
                    returnValue = Convert.ToBase64String(ms.ToArray());
                }
            }
            catch (Exception ex)
            {
                LOG.ErrorFormat("Error encrypting, error: ", ex.Message);
            }
            return(returnValue);
        }
Exemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="webRequest"></param>
        /// <returns></returns>
        public static string GetResponseAsString(HttpWebRequest webRequest, bool alsoReturnContentOnError)
        {
            string          responseData = null;
            HttpWebResponse response     = null;
            bool            isHttpError  = false;

            try
            {
                response = (HttpWebResponse)webRequest.GetResponse();
                LOG.InfoFormat("Response status: {0}", response.StatusCode);
                isHttpError = (int)response.StatusCode >= 300;
                if (isHttpError)
                {
                    LOG.ErrorFormat("HTTP error {0}", response.StatusCode);
                }
                DebugHeaders(response);
                responseData = GetResponseAsString(response);
                if (isHttpError)
                {
                    LOG.ErrorFormat("HTTP response {0}", responseData);
                }
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;
                HttpStatusCode statusCode = HttpStatusCode.Unused;
                if (response != null)
                {
                    statusCode = response.StatusCode;
                    LOG.ErrorFormat("HTTP error {0}", statusCode);
                    string errorContent = GetResponseAsString(response);
                    if (alsoReturnContentOnError)
                    {
                        return(errorContent);
                    }
                    LOG.ErrorFormat("Content: {0}", errorContent);
                }
                LOG.Error("WebException: ", e);
                if (statusCode == HttpStatusCode.Unauthorized)
                {
                    throw new UnauthorizedAccessException(e.Message);
                }
                throw;
            }
            finally
            {
                if (response != null)
                {
                    if (isHttpError)
                    {
                        LOG.ErrorFormat("HTTP error {0} with content: {1}", response.StatusCode, responseData);
                    }
                    response.Close();
                }
            }
            return(responseData);
        }
Exemplo n.º 7
0
        public void SaveIgnoreTree()
        {
            LOG.DebugFormat("Saving ignore tree to {0}", IgnoreCache);

            try
            {
                Utilities.XmlSerializeObject <Tree <RemoteFileInfo> >(m_ignoreTree, IgnoreCache);
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Load the files for the specified ietf
        /// </summary>
        /// <param name="ietf"></param>
        private static void LoadFiles(string ietf)
        {
            ietf = ReformatIETF(ietf);
            if (!languageFiles.ContainsKey(ietf))
            {
                LOG.ErrorFormat("No language {0} available.", ietf);
                return;
            }
            List <LanguageFile> filesToLoad = languageFiles[ietf];

            foreach (LanguageFile fileToLoad in filesToLoad)
            {
                LoadResources(fileToLoad);
            }
        }
Exemplo n.º 9
0
        public void PrintIgnoreTree()
        {
            LOG.Debug("Listing ignored files...");

            try
            {
                Tree <RemoteFileInfo> .PrintTree(m_ignoreTree, 0);
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }

            int numberOfFiles = Tree <RemoteFileInfo> .GetNumberOfChildren(m_ignoreTree, 0);

            LOG.DebugFormat("Loaded {0} ignored files", numberOfFiles);
        }
Exemplo n.º 10
0
        public void PrintRemoteTree()
        {
            LOG.Debug("Listing remote tree...");

            try
            {
                Tree <RemoteFileInfo> .PrintTree(m_remoteTree, 0);
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }

            int numberOfFiles = Tree <RemoteFileInfo> .GetNumberOfChildren(m_remoteTree, 0);

            LOG.DebugFormat("Refreshed {0} remote files", numberOfFiles);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Retrieves the cursor location safely, accounting for DPI settings in Vista/Windows 7.
 /// <returns>Point with cursor location, relative to the origin of the monitor setup (i.e. negative coordinates are
 /// possible in multiscreen setups)</returns>
 public static Point GetCursorLocation()
 {
     if (Environment.OSVersion.Version.Major >= 6)
     {
         POINT cursorLocation;
         if (User32.GetPhysicalCursorPos(out cursorLocation))
         {
             return(new Point(cursorLocation.X, cursorLocation.Y));
         }
         else
         {
             Win32Error error = Win32.GetLastErrorCode();
             LOG.ErrorFormat("Error retrieving PhysicalCursorPos : {0}", Win32.GetMessage(error));
         }
     }
     return(new Point(Cursor.Position.X, Cursor.Position.Y));
 }
Exemplo n.º 12
0
 public void Load()
 {
     try
     {
         // Setup session options
         SessionOptions = new SessionOptions
         {
             Protocol = Protocol.Ftp,
             HostName = "ns513998.dediseedbox.com",
             UserName = "******",
             Password = "******",
         };
     }
     catch (Exception e)
     {
         LOG.ErrorFormat("Error: {0}", e);
     }
 }
Exemplo n.º 13
0
        private void Update(string _path, Tree <RemoteFileInfo> _tree)
        {
            try
            {
                RemoteDirectoryInfo directory = m_session.ListDirectory(_path);

                foreach (WinSCP.RemoteFileInfo fileInfo in directory.Files)
                {
                    if (fileInfo.Name != "..")
                    {
                        if (fileInfo.IsDirectory)
                        {
                            //if the entry not cached - add the directory and then update its contents
                            if (Tree <RemoteFileInfo> .Find(m_ignoreTree, i => i.Name == fileInfo.Name && i.IsDirectory) == null)
                            {
                                _tree.AddChild(new RemoteFileInfo(fileInfo));

                                Update(_path + "/" + fileInfo.Name, _tree.GetChild(_tree.Children.Count - 1));
                            }
                        }
                        else
                        {
                            //if we are not ignoring the file
                            if (Tree <RemoteFileInfo> .Find(m_ignoreTree, i => i.Name == fileInfo.Name && !i.IsDirectory) == null)
                            {
                                //if the file extension is one we care about add it to list, other wise add to the ignore list
                                //if (!m_ignoredExtensions.Contains(Utilities.GetExtensionFromFileName(fileInfo.Name)))
                                {
                                    _tree.AddChild(new RemoteFileInfo(fileInfo));
                                }
                                //else
                                //{
                                //    m_ignoreTree.AddChild(new RemoteFileInfo2(fileInfo));
                                //}
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }
        }
Exemplo n.º 14
0
        public void PrintIgnoreChildren()
        {
            LOG.Debug("Listing ignore files...");

            try
            {
                if (m_ignoreTree.Children.Count > 0)
                {
                    Tree <RemoteFileInfo> .PrintTreeChildren(m_ignoreTree, RemoteRoot);
                }
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }

            int numberOfFiles = Tree <RemoteFileInfo> .GetNumberOfChildren(m_ignoreTree, 0);

            numberOfFiles = (numberOfFiles == 1) ? 0 : numberOfFiles;

            LOG.DebugFormat("Loaded {0} ignore files", numberOfFiles);
        }
Exemplo n.º 15
0
        public void PrintRemoteChildren()
        {
            LOG.Debug("Listing remote files...");

            try
            {
                if (m_remoteTree.Children.Count > 0)
                {
                    Tree <RemoteFileInfo> .PrintTreeChildren(m_remoteTree, "");
                }
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }

            int numberOfFiles = Tree <RemoteFileInfo> .GetNumberOfChildren(m_remoteTree, 0);

            numberOfFiles = (numberOfFiles == 1) ? 0 : numberOfFiles;

            LOG.DebugFormat("Refreshed {0} remote files", numberOfFiles);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Scan the files in all directories
        /// </summary>
        private static void ScanFiles()
        {
            languageFiles.Clear();
            helpFiles.Clear();
            foreach (string languagePath in languagePaths)
            {
                if (!Directory.Exists(languagePath))
                {
                    LOG.InfoFormat("Skipping non existing language path {0}", languagePath);
                    continue;
                }
                LOG.InfoFormat("Searching language directory '{0}' for language files with pattern '{1}'", languagePath, LANGUAGE_FILENAME_PATTERN);
                try
                {
                    foreach (string languageFilepath in Directory.GetFiles(languagePath, LANGUAGE_FILENAME_PATTERN, SearchOption.AllDirectories))
                    {
                        //LOG.DebugFormat("Found language file: {0}", languageFilepath);
                        LanguageFile languageFile = LoadFileInfo(languageFilepath);
                        if (languageFile == null)
                        {
                            continue;
                        }
                        if (string.IsNullOrEmpty(languageFile.Ietf))
                        {
                            LOG.WarnFormat("Fixing missing ietf in language-file {0}", languageFilepath);
                            string languageFilename = Path.GetFileName(languageFilepath);
                            if (IETF_REGEXP.IsMatch(languageFilename))
                            {
                                string replacementIETF = IETF_REGEXP.Replace(languageFilename, "$1");
                                languageFile.Ietf = ReformatIETF(replacementIETF);
                                LOG.InfoFormat("Fixed IETF to {0}", languageFile.Ietf);
                            }
                            else
                            {
                                LOG.ErrorFormat("Missing ietf , no recover possible... skipping language-file {0}!", languageFilepath);
                                continue;
                            }
                        }

                        // Check if we can display the file
                        if (!string.IsNullOrEmpty(languageFile.LanguageGroup) && unsupportedLanguageGroups.Contains(languageFile.LanguageGroup))
                        {
                            LOG.InfoFormat("Skipping unsuported (not able to display) language {0} from file {1}", languageFile.Description, languageFilepath);
                            continue;
                        }

                        // build prefix, based on the filename, but only if it's not set in the file itself.
                        if (string.IsNullOrEmpty(languageFile.Prefix))
                        {
                            string languageFilename = Path.GetFileNameWithoutExtension(languageFilepath);
                            if (PREFIX_REGEXP.IsMatch(languageFilename))
                            {
                                languageFile.Prefix = PREFIX_REGEXP.Replace(languageFilename, "$1");
                                if (!string.IsNullOrEmpty(languageFile.Prefix))
                                {
                                    languageFile.Prefix = languageFile.Prefix.Replace("plugin", "").ToLower();
                                }
                            }
                        }
                        List <LanguageFile> currentFiles = null;
                        if (languageFiles.ContainsKey(languageFile.Ietf))
                        {
                            currentFiles = languageFiles[languageFile.Ietf];
                            bool needToAdd = true;
                            List <LanguageFile> deleteList = new List <LanguageFile>();
                            foreach (LanguageFile compareWithLangfile in currentFiles)
                            {
                                if ((languageFile.Prefix == null && compareWithLangfile.Prefix == null) || (languageFile.Prefix != null && languageFile.Prefix.Equals(compareWithLangfile.Prefix)))
                                {
                                    if (compareWithLangfile.Version > languageFile.Version)
                                    {
                                        LOG.WarnFormat("Skipping {0}:{1}:{2} as {3}:{4}:{5} is newer", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version);
                                        needToAdd = false;
                                        break;
                                    }
                                    else
                                    {
                                        LOG.WarnFormat("Found {0}:{1}:{2} and deleting {3}:{4}:{5}", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version);
                                        deleteList.Add(compareWithLangfile);
                                    }
                                }
                            }
                            if (needToAdd)
                            {
                                foreach (LanguageFile deleteFile in deleteList)
                                {
                                    currentFiles.Remove(deleteFile);
                                }
                                LOG.InfoFormat("Added language {0} from: {1}", languageFile.Description, languageFile.Filepath);
                                currentFiles.Add(languageFile);
                            }
                        }
                        else
                        {
                            currentFiles = new List <LanguageFile>();
                            currentFiles.Add(languageFile);
                            languageFiles.Add(languageFile.Ietf, currentFiles);
                            LOG.InfoFormat("Added language {0} from: {1}", languageFile.Description, languageFile.Filepath);
                        }
                    }
                }
                catch (DirectoryNotFoundException)
                {
                    LOG.InfoFormat("Non existing language directory: {0}", languagePath);
                }
                catch (Exception e)
                {
                    LOG.Error("Error trying for read directory " + languagePath, e);
                }

                // Now find the help files
                LOG.InfoFormat("Searching language directory '{0}' for help files with pattern '{1}'", languagePath, HELP_FILENAME_PATTERN);
                try
                {
                    foreach (string helpFilepath in Directory.GetFiles(languagePath, HELP_FILENAME_PATTERN, SearchOption.AllDirectories))
                    {
                        LOG.DebugFormat("Found help file: {0}", helpFilepath);
                        string helpFilename = Path.GetFileName(helpFilepath);
                        string ietf         = ReformatIETF(helpFilename.Replace(".html", "").Replace("help-", ""));
                        if (!helpFiles.ContainsKey(ietf))
                        {
                            helpFiles.Add(ietf, helpFilepath);
                        }
                        else
                        {
                            LOG.WarnFormat("skipping help file {0}, already a file with the same IETF {1} found!", helpFilepath, ietf);
                        }
                    }
                }
                catch (DirectoryNotFoundException)
                {
                    LOG.InfoFormat("Non existing language directory: {0}", languagePath);
                }
                catch (Exception e)
                {
                    LOG.Error("Error trying for read directory " + languagePath, e);
                }
            }
        }
Exemplo n.º 17
0
        public void Sync(Tree <RemoteFileInfo> _tree, Tree <RemoteFileInfo> _tempIgnoreTree, string _remotePath, string _localPath, bool _remove = false, TransferOptions _transformOptions = null)
        {
            try
            {
                if (_tree.Children.Count != 0)
                {
                    for (int i = 0; i < _tree.Children.Count; i++)
                    {
                        if (_tree.Children[i] != null)
                        {
                            if (_tree.Children[i].Children != null)
                            {
                                string data = _tree.Children[i].Data.ToString();

                                if (data == null)
                                {
                                    data = string.Empty;
                                }

                                Tree <RemoteFileInfo> node = _tree.Children[i];
                                _tempIgnoreTree.AddNode(node);

                                Console.WriteLine("AT -> {0}", node.Data);

                                Sync(_tree.Children[i], _tempIgnoreTree.Children[_tempIgnoreTree.Children.Count - 1], _remotePath + "/" + data, _localPath, _remove, _transformOptions);
                            }
                        }
                    }
                }
                else
                {
                    if (_tree.Data != null)
                    {
                        string data = _tree.Data.ToString();
                        if (data != null)
                        {
                            string source = _remotePath + "/" + data;
                            if (!TestMode)
                            {
                                GetFiles(source, _localPath, _remove, _transformOptions);
                            }
                            else
                            {
                                //Console.WriteLine("Syncing {0} to {1}", source, _localPath);
                            }

                            Console.WriteLine("-------------DUMP--------------");
                            Tree <RemoteFileInfo> .PrintTree(_tempIgnoreTree, 0);

                            Console.WriteLine("--------------END--------------");

                            m_ignoreTree.AddNode(Tree <RemoteFileInfo> .Clone(_tempIgnoreTree));

                            _tempIgnoreTree = null;
                            _tempIgnoreTree = new Tree <RemoteFileInfo>();

                            m_syncedFiles++;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Write the passed Image to a tmp-file and call an external process, than read the file back and write it to the targetStream
        /// </summary>
        /// <param name="imageToProcess">Image to pass to the external process</param>
        /// <param name="targetStream">stream to write the processed image to</param>
        /// <returns></returns>
        private static bool ProcessPNGImageExternally(Image imageToProcess, Stream targetStream)
        {
            if (string.IsNullOrEmpty(conf.OptimizePNGCommand))
            {
                return(false);
            }
            if (!File.Exists(conf.OptimizePNGCommand))
            {
                LOG.WarnFormat("Can't find 'OptimizePNGCommand' {0}", conf.OptimizePNGCommand);
                return(false);
            }
            string tmpFileName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".png");

            try
            {
                using (FileStream tmpStream = File.Create(tmpFileName))
                {
                    LOG.DebugFormat("Writing png to tmp file: {0}", tmpFileName);
                    imageToProcess.Save(tmpStream, ImageFormat.Png);
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.DebugFormat("File size before processing {0}", new FileInfo(tmpFileName).Length);
                    }
                }
                if (LOG.IsDebugEnabled)
                {
                    LOG.DebugFormat("Starting : {0}", conf.OptimizePNGCommand);
                }

                ProcessStartInfo processStartInfo = new ProcessStartInfo(conf.OptimizePNGCommand);
                processStartInfo.Arguments              = string.Format(conf.OptimizePNGCommandArguments, tmpFileName);
                processStartInfo.CreateNoWindow         = true;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.RedirectStandardError  = true;
                processStartInfo.UseShellExecute        = false;
                using (Process process = Process.Start(processStartInfo))
                {
                    if (process != null)
                    {
                        process.WaitForExit();
                        if (process.ExitCode == 0)
                        {
                            if (LOG.IsDebugEnabled)
                            {
                                LOG.DebugFormat("File size after processing {0}", new FileInfo(tmpFileName).Length);
                                LOG.DebugFormat("Reading back tmp file: {0}", tmpFileName);
                            }
                            byte[] processedImage = File.ReadAllBytes(tmpFileName);
                            targetStream.Write(processedImage, 0, processedImage.Length);
                            return(true);
                        }
                        LOG.ErrorFormat("Error while processing PNG image: {0}", process.ExitCode);
                        LOG.ErrorFormat("Output: {0}", process.StandardOutput.ReadToEnd());
                        LOG.ErrorFormat("Error: {0}", process.StandardError.ReadToEnd());
                    }
                }
            }
            catch (Exception e)
            {
                LOG.Error("Error while processing PNG image: ", e);
            }
            finally
            {
                if (File.Exists(tmpFileName))
                {
                    LOG.DebugFormat("Cleaning up tmp file: {0}", tmpFileName);
                    File.Delete(tmpFileName);
                }
            }
            return(false);
        }