Esempio n. 1
0
        public bool testExtractFileRefInfo()
        {
            TestUtilities.vbtitle("testing FileRef handling");
            FileRef  fileRef = "cat/file";
            DirName  dtest   = RepoEnvironment.checkout.extractCategory(fileRef);
            FileName ftest   = RepoEnvironment.checkout.extractFileName(fileRef);
            bool     result1 = (dtest == "cat") && (ftest == "file");

            TestUtilities.checkResult(result1, string.Format("valid FileRef \"{0}\" - ", fileRef));

            fileRef = "cat/";
            dtest   = RepoEnvironment.checkout.extractCategory(fileRef);
            ftest   = RepoEnvironment.checkout.extractFileName(fileRef);
            bool result2 = (dtest == "cat") && (ftest == "");

            TestUtilities.checkResult(result2, string.Format("empty file in FileRef \"{0}\" - ", fileRef));

            fileRef = "/file";
            dtest   = RepoEnvironment.checkout.extractCategory(fileRef);
            ftest   = RepoEnvironment.checkout.extractFileName(fileRef);
            bool result3 = (dtest == "") && (ftest == "file");

            TestUtilities.checkResult(result3, string.Format("empty category in FileRef \"{0}\" - ", fileRef));

            fileRef = "abcdefg";
            dtest   = RepoEnvironment.checkout.extractCategory(fileRef);
            ftest   = RepoEnvironment.checkout.extractFileName(fileRef);
            bool result4 = (dtest == "") && (ftest == "");

            TestUtilities.checkResult(result4, string.Format("invalid FileRef \"{0}\" - ", fileRef));

            return(result1 && result2 && result3 && result4);
        }
Esempio n. 2
0
        /*----< find metadata file in storage >------------------------*/

        /*
         * - returns versioned fileName of metadata in Storage
         * - if not found, returns empty string.
         */
        public FileName findStoredMetaData(DirName category, FileName fileName)
        {
            FileName tempFile = RepoEnvironment.version.removeVersion(fileName);

            if (Path.GetExtension(tempFile) != ".xml")
            {
                return("");
            }

            // if fileName has no version, check if storage/category has a
            // versioned fileName

            if (!RepoEnvironment.version.hasVersion(fileName))
            {
                int version = RepoEnvironment.version.getLatestVersion(category, fileName);
                if (version == 0)
                {
                    return("");
                }
                fileName = fileName + "." + version.ToString();
            }

            // make sure there is a file with the cached version found above
            List <FileName> files = RepoEnvironment.storage.files(category);

            foreach (FileName file in files)
            {
                if (file == fileName)
                {
                    return(file);
                }
            }
            return("");
        }
Esempio n. 3
0
        /*----< test moving file to category folder >------------------*/

        public bool testAddFile(FileName srcFile, DirName category)
        {
            TestUtilities.vbtitle("testing addFile");
            FileName dstFile     = srcFile;
            FileSpec srcFileSpec = storage.stagingFilePath(srcFile);

            srcFileSpec = Path.GetFullPath(srcFileSpec);

            bool test;

            if (!File.Exists(srcFileSpec))
            {
                test = TestUtilities.handleInvoke(
                    () => {
                    var tempFile = File.Create(srcFileSpec);
                    tempFile.Close();
                    return(true);
                }
                    );
            }

            TestUtilities.putLine(string.Format("adding file \"{0}\" to category \"{1}\"", srcFile, category));

            test = TestUtilities.handleInvoke(
                () => { return(storage.addFile(category, srcFile)); }
                );

            TestUtilities.checkResult(test, "Storage.testAddFile");
            return(test);
        }
 public static void cmdFTPDownloadFile()
 {
     try
     {
         DirName = DirName.Replace("\\", "/");
         FileStream   myFTPCommand = new System.IO.FileStream("FTPCommand.txt", FileMode.Create, FileAccess.ReadWrite);
         StreamWriter myCommand    = new StreamWriter(myFTPCommand);
         myCommand.BaseStream.Seek(0, SeekOrigin.Begin);
         myCommand.WriteLine("open" + " " + FTPServerIP + " ");
         myCommand.WriteLine(UserName);
         myCommand.WriteLine(PassWord);
         myCommand.WriteLine("get" + " " + DirName + "\"" + FromFileName + "\"" + " " + "\"" + ToFileName + "\"");
         myCommand.WriteLine("bye");
         myCommand.Flush();
         myCommand.Close();
         myCommand.Dispose();
         Process.Start(Environment.GetEnvironmentVariable("SystemRoot") + "\\system32\\ftp.exe", "-s:\"" + Path.GetFullPath("FTPCommand.txt") + "\"").WaitForExit();
         File.Delete("D:\\FTPCommand.txt");
     }
     catch (Exception ex)
     {
         //Console.WriteLine("FTP File Seach Fail" + "\n" + "{0}", ex.Message);
         //MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false);
     }
 }
Esempio n. 5
0
        /*----< test copying file from category to staging folder >----*/

        public bool testRetrieveFile(DirName category)
        {
            TestUtilities.vbtitle("testing retrieveFile");

            PathName path = storage.storagePath(category);

            FileSpec[] files = Directory.GetFiles(path);
            if (files.Length == 0)
            {
                TestUtilities.putLine(string.Format("can't find file in \"{0}\"", category));
                return(false);
            }

            FileName testFile1 = Path.GetFileName(files[fileIndex]);

            TestUtilities.putLine(string.Format("retrieving file \"{0}\"", testFile1));
            bool result1 = storage.retrieveFile(category, testFile1);

            fileIndex = (++fileIndex) % files.Length;
            TestUtilities.checkResult(result1, "Storage.retrieveFile");

            FileName testFile2 = Path.GetFileName(files[fileIndex]);

            TestUtilities.putLine(string.Format("retrieving file \"{0}\"", testFile2));
            bool result2 = storage.retrieveFile(category, testFile2);

            fileIndex = (++fileIndex) % files.Length;
            TestUtilities.checkResult(result2, "Storage.retrieveFile");

            return(result1 && result2);
        }
Esempio n. 6
0
        public bool testComponent()
        {
            TestUtilities.title("Testing FileNameEditor", '=');
            TestUtilities.putLine();

            TestUtilities.title("Testing extension edits");
            FileName fileName  = "SomeFile.cs.2";
            FileName test1Name = addXmlExt(fileName);
            bool     t1        = test1Name.Contains(".xml");

            showResult(t1, test1Name, "addXmlExt");

            FileName test2Name = removeXmlExt(test1Name);
            bool     t2        = test2Name == fileName;

            showResult(t2, test2Name, "removeXmlExt");

            FileName test3Name = removeXmlExt(test2Name);
            bool     t3        = test3Name == fileName;

            showResult(t3, test3Name, "removeXmlExt");
            TestUtilities.putLine();

            TestUtilities.title("Testing path construction");
            DirName stagingdir  = "Fawcett";
            FullDir stagingpath = stagingPath(stagingdir);
            bool    t4          = (stagingpath.Contains("C:/") || stagingpath.Contains("../")) && stagingpath.Contains(stagingdir);

            showResult(t4, stagingpath, "stagingPath");

            DirName category    = "SomeCategory";
            FullDir storagepath = storagePath(category);
            bool    t5          = (storagepath.Contains("C:/") || storagepath.Contains("../")) && storagepath.Contains(category);

            showResult(t5, storagepath, "storagePath");

            FileName someFileName = "someFileName";
            FileSpec filespec     = fileSpec(storagepath, someFileName);
            bool     t6           = filespec.Contains("/someFileName");

            showResult(t6, filespec, "fileSpec");

            FileRef fileref = storageFolderRef(filespec);
            bool    t7      = fileref.IndexOf('/') == fileref.LastIndexOf('/');

            showResult(t7, fileref, "storageFolderRef");

            DirName cat = extractCategory(fileref);
            bool    t8  = cat == category;

            showResult(t8, cat, "extractCategory");

            FileName file = extractFileName(fileref);
            bool     t9   = file == someFileName;

            showResult(t8, file, "extractFileName");

            return(t1 && t2 && t3 && t4 && t5 && t6 && t7 && t8 && t9);
        }
Esempio n. 7
0
 /// <summary>
 /// Parse a directoryname
 /// </summary>
 /// <returns>Parsed DirName</returns>
 public DirName ParseDirectoryName()
 {
     DirName directoryName = new DirName();
     
     directoryName.SetDirectory(ParseDirectory());
     
     return directoryName;
 }
Esempio n. 8
0
        /*----< create directory for storing packages >----------------*/

        public bool createStorage(DirName category = "")
        {
            PathName      path = Path.Combine(RepoEnvironment.storagePath, category);
            DirectoryInfo di   = Directory.CreateDirectory(path);

            if (di.Exists)
            {
                return(true);
            }
            return(false);
        }
Esempio n. 9
0
        /*----< show found status >------------------------------------*/

        public void showFoundStatus(DirName category, FileName searchName, FileName foundName)
        {
            TestUtilities.putLine(string.Format("searching for file \"{0}/{1}\"", category, searchName));
            if (foundName.Length > 0)
            {
                TestUtilities.putLine(string.Format("found file \"{0}/{1}\"", category, foundName));
            }
            else
            {
                TestUtilities.putLine(string.Format("didn't find file \"{0}/{1}\"", category, searchName));
            }
        }
Esempio n. 10
0
        /*----< find all versions of file in category >----------------*/

        public List <FileName> findVersions(DirName category, FileName fileName)
        {
            if (RepoEnvironment.version.hasVersion(fileName))
            {
                fileName = RepoEnvironment.version.removeVersion(fileName);
            }

            FileName[] files = Directory.GetFiles(storagePath(category), fileName + "*");
            for (int i = 0; i < files.Length; ++i)
            {
                files[i] = Path.GetFileName(files[i]);
            }
            return(files.ToList <string>());
        }
Esempio n. 11
0
        /*---< return list of unique fileNames in storage/category >---*/

        public List <FileName> uniqueFileNames(DirName category, bool showPath = false)
        {
            HashSet <FileName> set       = new HashSet <FileSpec>();
            List <FileName>    fileNames = files(category);

            for (int i = 0; i < fileNames.Count; ++i)
            {
                fileNames[i] = RepoEnvironment.version.removeVersion(fileNames[i]);
                if (!set.Contains(fileNames[i]))
                {
                    set.Add(fileNames[i]);
                }
            }
            return(set.ToList <FileName>());
        }
Esempio n. 12
0
        /*----< test creating subfolder in storage >-------------------*/

        public bool testCreateStorage()
        {
            TestUtilities.vbtitle("testing createStorage");
            bool    test1, test2;
            DirName path = "test";

            test1 = TestUtilities.handleInvoke(() => { return(storage.createStorage(path)); });
            test2 = Directory.Exists(storage.storagePath(path));
            if (test1 && test2)
            {
                TestUtilities.putLine(string.Format("Created storage \"{0}\"", path));
            }
            TestUtilities.checkResult(test1 && test2, "Storage.createStorage");
            return(test1 && test2);
        }
Esempio n. 13
0
        /*----< copy file from storage to staging area >---------------*/

        /*
         * - srcFile is expected to be a file name, e.g., has no path
         */
        public bool retrieveFile(DirName category, FileName srcFile, bool overwrite = true)
        {
            FileSpec srcFileSpec = storageFilePath(category, srcFile);
            FileSpec dstFileSpec = RepoEnvironment.version.removeVersion(srcFile);

            dstFileSpec = stagingFilePath(dstFileSpec);

            bool test = TestUtilities.handleInvoke(
                () =>
            {
                File.Copy(srcFileSpec, dstFileSpec, overwrite); return(true);
            }
                );

            return(test);
        }
Esempio n. 14
0
        /*----< test path handling >-----------------------------------*/

        /*
         * - test storagePath, extractCategory, and extractFilename
         */
        bool testPathHandling()
        {
            TestUtilities.vbtitle("testing path handling");

            DirName  testCategory = "TestCategory";
            FileName testFileName = "foobar.cs.23";

            FullPath testPath1 = checkin.storagePath(testCategory + "/" + testFileName);

            TestUtilities.putLine(string.Format("test path = \"{0}\"", testPath1));

            DirName category = checkin.extractCategory(testPath1);

            if (category != testCategory)
            {
                return(false);
            }
            TestUtilities.putLine(string.Format("category = \"{0}\"", category));

            FileName fileName = checkin.extractFileName(testPath1);

            if (fileName != testFileName)
            {
                return(false);
            }
            TestUtilities.putLine(string.Format("fileName = \"{0}\"", fileName));

            testPath1 = "abc123";
            TestUtilities.putLine(string.Format("test path = \"{0}\"", testPath1));

            category = checkin.extractCategory(testPath1);
            if (category.Length != 0)
            {
                return(false);
            }
            TestUtilities.putLine(string.Format("category = \"{0}\"", category));

            fileName = checkin.extractFileName(testFileName);
            if (fileName.Length != 0)
            {
                return(false);
            }
            TestUtilities.putLine(string.Format("fileName = \"{0}\"", fileName));

            return(true);
        }
Esempio n. 15
0
        public bool testDoCheckout()
        {
            TestUtilities.vbtitle("testing doCheckout");

            // setup test by running checkin.testComponent()
            bool verbose = ClientEnvironment.verbose;

            ClientEnvironment.verbose = false;
            RepoEnvironment.checkin.testComponent();
            ClientEnvironment.verbose = verbose;

            // execute test
            DirName  category = "test";
            FileName fileName = "testFile3.cs.xml";
            bool     test     = RepoEnvironment.checkout.doCheckout(category, fileName);

            return(test);
        }
Esempio n. 16
0
        /*----< return list of categories >----------------------------*/

        public List <DirName> categories(bool showPath = false)
        {
            PathName[]     dirs = Directory.GetDirectories(RepoEnvironment.storagePath);
            List <DirName> cats = new List <DirName>();

            foreach (DirName dir in dirs)
            {
                DirectoryInfo di   = new DirectoryInfo(dir);
                DirName       name = di.Name;
                if (showPath)
                {
                    name = Path.Combine(RepoEnvironment.storagePath, name);
                    name = Path.GetFullPath(name); // now a FullPath
                }
                cats.Add(name);
            }
            return(cats);
        }
Esempio n. 17
0
        /*----< return list of files in storage/category >-------------*/

        public List <FileName> files(DirName category, bool showPath = false)
        {
            PathName path = Path.Combine(RepoEnvironment.storagePath, category);

            FileSpec[] files = Directory.GetFiles(path);
            for (int i = 0; i < files.Length; ++i)
            {
                if (showPath)
                {
                    files[i] = Path.GetFullPath(files[i]); // now an absolute FileSpec
                }
                else
                {
                    files[i] = Path.GetFileName(files[i]); // now a FileName
                }
            }
            return(files.ToList <FileName>());
        }
Esempio n. 18
0
        /*----< copy checkout files to staging directory >-------------*/

        /*
         *  Copies metadata file and its referenced file and
         *  copies all descendent metadata files and their referenced files.
         */
        public bool doCheckout(DirName category, FileName fileName)
        {
            FileName found = RepoEnvironment.checkin.findStoredMetaData(category, fileName);

            if (found == "")
            {
                return(false);
            }

            MetaData md = new MetaData();

            try
            {
                string path = System.IO.Path.Combine(RepoEnvironment.storagePath + "/", category + "/", found);
                md.load(path);
            }
            catch
            {
                return(false);
            }
            string refFile = md.fileSpec;

            fileList.Clear();
            string fileSpec = System.IO.Path.Combine(category + "/", fileName);

            fileList.Add(refFile);
            fileList.Add(fileSpec);
            Dependencies deps = RepoEnvironment.storage.descendents(fileSpec);

            foreach (string dep in deps)
            {
                fileList.Add(dep);
            }
            foreach (string file in fileList)
            {
                string cata = extractCategory(file);
                string name = extractFileName(file);
                RepoEnvironment.storage.retrieveFile(cata, name);
                string temp = removeXmlExt(name);
                RepoEnvironment.storage.retrieveFile(cata, temp);
            }
            return(true);
        }
Esempio n. 19
0
        private static string GetFTPURL()
        {
            StringBuilder stringBuilder = new StringBuilder("ftp://");

            if (!string.IsNullOrEmpty(FTPServerIP))
            {
                stringBuilder.Append(FTPServerIP);
            }

            if (!string.IsNullOrEmpty(DirName))
            {
                DirName.Replace("\\", "/");
                DirName = DirName.TrimStart('/');
                DirName = DirName.TrimEnd('/');
                stringBuilder.Append("/").Append(DirName);
            }

            if (!string.IsNullOrEmpty(FromFileName))
            {
                FileName = FromFileName.TrimStart('/');
                FileName = Path.GetFileName(FileName);
                if (!string.IsNullOrEmpty(DirName))
                {
                    stringBuilder.Append("/");
                }
                stringBuilder.Append(FileName);
            }
            else
            {
                if (!string.IsNullOrEmpty(ToFileName))
                {
                    FileName = ToFileName.TrimStart('/');
                    FileName = Path.GetFileName(FileName);
                    if (!string.IsNullOrEmpty(DirName))
                    {
                        stringBuilder.Append("/");
                    }
                    stringBuilder.Append(FileName);
                }
            }

            return(stringBuilder.ToString());
        }
        /*----< returns names of files stored in server folder >-------*/

        public static FileList getFiles(DirName category)
        {
            FileList files = new FileList();

            try
            {
                string path = System.IO.Path.Combine(ServerEnvironment.storagePath + "/", category);
                files = System.IO.Directory.GetFiles(path).ToList <string>();
                for (int i = 0; i < files.Count; ++i)
                {
                    files[i] = System.IO.Path.GetFileName(files[i]);
                }
                return(files);
            }
            catch
            {
                return(files);
            }
        }
Esempio n. 21
0
        /*----< test find file >---------------------------------------*/

        public bool testFindFile()
        {
            TestUtilities.vbtitle("testing findFile");
            DirName         category = "test2";
            bool            t1       = false;
            bool            t2       = false;
            bool            t3       = false;
            List <FileName> allfiles = storage.files(category);
            FileName        file;

            if (allfiles.Count > 0)
            {
                file = allfiles[0];
                TestUtilities.putLine(string.Format("searching for file \"{0}\" in category \"{1}\"", file, category));
                FileName found1 = storage.findFile(category, file);
                TestUtilities.putLine(string.Format("found file \"{0}\"", found1));
                t1 = (found1.Length > 0);
                TestUtilities.checkResult(t1, "testFindFile");
            }
            if (allfiles.Count > 1)
            {
                file = "doesNotExist.cs";
                TestUtilities.putLine(string.Format("searching for file \"{0}\" in category \"{1}\"", file, category));
                string found2 = storage.findFile(category, file);
                TestUtilities.putLine(string.Format("found file \"{0}\"", found2));
                t2 = (found2.Length == 0);
                TestUtilities.checkResult(t2, "testFindFile");
            }
            if (allfiles.Count > 0)
            {
                file = RepoEnvironment.version.removeVersion(allfiles[1]);
                TestUtilities.putLine(string.Format("searching for file \"{0}\" in category \"{1}\"", file, category));
                FileName found3 = storage.findFile(category, file);
                TestUtilities.putLine(string.Format("found file \"{0}\"", found3));
                t3 = (found3.Length > 0);
                TestUtilities.checkResult(t3, "testFindFile");
            }
            bool result = t1 && t2 && t3;

            TestUtilities.checkResult(result, "Storage.findFile");
            return(result);
        }
Esempio n. 22
0
        public void ParseDirectoryNameTest()
        {
            //Get tokens and parse it
            TokenIterator tokens     = Init("home\\site\\test.wae");
            SiteParser    siteParser = new SiteParser(tokens);
            DirName       output     = siteParser.ParseDirectoryName();
            Dir           directory  = output.GetDirectory();

            //Check output
            Assert.AreEqual(2, directory.GetDirectoryElements().Count);

            //Get directory's and transfer to array to provide walking
            List <ISyntaxNode> .Enumerator directoryEnumerator = directory.GetDirectoryElements().GetEnumerator();

            //Check directory's
            directoryEnumerator.MoveNext();
            Assert.AreEqual("home", ((PathElement)directoryEnumerator.Current).GetPathElement());
            directoryEnumerator.MoveNext();
            Assert.AreEqual("site", ((PathElement)directoryEnumerator.Current).GetPathElement());
        }
Esempio n. 23
0
        /*----< retrieves children specified in metadata file >--------*/

        /*
         *  returns list that includes reference to metadata file and
         *  references to its metadata children
         */
        public bool retrieveDependencies(DirName category, FileName filename)
        {
            FileName found = RepoEnvironment.checkin.findStoredMetaData(category, filename);

            if (found == "")
            {
                return(false);
            }

            FullPath  pathToMetaData = System.IO.Path.Combine(RepoEnvironment.storagePath, category);
            IMetaData md             = RepoEnvironment.checkin.loadMetaData(pathToMetaData, found);

            if (md == null)
            {
                return(false);
            }

            if (ClientEnvironment.verbose)
            {
                TestUtilities.putLine(string.Format("contents of metadata \"{0}\" on dependency tree", found));
                md.show();
                TestUtilities.putLine();
            }
            // extract primary filename from metadata and add to fileList
            FileName srcFile = extractFileName(md.fileSpec);

            fileList.Add(srcFile);

            if (md.dependencies.Count == 0)
            {
                return(true);
            }

            foreach (FileRef fileRef in md.dependencies)
            {
                FileName dfileName = extractFileName(fileRef);
                dependencies.Add(dfileName);
                retrieveDependencies(category, dfileName);
            }
            return(true);
        }
Esempio n. 24
0
        public static DateTime FTPGetFileDate()
        {
            try
            {
                DirName = DirName.Replace("\\", "/");
                string sURI = "FTP://" + FTPServerIP + "/" + DirName + "/" + FileName;

                FtpWebRequest myFTP = (FtpWebRequest)WebRequest.Create(sURI); //建立FTP連線

                //設定連線模式及相關參數
                myFTP.EnableSsl = EnabledSSL;   //設定是否使用安全連線

                if (EnabledSSL)
                {
                    ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertificatePolicy;
                }

                myFTP.Credentials = new NetworkCredential(UserName, PassWord);      //帳密驗證
                myFTP.Timeout     = 2000;                                           //等待時間
                myFTP.UseBinary   = true;                                           //傳輸資料型別 二進位/文字
                myFTP.Method      = WebRequestMethods.Ftp.GetDateTimestamp;         //取得資料修改日期

                FtpWebResponse myFTPFileDate = (FtpWebResponse)myFTP.GetResponse(); //取得FTP請求回應
                return(myFTPFileDate.LastModified);
            }
            catch (Exception ex)
            {
                Console.WriteLine("FTP Dictionar Query Fail" + "\n" + "{0}", ex.Message);
                //MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false);
                FTPReTry--;
                if (FTPReTry >= 0)
                {
                    return(FTPGetFileDate());
                }
                else
                {
                    return(DateTime.MinValue);
                }
            }
        }
Esempio n. 25
0
        /*----< move or copy file from staging area to storage >-------*/

        /*
         *  srcFile is the name of file in stagingPath
         *  dstFile is the name of the file to be moved to storagePath
         *  category is subdirectory of storagePath where dstFile will be moved or copied
         *
         *  modifyFile adds a version number equal to the existing version number
         *  to dstFile before putting in storage area defined by category
         *
         *  For testing purposes it may be convenient to copy, rather than move, the srcFile.
         *  If so set move to false.
         */
        public bool modifyFile(DirName category, FileName srcFile, FileName dstFile = "", bool move = true)
        {
            move = false;
            if (dstFile.Length == 0)
            {
                dstFile = srcFile;
            }

            //FileName ver_dstFile = RepoEnvironment.version.addVersion(category, dstFile);
            int      ver         = RepoEnvironment.version.getLatestVersion(category, dstFile);
            FileName ver_dstFile = dstFile + "." + ver.ToString();

            FileSpec srcFileSpec = stagingFilePath(srcFile);
            FileSpec catPath     = storagePath(category);

            if (!Directory.Exists(catPath))
            {
                Directory.CreateDirectory(catPath);
            }

            FileSpec dstFileSpec = storageFilePath(category, ver_dstFile);

            bool ok;

            if (move)
            {
                ok = TestUtilities.handleInvoke(
                    () => { File.Move(srcFileSpec, dstFileSpec); return(true); }
                    );
            }
            else
            {
                ok = TestUtilities.handleInvoke(
                    () => { File.Copy(srcFileSpec, dstFileSpec, true); return(true); }
                    );
            }

            return(ok);
        }
Esempio n. 26
0
        static private string CurrentDir(DirName dirName)
        {
            string path;

            if (dirName == DirName.Library)
            {
                path = "library";
            }
            else
            {
                path = "temp";
            }

            DirectoryInfo dir = new DirectoryInfo(
                System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\" + path);

            if (!dir.Exists)
            {
                dir.Create();
            }
            return(dir.FullName);
        }
        /*----< returns names of files stored in server folder >-------*/

        public static FileList getFiles(DirName category, string[] patterns, bool sortByTime)
        {
            FileList files = new FileList();

            try
            {
                string path = System.IO.Path.Combine(RepoServerEnvironment.storagePath + "/", category);

                IEnumerable <FileInfo> fileInfos;
                if (sortByTime)
                {
                    fileInfos = new DirectoryInfo(path).GetFiles().OrderByDescending(f => f.LastWriteTime);
                }
                else
                {
                    fileInfos = new DirectoryInfo(path).GetFiles();
                }

                if (patterns == null || patterns.Length == 0)
                {
                    files = fileInfos.Select(x => x.Name).ToList <string>();
                }
                else
                {
                    files = fileInfos.Select(x => x.Name).Where(f => patterns.Any(f.ToLower().EndsWith)).ToList <string>();
                }

                for (int i = 0; i < files.Count; ++i)
                {
                    files[i] = System.IO.Path.GetFileName(files[i]);
                }
                return(files);
            }
            catch
            {
                return(files);
            }
        }
Esempio n. 28
0
        /*----< find file in Storage/Category >-----------------------*/

        public FileName findFile(DirName category, FileName fileName)
        {
            string foundName = "";

            // if not versioned, add latest version

            if (!RepoEnvironment.version.hasVersion(fileName))
            {
                int ver = RepoEnvironment.version.getLatestVersion(category, fileName);
                fileName = fileName + "." + ver.ToString();
            }
            List <FileName> files = RepoEnvironment.storage.files(category);

            foreach (FileSpec file in files)
            {
                if (file == fileName)
                {
                    foundName = fileName;
                    break;
                }
            }
            return(foundName);
        }
Esempio n. 29
0
        private void GatherFile(string ReqFile, string ReqParam, HttpListenerRequest SourceReq)
        {
            HttpWebRequest ServerRequest = WebRequest.Create(new Uri("http://gc2.gczero.com/" + ReqFile + "?" + ReqParam)) as HttpWebRequest;

            for (int i = 0; i < SourceReq.Headers.Count; i++)
            {
                string HeaderName_Orig  = SourceReq.Headers.Keys[i];
                string HeaderValue_Orig = SourceReq.Headers.GetValues(i)[0];

                switch (HeaderName_Orig)
                {
                case "Accept":
                    ServerRequest.Accept = HeaderValue_Orig;
                    //ServerRequest.Connection = HeaderValue_Orig;
                    break;

                case "User-Agent":
                    ServerRequest.UserAgent = HeaderValue_Orig;
                    break;

                case "Accept-Encoding":
                    //ServerRequest.TransferEncoding = HeaderValue_Orig;
                    break;

                case "Accept-Language":
                    //ServerRequest.a
                    break;

                case "Host":
                    ServerRequest.Host = HeaderValue_Orig;
                    break;
                }
            }

            var  Input      = default(byte[]);
            bool HasContent = false;

            if (SourceReq.HttpMethod == "POST")
            {
                HasContent = true;
                using (var memstream = new MemoryStream())
                {
                    SourceReq.InputStream.CopyTo(memstream);
                    Input = memstream.ToArray();
                }
            }

            if (HasContent)
            {
                ServerRequest.Method = "POST";
                ServerRequest.GetRequestStream().Write(Input, 0, Input.Length);
            }

            Console.WriteLine("Getting response from game server: " + ReqFile);
            HttpWebResponse ServerResponse;

            try
            {
                ServerResponse = ServerRequest.GetResponse() as HttpWebResponse;
            }
            catch (Exception e)
            {
                throw e;
            }

            var ServerOutput = default(byte[]);

            using (var memstream = new MemoryStream())
            {
                ServerResponse.GetResponseStream().CopyTo(memstream);
                ServerOutput = memstream.ToArray();
            }

            if (ReqFile.Split('/').Length > 0)
            {
                string DirectoryData = "";
                foreach (string DirName in ReqFile.Split('/'))
                {
                    if (!DirName.Contains("."))
                    {
                        if (nonWindows)
                        {
                            DirectoryData += DirName + "/";
                        }
                        else
                        {
                            DirectoryData += DirName + "\\";
                        }
                    }

                    if (!Directory.Exists(DirectoryData))
                    {
                        Console.WriteLine("Creating directory: " + DirectoryData);
                        Directory.CreateDirectory(CacheFolder + DirectoryData);
                    }
                }
            }
            File.WriteAllBytes(CacheFolder + ReqFile, ServerOutput);
            SpecialTreatment(ReqFile);
            return;
            //Console.ReadLine();
        }
Esempio n. 30
0
        public CertVaultCertificate(CertVault vault, DirectoryPath dirName, CertVaultCertType certType)
        {
            this.Vault = vault;

            if (certType.EqualsAny(CertVaultCertType.Acme, CertVaultCertType.Static, CertVaultCertType.AutoGenerated) == false)
            {
                throw new ArgumentOutOfRangeException("certType");
            }

            try
            {
                dirName.CreateDirectory();
            }
            catch { }

            CertificateStore?store = null;

            this.CertType = certType;
            this.DirName  = dirName;

            if (certType == CertVaultCertType.Static || certType == CertVaultCertType.AutoGenerated)
            {
                // Static / auto generated cert
                var files = DirName.EnumDirectory().Where(x => x.IsDirectory == false);

                string?p12file = files.Where(x => x.Name._IsExtensionMatch(Consts.Extensions.Filter_Pkcs12s)).SingleOrDefault()?.FullPath;

                string?certfile = files.Where(x => x.Name._IsExtensionMatch(Consts.Extensions.Filter_Certificates)).SingleOrDefault()?.FullPath;
                string?keyfile  = files.Where(x => x.Name._IsExtensionMatch(Consts.Extensions.Filter_Keys)).SingleOrDefault()?.FullPath;

                string?passwordfile = files.Where(x => x.Name._IsSamei(Consts.FileNames.CertVault_Password)).SingleOrDefault()?.FullPath;
                string?password     = null;

                if (passwordfile != null)
                {
                    password = FileSystem !.ReadStringFromFile(passwordfile, oneLine: true);

                    if (password._IsEmpty())
                    {
                        password = null;
                    }
                }

                if (p12file != null)
                {
                    store = new CertificateStore(FileSystem !.ReadDataFromFile(p12file).Span, password);
                }
                else if (certfile != null && keyfile != null)
                {
                    store = new CertificateStore(FileSystem !.ReadDataFromFile(certfile).Span, FileSystem.ReadDataFromFile(keyfile).Span, password);
                }
                else
                {
                    store = null;
                }
            }
            else
            {
                // ACME cert
                FilePath fileName = DirName.Combine(DirName.GetThisDirectoryName() + Consts.Extensions.Certificate_Acme);

                if (fileName.IsFileExists())
                {
                    store = new CertificateStore(fileName.ReadDataFromFile().Span, this.Vault.AcmeCertKey !);
                }
                else
                {
                    store = null;
                }
            }

            Certificate?test = store?.PrimaryContainer.CertificateList[0];

            if (test != null && store != null)
            {
                if (test.PublicKey.Equals(store.PrimaryContainer.PrivateKey.PublicKey) == false)
                {
                    Con.WriteDebug($"CertVault: The public key certificate in the directory '{dirName}' doesn't match to the private key.");
                    store = null;
                }
            }

            this.Store = store;
        }