private void BackupProjectFiles(TempGenerationResult result)
        {
            var projectGuid = GenContext.ToolBox.Shell.GetActiveProjectGuid();

            if (string.IsNullOrEmpty(projectGuid))
            {
                return;
            }

            var backupFolder = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                Configuration.Current.BackupFolderPath,
                projectGuid);

            var fileName = Path.Combine(backupFolder, "backup.json");

            if (Directory.Exists(backupFolder))
            {
                Fs.SafeDeleteDirectory(backupFolder);
            }

            Fs.EnsureFolder(backupFolder);

            File.WriteAllText(fileName, JsonConvert.SerializeObject(result), Encoding.UTF8);

            var modifiedFiles = result.ConflictingFiles.Concat(result.ModifiedFiles);

            foreach (var file in modifiedFiles)
            {
                var originalFile  = Path.Combine(GenContext.Current.ProjectPath, file);
                var backupFile    = Path.Combine(backupFolder, file);
                var destDirectory = Path.GetDirectoryName(backupFile);

                Fs.SafeCopyFile(originalFile, destDirectory, true);
            }
        }
        public void SafeCopyFile_FileDoesNotExist_ShouldCreateNewFileWhileCopying()
        {
            var testScenarioName  = "FileDoesNotExist";
            var directoryToCreate = $"{_testFolder}\\{testScenarioName}";

            FSTestsFixture.CreateFolders(_testFolder, new List <string>()
            {
                testScenarioName
            });
            var expectedDestinationFile = Path.Combine(directoryToCreate, Path.GetFileName(_sourceFile));

            var fileExistsAtStart  = File.Exists(expectedDestinationFile);
            var totalOriginalFiles = Directory.GetFiles(directoryToCreate).Length;

            Fs.SafeCopyFile(_sourceFile, directoryToCreate, true);

            var totalNewFiles = Directory.GetFiles(directoryToCreate).Length;

            var fileHasBeenCreated = totalNewFiles > totalOriginalFiles;

            Assert.False(fileExistsAtStart);
            Assert.True(fileHasBeenCreated);
            Assert.True(File.Exists(expectedDestinationFile));
        }
Exemplo n.º 3
0
        public void ReceiveFile(string FileName, long FileLength)
        {
            FileStream Fs = null;

            try
            {
                byte[] RecData = new byte[FilePiece.data_size];
                int    RecBytes;
                client    = Listener.AcceptTcpClient();
                netstream = client.GetStream();
                if (FileName != string.Empty)
                {
                    Fs = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
                    while ((RecBytes = netstream.Read(RecData, 0, RecData.Length)) > 0)
                    {
                        Fs.Write(RecData, 0, RecBytes);
                    }
                    Fs.Close();
                    netstream.Close();
                    client.Close();
                }
            }
            catch (IOException ex)
            {
                Fs.Close();
                DestroyConnection();
                Message = "COPY: Not enough space on disk: " + ex;
                Console.WriteLine(Message);
                error = true;
            }
            catch
            {
                error = true;
                Fs.Close();
            }
        }
Exemplo n.º 4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @ParameterizedTest @ValueSource(ints = {0, 1}) void swappingOutMustNotOverwriteDataBeyondPage(int noChannelStriping) throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void SwappingOutMustNotOverwriteDataBeyondPage(int noChannelStriping)
        {
            sbyte[]      initialData = new sbyte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            sbyte[]      finalData   = new sbyte[] { 1, 2, 3, 4, 8, 7, 6, 5, 9, 10 };
            StoreChannel channel     = Fs.create(File);

            channel.WriteAll(Wrap(initialData));
            channel.close();

            sbyte[] change = new sbyte[] { 8, 7, 6, 5 };
            long    page   = CreatePage(change);

            PageSwapperFactory factory = CreateSwapperFactory();
            PageSwapper        swapper = CreateSwapper(factory, File, 4, null, false, Bool(noChannelStriping));

            swapper.Write(1, page);

            Stream stream = Fs.openAsInputStream(File);

            sbyte[] actual = new sbyte[( int )Fs.getFileSize(File)];

            assertThat(stream.Read(actual, 0, actual.Length), @is(actual.Length));
            assertThat(actual, byteArray(finalData));
        }
        private async Task BuildProjectAndRunWackAsync(string projectType, string framework, string platform, string language, Func <ITemplateInfo, bool> templateSelector)
        {
            var projectName = $"{projectType}{framework}Wack{ShortLanguageName(language)}Wpf";

            var projectPath = await AssertGenerateProjectAsync(projectName, projectType, framework, platform, language, templateSelector, GenerationFixture.GetDefaultName);

            // Replace the default assets in the generated project or they will cause WACK to fail
            foreach (var assetFile in new DirectoryInfo("../../TestData/NonDefaultAssets").GetFiles("*.png"))
            {
                File.Copy(assetFile.FullName, Path.Combine(GenContext.Current.DestinationPath + ".Packaging", "Images", assetFile.Name), overwrite: true);
            }

            var packagingProjectName = projectName + ".Packaging";

            // Create MSIXBundle
            // NOTE. This is very slow. (i.e. ~10+ mins) as it does a full release build including all .net native compilation
            var(exitCode, outputFile) = _fixture.BuildMsixBundle(projectName, projectPath, packagingProjectName, "wapproj", "bat\\Wpf\\RestoreAndBuildAppx.bat");

            Assert.True(exitCode.Equals(0), $"Failed to create MsixBundle for {packagingProjectName}. {Environment.NewLine}Errors found: {_fixture.GetErrorLines(outputFile)}.{Environment.NewLine}Please see {Path.GetFullPath(outputFile)} for more details.");

            var bundleFile = new DirectoryInfo(Path.Combine(projectPath, packagingProjectName, "AppPackages")).GetFiles("*.msixbundle", SearchOption.AllDirectories).First().FullName;

            // Run WACK test
            // NOTE. This requires elevation. If not elevated you'll get a UAC prompt
            var wackResult = _fixture.RunWackTestOnMsixBundle(bundleFile, projectPath);

            Assert.True(wackResult.exitCode.Equals(0), $"Failed to create MsixBundle for {packagingProjectName}. {Environment.NewLine}Errors found: {_fixture.GetErrorLines(wackResult.outputFile)}.{Environment.NewLine}Please see {Path.GetFullPath(wackResult.outputFile)} for more details.");

            var overallSuccessXml = @"OVERALL_RESULT=""PASS""";

            var wackResultOutput = File.ReadAllText(wackResult.resultFile);

            Assert.True(wackResultOutput.Contains(overallSuccessXml), $"WACK test failed for {projectName}.{Environment.NewLine}Please see {Path.GetFullPath(wackResult.resultFile)} for more details.");

            Fs.SafeDeleteDirectory(projectPath);
        }
        public void EnsureFileEditable_FileIsReadOnly_ShouldChangeToReadOnly()
        {
            var testScenarioName = "FileIsReadOnly";
            var fileToEdit       = $"{_testFolder}\\{testScenarioName}";

            try
            {
                FSTestsFixture.CreateFiles(_testFolder, new List <string> {
                    testScenarioName
                }, true);

                Fs.EnsureFileEditable(fileToEdit);
                var newFileInfo = new FileInfo(fileToEdit);

                Assert.False(newFileInfo.IsReadOnly);
            }
            finally
            {
                _ = new FileInfo(fileToEdit)
                {
                    IsReadOnly = false,
                };
            }
        }
Exemplo n.º 7
0
        public void StartRending(System.IO.DirectoryInfo baseTempDir, List <VocalUtau.Calculators.BarkerCalculator.BgmPreRender> BList, string RendToWav = "")
        {
            _IsRending   = true;
            _ExitRending = false;
            if (RendingStateChange != null)
            {
                RendingStateChange(this);
            }

            string        ProcessIDStr = Process.GetCurrentProcess().Id.ToString();
            DirectoryInfo tempDir      = baseTempDir.CreateSubdirectory("temp");
            DirectoryInfo cacheDir     = baseTempDir.CreateSubdirectory("cache");

            string TrackFileName = tempDir.FullName + "\\Bgm_" + CacheSignal + ".wav";

            FileStream Fs;

            headSize = InitFile(out Fs, TrackFileName);
            Semaphore semaphore = new Semaphore(1, 1, "VocalUtau.WavTool." + ProcessIDStr + ".Bgm_" + CacheSignal);

            for (int i = 0; i < BList.Count; i++)
            {
                if (BList[i].DelayTime > 0)
                {
                    int ByteTime = (int)(IOHelper.NormalPcmMono16_Format.AverageBytesPerSecond * BList[i].DelayTime);
                    ByteTime -= ByteTime % 2;
                    byte[] byteL = new byte[ByteTime];
                    Array.Clear(byteL, 0, ByteTime);
                    Fs.Write(byteL, 0, ByteTime);
                }
                semaphore.WaitOne();
                try
                {
                    int ByteTime = (int)(IOHelper.NormalPcmMono16_Format.AverageBytesPerSecond * BList[i].PassTime);
                    ByteTime -= ByteTime % 2;
                    using (NAudio.Wave.AudioFileReader reader = new NAudio.Wave.AudioFileReader(BList[i].FilePath))
                    {
                        int JumpLoops = ByteTime / 2;
                        using (NAudio.Wave.Wave32To16Stream w16 = new NAudio.Wave.Wave32To16Stream(reader))
                        {
                            using (NAudio.Wave.WaveStream wfmt = new NAudio.Wave.BlockAlignReductionStream(w16))
                            {
                                using (NAudio.Wave.WaveStream wout = new NAudio.Wave.WaveFormatConversionStream(IOHelper.NormalPcmMono16_Format, wfmt))
                                {
                                    while (wout.Position < wout.Length)
                                    {
                                        if (_ExitRending)
                                        {
                                            break;
                                        }
                                        byte[] by = new byte[2];
                                        int    rd = wout.Read(by, 0, 2);
                                        if (JumpLoops > 0)
                                        {
                                            JumpLoops--;
                                        }
                                        else
                                        {
                                            Fs.Write(by, 0, 2);
                                        }

                                        /*  for (int w = 1; w < w16.WaveFormat.Channels; w++)
                                         * {
                                         *    int rdr = w16.Read(by, 0, 2);
                                         * }*/
                                    }
                                }
                            }
                        }
                    }
                }
                catch {; }
                Fs.Flush();
                semaphore.Release();
                if (_ExitRending)
                {
                    break;
                }
            }
            _IsRending = false;
            long total = Fs.Length;

            byte[] head = IOHelper.GenerateHead((int)(total - headSize));
            Fs.Seek(0, SeekOrigin.Begin);
            Fs.Write(head, 0, head.Length);
            Fs.Flush();
            Fs.Close();
            _ExitRending = false;
            if (RendingStateChange != null)
            {
                RendingStateChange(this);
            }
            if (RendToWav != "")
            {
                File.Copy(TrackFileName, RendToWav, true);
                try
                {
                    File.Delete(TrackFileName);
                }
                catch {; }
            }
        }
Exemplo n.º 8
0
 public AzureBlobFileSystemTests()
 {
     this.RootDirectory = Fs.GetDirectory("testroot");
 }
        public async Task EnsureReswResourceInGeneratedProjectsAreUsedAsync(string projectType, string framework, string platform, string language)
        {
            var projectName = $"{projectType}{framework}Resw";

            var resultPath = await GenerateProjectForTestingAsync(projectName, projectType, framework, platform, language);

            var reswFilePath = Path.Combine(resultPath, projectName, "strings", "en-us", "Resources.resw");

            var xdoc = new XmlDocument();

            xdoc.Load(reswFilePath);

            var searchTerms = new List <string>();

            foreach (XmlElement element in xdoc.GetElementsByTagName("data"))
            {
                var interestedPartOfName = element.Attributes["name"].Value;

                if (interestedPartOfName.Contains("."))
                {
                    interestedPartOfName = interestedPartOfName.Substring(0, interestedPartOfName.IndexOf(".", StringComparison.Ordinal));
                }

                if (!searchTerms.Contains(interestedPartOfName))
                {
                    searchTerms.Add(interestedPartOfName);
                }
            }

            foreach (var fileExt in new[] { "*.xaml", "*.appxmanifest", "*.cs" })
            {
                foreach (var file in Directory.GetFiles(resultPath, fileExt, SearchOption.AllDirectories))
                {
                    var fileContents = File.ReadAllText(file);

                    for (var i = searchTerms.Count - 1; i >= 0; i--)
                    {
                        var    usage  = searchTerms[i];
                        string usage2 = null;

                        switch (fileExt)
                        {
                        case "*.appxmanifest":
                            usage  = "ms-resource:" + usage;
                            usage2 = null;
                            break;

                        case "*.cs":
                            usage  = $"\"{usage}\".GetLocalized()";
                            usage2 = usage.Replace("\".Get", "/Header\".Get");
                            break;

                        case "*.xaml":
                            usage  = $"x:Uid=\"{usage}\"";
                            usage2 = null;
                            break;
                        }

                        if (fileContents.Contains(usage))
                        {
                            searchTerms.RemoveAt(i);
                        }

                        if (usage2 != null && fileContents.Contains(usage2))
                        {
                            searchTerms.RemoveAt(i);
                        }
                    }
                }
            }

            Assert.True(searchTerms.Count == 0, $"Unused string resources: {string.Join(", ", searchTerms)}");

            Fs.SafeDeleteDirectory(resultPath);
        }
Exemplo n.º 10
0
 protected static void Copy(string sourceFolder, string targetFolder)
 {
     Fs.SafeDeleteDirectory(targetFolder);
     Fs.CopyRecursive(sourceFolder, targetFolder);
 }
Exemplo n.º 11
0
        private void OpenAllNcas()
        {
            string[] files = Fs.GetFileSystemEntries(ContentsDir, "*.nca", SearchOption.AllDirectories);

            foreach (string file in files)
            {
                Nca nca = null;
                try
                {
                    bool     isNax0;
                    IStorage storage = OpenSplitNcaStream(Fs, file);
                    if (storage == null)
                    {
                        continue;
                    }

                    using (var reader = new BinaryReader(storage.AsStream(), Encoding.Default, true))
                    {
                        reader.BaseStream.Position = 0x20;
                        isNax0 = reader.ReadUInt32() == 0x3058414E; // NAX0
                        reader.BaseStream.Position = 0;
                    }

                    if (isNax0)
                    {
                        string sdPath = "/" + Util.GetRelativePath(file, ContentsDir).Replace('\\', '/');
                        var    nax0   = new Nax0(Keyset, storage, sdPath, false);
                        nca = new Nca(Keyset, nax0.BaseStorage, false);
                    }
                    else
                    {
                        nca = new Nca(Keyset, storage, false);
                    }

                    nca.NcaId = Path.GetFileNameWithoutExtension(file);
                    string extension = nca.Header.ContentType == ContentType.Meta ? ".cnmt.nca" : ".nca";
                    nca.Filename = nca.NcaId + extension;
                }
                catch (MissingKeyException ex)
                {
                    if (ex.Name == null)
                    {
                        Console.WriteLine($"{ex.Message} File:\n{file}");
                    }
                    else
                    {
                        string name = ex.Type == KeyType.Title ? $"Title key for rights ID {ex.Name}" : ex.Name;
                        Console.WriteLine($"{ex.Message}\nKey: {name}\nFile: {file}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{ex.Message} File: {file}");
                }

                if (nca?.NcaId != null)
                {
                    Ncas.Add(nca.NcaId, nca);
                }
            }
        }
Exemplo n.º 12
0
        private static void ScanAFile(FileInfo f)
        {
            Debug.WriteLine(f.FullName);

            Stream fStream;
            int    errorCode = IO.FileStream.OpenFileRead(f.FullName, out fStream);

            if (errorCode != 0)
            {
                return;
            }

            int      offset;
            FileType foundFileType = FileHeaderReader.GetType(fStream, out offset);

            RvFile tFile = UnCompFiles.CheckSumRead(fStream, offset);

            tFile.AltType = foundFileType;

            if (foundFileType == FileType.CHD)
            {
                // need to validate check the CHD file
            }

            // test if needed.
            FindStatus res = fileneededTest(tFile);

            if (res == FindStatus.FileNeededInArchive)
            {
                Debug.WriteLine("Reading file as " + tFile.SHA1);
                GZip gz = new GZip();
                gz.crc              = tFile.CRC;
                gz.md5Hash          = tFile.MD5;
                gz.sha1Hash         = tFile.SHA1;
                gz.uncompressedSize = tFile.Size;

                Stream ds;
                IO.FileStream.OpenFileRead(f.FullName, out ds);
                string outfile = Getfilename(tFile.SHA1);
                gz.WriteGZip(outfile, ds, false);
                ds.Close();
                ds.Dispose();

                tFile.DBWrite();
            }

            if (foundFileType == FileType.ZIP)
            {
                ZipFile fz = new ZipFile();
                fz.ZipFileOpen(f.FullName, f.LastWriteTime, true);
                {
                    for (int i = 0; i < fz.LocalFilesCount(); i++)
                    {
                        // this needs to go back into the Zip library.
                        int    Buffersize = 1024 * 1024;
                        byte[] _buffer    = new byte[Buffersize];
                        Stream stream;
                        ulong  streamSize;
                        ushort compressionMethod;
                        fz.ZipFileOpenReadStream(i, false, out stream, out streamSize, out compressionMethod);
                        string file = @"C:\RomVaultX\" + Guid.NewGuid();
                        Stream Fs;
                        IO.FileStream.OpenFileWrite(file, out Fs);
                        ulong sizetogo = streamSize;
                        while (sizetogo > 0)
                        {
                            int sizenow = sizetogo > (ulong)Buffersize ? Buffersize : (int)sizetogo;
                            stream.Read(_buffer, 0, sizenow);
                            Fs.Write(_buffer, 0, sizenow);
                            sizetogo -= (ulong)sizenow;
                        }
                        Fs.Close();
                        stream.Close();

                        FileInfo fi = new FileInfo(file);
                        ScanAFile(fi);
                        File.Delete(file);
                    }
                }
            }
            if (foundFileType == FileType.GZ)
            {
            }
        }
Exemplo n.º 13
0
 protected void WritePageList(Fs appFs, string[] pageNames)
 {
     appFs.WriteFile(PagesPath, pageNames.ToJson(true));
 }
Exemplo n.º 14
0
        public async Task EnsureFrameworkLaunchPageVisualsAreEquivalentAsync(string projectType, string page, string[] frameworks)
        {
            var genIdentities = new[] { page };

            var noClickCount = 0;

            if (page == "wts.Page.Map")
            {
                noClickCount = 1;
            }
            else if (page == "wts.Page.Camera")
            {
                noClickCount = 2;
            }

            ExecutionEnvironment.CheckRunningAsAdmin();
            WinAppDriverHelper.CheckIsInstalled();

            // MVVMBasic is considered the reference version. Compare generated apps with equivalent in other frameworks
            var refAppDetails = await SetUpProjectForUiTestComparisonAsync(ProgrammingLanguages.CSharp, projectType, "MVVMBasic", genIdentities, lastPageIsHome : true, createForScreenshots : true);

            var otherProjDetails = new VisualComparisonTestDetails[frameworks.Length];

            bool allTestsPassed = true;

            var outputMessages = string.Empty;

            for (int i = 0; i < frameworks.Length; i++)
            {
                string framework = frameworks[i];
                otherProjDetails[i] = await SetUpProjectForUiTestComparisonAsync(ProgrammingLanguages.CSharp, projectType, framework, genIdentities, lastPageIsHome : true, createForScreenshots : true);

                var testProjectDetails = SetUpTestProjectForInitialScreenshotComparison(refAppDetails, otherProjDetails[i], GetExclusionAreasForVisualEquivalencyTest(projectType, page), noClickCount);

                var(testSuccess, testOutput) = RunWinAppDriverTests(testProjectDetails);

                if (testSuccess)
                {
                    UninstallAppx(otherProjDetails[i].PackageFullName);

                    RemoveCertificate(otherProjDetails[i].CertificatePath);

                    // Parent of images folder also contains the test project
                    Fs.SafeDeleteDirectory(Path.Combine(testProjectDetails.imagesFolder, ".."));
                }
                else
                {
                    allTestsPassed = false;

                    if (Directory.Exists(testProjectDetails.imagesFolder) &&
                        Directory.GetFiles(testProjectDetails.imagesFolder, "*.*-Diff.png").Any())
                    {
                        outputMessages += $"Failing test images in {testProjectDetails.imagesFolder}{Environment.NewLine}{Environment.NewLine}{outputMessages}";
                    }
                    else
                    {
                        outputMessages += $"{Environment.NewLine}{string.Join(Environment.NewLine, testOutput)}";
                    }
                }
            }

            if (allTestsPassed)
            {
                UninstallAppx(refAppDetails.PackageFullName);

                RemoveCertificate(refAppDetails.CertificatePath);
            }

            Assert.True(allTestsPassed, outputMessages.TrimStart());
        }
Exemplo n.º 15
0
        static async Task TestCache1()
        {
            var visitor = Fs.NewVisitor("visitor_5678")
                          .WithContext(new Dictionary <string, object> {
                ["plan"] = "premium"
            }).Build();


            await visitor.FetchFlags();

            var flag = visitor.GetFlag("myAwesomeFeature", 1);

            Console.WriteLine("flagValue: {0}", flag.GetValue());

            await visitor.SendHit(new Screen("Screen 1"));

            Console.WriteLine("Go offline");
            Console.ReadKey();

            await visitor.SendHit(new Screen("Screen 2"));

            await visitor.SendHit(new Event(EventCategory.ACTION_TRACKING, "event 1"));

            await visitor.GetFlag("perso_value", 1).UserExposed();

            Console.WriteLine("Go online");
            Console.ReadKey();

            await visitor.FetchFlags();

            visitor = Fs.NewVisitor("visitor_5678")
                      .WithContext(new Dictionary <string, object>
            {
                ["plan"] = "premium"
            }).IsAuthenticated(true).HasConsented(true).Build();

            await visitor.FetchFlags();

            flag = visitor.GetFlag("myAwesomeFeature", 1);

            Console.WriteLine("flagValue: {0}", flag.GetValue());

            Console.WriteLine("update context");
            Console.ReadKey();

            visitor.UpdateContext(new Dictionary <string, object>
            {
                ["plan"] = "enterprise"
            });

            await visitor.FetchFlags();

            Console.WriteLine("flagValue: {0}", flag.GetValue());

            Console.WriteLine("SetConsent false");
            Console.ReadKey();

            visitor.SetConsent(false);

            await visitor.SendHit(new Screen("Screen 3"));

            Console.WriteLine("SetConsent true");
            Console.ReadKey();
            visitor.SetConsent(true);
            await visitor.FetchFlags();

            Console.WriteLine("Go offline");
            Console.ReadKey();

            visitor.UpdateContext(new Dictionary <string, object>
            {
                ["plan"] = "enterprise"
            });

            await visitor.FetchFlags();

            flag = visitor.GetFlag("myAwesomeFeature", 1);

            Console.WriteLine("flagValue: {0}", flag.GetValue());

            Console.WriteLine("Go offline");
            Console.ReadKey();

            await visitor.SendHit(new Screen("Screen 4"));

            visitor.SetConsent(false);

            Console.WriteLine("Go online");
            Console.WriteLine("Enable panic mode");
            Console.ReadKey();

            await visitor.FetchFlags();

            visitor.SetConsent(true);

            await visitor.SendHit(new Event(EventCategory.USER_ENGAGEMENT, "Event 2"));

            await visitor.SendHit(new Transaction("#12345", "affiliation")
            {
                Taxes          = 19.99,
                Currency       = "USD",
                CouponCode     = "code",
                ItemCount      = 1,
                ShippingMethod = "road",
                ShippingCosts  = 5,
                PaymentMethod  = "credit_card",
                TotalRevenue   = 199.99
            });

            await visitor.SendHit(new Item("#12345", "product", "sku123")
            {
                Price    = 199.99,
                Quantity = 1,
                Category = "test",
            });

            await visitor.SendHit(new Event(EventCategory.ACTION_TRACKING, "click")
            {
                Label = "label",
                Value = 100,
            });

            await visitor.FetchFlags();

            Console.WriteLine("Disabled panic mode");
            Console.ReadKey();

            await visitor.FetchFlags();

            flag = visitor.GetFlag("myAwesomeFeature", 1);

            Console.WriteLine("flagValue: {0}", flag.GetValue());
        }
 //关闭词法分析器
 public static void CloseScanner()
 {
     Fs?.Close();
 }
Exemplo n.º 17
0
 public void SafeMoveFile_OriginFileDoesNotExist_JustReturns(string filePath, string newfilePath)
 {
     Fs.SafeMoveFile(filePath, newfilePath);
 }
Exemplo n.º 18
0
 /// <summary>
 /// Define the fulltext content
 /// </summary>
 /// <returns></returns>
 public override Return LoadBlobDocument()
 {
     //set fulltext
     Blob = Fs.StrToBlob(cntr.transformText(message.ValueStr("text"), false));
     return(base.LoadBlobDocument());
 }
Exemplo n.º 19
0
 public S3FileSystem(string bucketName, IDataDirectoryProvider dataDirectoryProvider, AmazonS3Client amazonS3Client) : base(dataDirectoryProvider, new S3FileService(bucketName, amazonS3Client))
 {
     BucketName = DefaultBucketName;
     Repository = new DaoRepository();
     LocalFs    = new Fs(DataDirectoryProvider.GetFilesDirectory());
 }
Exemplo n.º 20
0
 public void SafeDeleteDirectory_DirectoryPathIsNullOrEmpty_ShouldNotThrowException(string rootDir)
 {
     Fs.SafeDeleteDirectory(rootDir);
 }
Exemplo n.º 21
0
 protected void WriteBook(Fs appFs, WebBook webBook)
 {
     appFs.WriteFile(BooksPath._Format(webBook.Name), webBook.ToJson(true), true);
 }
 internal double DegreeAtValue(double val)
 {
     return(Fs.DegreeAtValue(val));
 }
        protected async Task <string> AssertGenerateRightClickAsync(string projectName, string projectType, string framework, string language, bool cleanGeneration = true)
        {
            await SetUpFixtureForTestingAsync(language);

            ProjectName = projectName;
            ProjectPath = Path.Combine(_fixture.TestNewItemPath, projectName, projectName);
            OutputPath  = ProjectPath;

            var userSelection = await GenerationFixture.SetupProjectAsync(projectType, framework, language);

            await NewProjectGenController.Instance.UnsafeGenerateProjectAsync(userSelection);

            var emptyProject = Path.Combine(_fixture.TestNewItemPath, projectName);

            // Assert on project
            Assert.True(Directory.Exists(emptyProject));

            int emptyProjecFileCount = Directory.GetFiles(emptyProject, "*.*", SearchOption.AllDirectories).Count();

            Assert.True(emptyProjecFileCount > 2);

            // Add new items
            var rightClickTemplates = GenerationFixture.Templates.Where(
                t => (t.GetTemplateType() == TemplateType.Feature || t.GetTemplateType() == TemplateType.Page) &&
                t.GetFrameworkList().Contains(framework) &&
                !t.GetIsHidden() &&
                t.GetRightClickEnabled());

            foreach (var item in rightClickTemplates)
            {
                OutputPath = GenContext.GetTempGenerationPath(projectName);

                var newUserSelection = new UserSelection
                {
                    ProjectType        = projectType,
                    Framework          = framework,
                    HomeName           = "",
                    Language           = language,
                    ItemGenerationType = ItemGenerationType.GenerateAndMerge
                };

                GenerationFixture.AddItem(newUserSelection, item, GenerationFixture.GetDefaultName);

                await NewItemGenController.Instance.UnsafeGenerateNewItemAsync(item.GetTemplateType(), newUserSelection);

                NewItemGenController.Instance.UnsafeFinishGeneration(newUserSelection);
            }

            var finalProjectPath      = Path.Combine(_fixture.TestNewItemPath, projectName);
            int finalProjectFileCount = Directory.GetFiles(finalProjectPath, "*.*", SearchOption.AllDirectories).Count();

            Assert.True(finalProjectFileCount > emptyProjecFileCount);

            // Clean
            if (cleanGeneration)
            {
                Fs.SafeDeleteDirectory(finalProjectPath);
            }

            return(finalProjectPath);
        }
        public void GetExistingFolderNames_RootDirectoryEmptyOrNull_ShouldReturnEmptyList(string rootDirectory)
        {
            var actual = Fs.GetExistingFolderNames(rootDirectory);

            Assert.Empty(actual);
        }
Exemplo n.º 25
0
        public UserFile CreateUserFile(string path = "", string alt = "", string caption = "")
        {
            var userFileRecord = new EntityRecord();

            if (path.StartsWith("/fs"))
            {
                path = path.Substring(3);
            }
            var tempFile = Fs.Find(path);

            if (tempFile == null)
            {
                throw new Exception("File not found on that path");
            }
            var newFileId = Guid.NewGuid();

            userFileRecord["id"]      = newFileId;
            userFileRecord["alt"]     = alt;
            userFileRecord["caption"] = caption;
            var fileKilobytes = Math.Round(((decimal)tempFile.GetBytes().Length / 1024), 2);

            userFileRecord["size"] = fileKilobytes;
            userFileRecord["name"] = Path.GetFileName(path);
            var fileExtension = Path.GetExtension(path);
            var mimeType      = MimeMapping.GetMimeMapping(path);

            if (mimeType.StartsWith("image"))
            {
                var dimensionsRecord = Helpers.GetImageDimension(tempFile.GetBytes());
                userFileRecord["width"]  = (decimal)dimensionsRecord["width"];
                userFileRecord["height"] = (decimal)dimensionsRecord["height"];
                userFileRecord["type"]   = "image";
            }
            else if (mimeType.StartsWith("video"))
            {
                userFileRecord["type"] = "video";
            }
            else if (mimeType.StartsWith("audio"))
            {
                userFileRecord["type"] = "audio";
            }
            else if (fileExtension == ".doc" || fileExtension == ".docx" || fileExtension == ".odt" || fileExtension == ".rtf" ||
                     fileExtension == ".txt" || fileExtension == ".pdf" || fileExtension == ".html" || fileExtension == ".htm" || fileExtension == ".ppt" ||
                     fileExtension == ".pptx" || fileExtension == ".xls" || fileExtension == ".xlsx" || fileExtension == ".ods" || fileExtension == ".odp")
            {
                userFileRecord["type"] = "document";
            }
            else
            {
                userFileRecord["type"] = "other";
            }

            var newFilePath = $"/file/{newFileId}/{Path.GetFileName(path)}";

            using (DbConnection con = DbContext.Current.CreateConnection())
            {
                con.BeginTransaction();
                try
                {
                    var file = Fs.Move(path, newFilePath, false);
                    if (file == null)
                    {
                        throw new Exception("File move from temp folder failed");
                    }

                    userFileRecord["path"] = newFilePath;
                    var response = RecMan.CreateRecord("user_file", userFileRecord);
                    if (!response.Success)
                    {
                        throw new Exception(response.Message);
                    }

                    userFileRecord = response.Object.Data.First();
                    con.CommitTransaction();
                }
                catch (Exception ex)
                {
                    con.RollbackTransaction();
                    throw ex;
                }
            }
            return(userFileRecord.MapTo <UserFile>());
        }
Exemplo n.º 26
0
 /// <summary>
 ///  Write 16-bit value to output stream, LSB first
 /// </summary>
 /// <param name="value"></param>
 protected void WriteShort(int value)
 {
     Fs.WriteByte(Convert.ToByte(value & 0xff));
     Fs.WriteByte(Convert.ToByte((value >> 8) & 0xff));
 }
        public async Task EnsureDefinedUidsHaveResourceEntriesAsync(string projectType, string framework, string platform, string language)
        {
            var projectName = $"{projectType}{framework}Uids";

            var resultPath = await GenerateProjectForTestingAsync(projectName, projectType, framework, platform, language);

            var reswFilePath = Path.Combine(resultPath, projectName, "strings", "en-us", "Resources.resw");

            var uidsWithoutResources = new List <string>();

            var xdoc = new XmlDocument();

            xdoc.Load(reswFilePath);

            var resources = new List <string>();

            foreach (XmlElement element in xdoc.GetElementsByTagName("data"))
            {
                var interestedPartOfName = element.Attributes["name"].Value;

                if (interestedPartOfName.Contains("."))
                {
                    interestedPartOfName = interestedPartOfName.Substring(0, interestedPartOfName.IndexOf(".", StringComparison.Ordinal));
                }

                if (!resources.Contains(interestedPartOfName))
                {
                    resources.Add(interestedPartOfName);
                }
            }

            foreach (var file in Directory.GetFiles(resultPath, "*.xaml", SearchOption.AllDirectories))
            {
                var fileContents = File.ReadAllText(file);

                if (fileContents.Contains("x:Uid"))
                {
                    var keepSearching = true;

                    var pos = 0;

                    while (keepSearching)
                    {
                        pos = fileContents.IndexOf("x:Uid=\"", pos + 1, StringComparison.Ordinal);

                        if (pos >= 0)
                        {
                            var uid = fileContents.Substring(pos + 7, fileContents.IndexOf("\"", pos + 7, StringComparison.Ordinal) - pos - 7);

                            if (!resources.Contains(uid))
                            {
                                uidsWithoutResources.Add(uid);
                            }
                        }
                        else
                        {
                            keepSearching = false;
                        }
                    }
                }
            }

            var validExceptions = new[] { "CameraPage_CameraControl", "PivotPage" };

            foreach (var validException in validExceptions)
            {
                uidsWithoutResources.Remove(validException);
            }

            Assert.True(uidsWithoutResources.Count == 0, $"Uids without string resources: {string.Join(", ", uidsWithoutResources)}");

            Fs.SafeDeleteDirectory(resultPath);
        }
Exemplo n.º 28
0
 public void SafeDeleteFile_PathNotFound_ShouldNotThrowException(string filePath)
 {
     Fs.SafeDeleteFile(filePath);
 }
Exemplo n.º 29
0
        /// <summary>
        /// Validate the parameter. Error messages are added to the errors collection
        /// if there are issues with the parameter.
        /// </summary>
        public void Validate(IHttpPostParam parameter, ArrayRig <string> errors)
        {
            // is default validatation enabled?
            if (DefaultValidation)
            {
                // yes, is the parameter required?
                bool required = this._attributes.ContainsKey("required");

                if (required)
                {
                    // yes, was the parameter retrieved?
                    if (parameter == null)
                    {
                        // no, add an error
                        errors.Add("Missing a required parameter.");

                        // is the custom validation set?
                        if (OnValidate != null)
                        {
                            // yes, run the custom validation
                            OnValidate.Add(parameter, errors);
                            OnValidate.Run();
                        }

                        return;
                    }
                }
                else if (parameter == null)
                {
                    return;
                }

                string name;

                // validate the input value name
                if (parameter.Params.TryGetValue("name", out name))
                {
                    if (!name.Equals(this["name"], StringComparison.Ordinal))
                    {
                        errors.Add("Input element name mismatch.");
                        return;
                    }
                }
                else
                {
                    name = this["name"];
                    if (name == null)
                    {
                        errors.Add("Attribute 'name' missing.");
                        return;
                    }
                }

                // has the friendly name been assigned? yes, replace it in messages.
                if (!string.IsNullOrEmpty(FriendlyName))
                {
                    name = FriendlyName;
                }

                // get the post parameter as its correct type
                HttpPostParam <string>           paramString = parameter as HttpPostParam <string>;
                HttpPostParam <ArrayRig <byte> > paramBinary = null;
                if (paramString == null)
                {
                    paramBinary = parameter as HttpPostParam <ArrayRig <byte> >;
                }
                else if (string.IsNullOrEmpty(paramString.Value))
                {
                    // is the parameter required? yes, add an error
                    if (required)
                    {
                        errors.Add(name + " is required.");
                    }
                    // no, skip validation
                    else
                    {
                        return;
                    }
                }
                else if (paramString.Value.Length > MaxLength)
                {
                    errors.Add("Exceeded maximum characters (" + MaxLength + ") for " + name + ".");
                    return;
                }
                else if (paramString.Value.Length < MinLength)
                {
                    errors.Add("Entered value was shorter than the minimum length (" + MinLength + ") for " + name + ".");
                    return;
                }
                else if (Regex != null && !Regex.IsMatch(paramString.Value))
                {
                    // has the title for the input been specified?
                    errors.Add(this["title"] ?? "Invalid entry for " + name + ".");
                    return;
                }

                if ((paramString == null || paramString.Value == string.Empty) &&
                    (paramBinary == null || paramBinary.Value.Count == 0))
                {
                    if (required || _type == InputType.Hidden)
                    {
                        errors.Add(name + " is required.");
                    }
                    return;
                }

                // perform default validation based on type
                switch (_type)
                {
                case InputType.Checkbox:
                    if (paramString == null)
                    {
                        errors.Add(name + " is required.");
                        return;
                    }
                    if (!paramString.Value.Equals(this["value"]))
                    {
                        errors.Add(name + " has an incorrect value.");
                        return;
                    }
                    break;

                case InputType.Color:
                    if (paramString == null)
                    {
                        errors.Add("Please select a color for " + name + ".");
                        return;
                    }
                    WebColor color;
                    if (!WebColor.TryParse(paramString.Value, out color))
                    {
                        errors.Add("Incorrect hexadecimal color format. Should be #XXXXXXXX or #XXXXXX or #XXX.");
                        return;
                    }
                    break;

                case InputType.Date:
                    if (paramString == null)
                    {
                        errors.Add("Please select " + name + ".");
                        return;
                    }
                    DateTime date;
                    if (!DateTime.TryParse(paramString.Value, out date))
                    {
                        errors.Add("Received an incorrect date format.");
                        return;
                    }
                    break;

                case InputType.DatetimeLocal:
                    if (paramString == null)
                    {
                        errors.Add("Please select a date-time for " + name + ".");
                        return;
                    }
                    DateTime dateTime;
                    if (!DateTime.TryParse(paramString.Value, out dateTime))
                    {
                        errors.Add("Received an incorrect date-time format.");
                        return;
                    }
                    break;

                case InputType.Email:
                    if (paramString == null)
                    {
                        errors.Add(name + " is required.");
                        return;
                    }
                    if (!Efz.Validate.Email(paramString.Value))
                    {
                        errors.Add("Email appears malformed.");
                        return;
                    }
                    break;

                case InputType.File:
                    if (paramBinary == null)
                    {
                        errors.Add("You didn't choose a file for " + name + ".");
                        return;
                    }
                    if (paramBinary.Value.Count == 0)
                    {
                        errors.Add("Required file parameter is missing.");
                    }
                    string filename;
                    if (!paramBinary.Params.TryGetValue("filename", out filename) ||
                        !Fs.ParseFileName(ref filename))
                    {
                        errors.Add("The file name of " + name + " was invalid.");
                        return;
                    }
                    // ensure the content type matches accepted types
                    string contentType;
                    if (!paramBinary.Params.TryGetValue("content-type", out contentType))
                    {
                        errors.Add("Content type of " + name + " was not provided.");
                        return;
                    }
                    // check the accepted file types
                    string accepted;
                    if (_attributes.TryGetValue("accept", out accepted))
                    {
                        var extension = Mime.GetExtension(contentType);
                        if (extension == string.Empty)
                        {
                            errors.Add("Content type '" + contentType + "' was invalid.");
                            return;
                        }
                        if (!accepted.Contains(Chars.Stop + extension + Chars.Comma) && !accepted.EndsWith(Chars.Stop + extension, StringComparison.Ordinal))
                        {
                            errors.Add("Accepted file types include '" + accepted + "'.");
                            return;
                        }
                    }
                    break;

                case InputType.Month:
                    if (paramString == null)
                    {
                        errors.Add("You didn't choose a month for " + name + ".");
                        return;
                    }
                    if (paramString.Value.Length != 7 || !RegexMonth.IsMatch(paramString.Value))
                    {
                        errors.Add(name + " seems malformed.");
                        return;
                    }
                    if (paramString.Value[4] == Chars.Dash)
                    {
                        paramString.Value = paramString.Value.Substring(5) + Chars.Dash + paramString.Value.Substring(0, 4);
                    }
                    break;

                case InputType.Number:
                    int number;
                    if (!int.TryParse(paramString.Value, out number))
                    {
                        errors.Add("The " + name + " seems malformed.");
                        return;
                    }
                    if (_attributes.ContainsKey("min"))
                    {
                        int min = _attributes["min"].ToInt32();
                        if (number < min)
                        {
                            errors.Add(name + " was not within a valid range.");
                            return;
                        }
                    }
                    if (_attributes.ContainsKey("max"))
                    {
                        int max = _attributes["max"].ToInt32();
                        if (number > max)
                        {
                            errors.Add(name + " was not within a valid range.");
                            return;
                        }
                    }
                    if (_attributes.ContainsKey("step"))
                    {
                        int step = _attributes["step"].ToInt32();
                        if (number % step != 0)
                        {
                            errors.Add(name + " was not a valid value.");
                            return;
                        }
                    }
                    break;

                case InputType.Password:
                    if (paramString == null)
                    {
                        errors.Add(name + " is required.");
                        return;
                    }
                    if (!RegexPassword.IsMatch(paramString.Value))
                    {
                        errors.Add("Enter a password with at least four(4) characters.");
                        return;
                    }
                    break;

                case InputType.Range:
                    if (paramString == null)
                    {
                        errors.Add("Value required for " + name + ".");
                        return;
                    }
                    int range;
                    if (!int.TryParse(paramString.Value, out range))
                    {
                        errors.Add("Invalid " + name + " value received.");
                        return;
                    }
                    if (_attributes.ContainsKey("min"))
                    {
                        int min = _attributes["min"].ToInt32();
                        if (range < min)
                        {
                            errors.Add(name + " was not within a valid range.");
                            return;
                        }
                    }
                    if (_attributes.ContainsKey("max"))
                    {
                        int max = _attributes["max"].ToInt32();
                        if (range > max)
                        {
                            errors.Add(name + " was not within a valid range.");
                            return;
                        }
                    }
                    if (_attributes.ContainsKey("step"))
                    {
                        int step = _attributes["step"].ToInt32();
                        if (range % step != 0)
                        {
                            errors.Add(name + " was not a valid value.");
                            return;
                        }
                    }
                    break;

                case InputType.Tel:
                    if (paramString == null)
                    {
                        errors.Add(name + " is required.");
                        return;
                    }
                    if (!Efz.Validate.PhoneNumber(paramString.Value))
                    {
                        errors.Add(name + " was suspected of being invalid.");
                        return;
                    }
                    break;

                case InputType.Text:
                    if (paramString == null || paramString.Value.Length == 0)
                    {
                        errors.Add(name + " is required.");
                        return;
                    }
                    break;

                case InputType.Time:
                    if (paramString == null)
                    {
                        errors.Add(name + " is required.");
                        return;
                    }
                    if (paramString.Value.Length != 5 || !RegexTime.IsMatch(paramString.Value))
                    {
                        errors.Add(name + " was found to be invalid.");
                        return;
                    }
                    break;

                case InputType.Url:
                    if (paramString == null)
                    {
                        errors.Add(name + " is required.");
                        return;
                    }
                    if (paramString.Value.Length < 4 || paramString.Value.Length > 200 ||
                        !RegexUrl.IsMatch(paramString.Value))
                    {
                        errors.Add("Url was invalid.");
                        return;
                    }
                    break;

                case InputType.Week:
                    if (paramString == null)
                    {
                        errors.Add("Please select " + name + ".");
                        return;
                    }
                    if (paramString.Value.Length != 8 || !RegexWeek.IsMatch(paramString.Value))
                    {
                        errors.Add(name + " was malformed.");
                        return;
                    }
                    break;
                }
            }

            // is the custom validation set? no, complete
            if (OnValidate == null)
            {
                return;
            }

            // run the custom validation
            OnValidate.Add(parameter, errors);
            OnValidate.Run();
        }
Exemplo n.º 30
0
        public static void Main(string[] args)
        {
            /*
             * First thing you need to do is initialize the filesystem.  You simply call
             * PHYSFS_init();
             * to do this.
             *
             * From the docs:
             * argv0 the argv[0] string passed to your program's mainline. This may be NULL
             * on most platforms (such as ones without a standard main() function), but you
             * should always try to pass something in here. Unix-like systems such as Linux
             * _need_ to pass argv[0] from main() in here.
             */
            Fs.PHYSFS_init("init");

            /*
             * After you have it initialized, then you need to set up any archives that
             * will be read from.  You can do this by using the
             * PHYSFS_AddToSearchPath(char*, int); function.  The 1 makes it added to the
             * end of the search path so that it is the last looked at.  You could instead
             * put a 0 there and have it be the first thing looked at.
             */
            Fs.PHYSFS_addToSearchPath(@"..\..\Data\myzip.zip", 1);
            Fs.PHYSFS_addToSearchPath(@".\Data\myzip.zip", 1);

            /*
             * Now that we have initialized physfs and added an archive to its search path,
             * we can do some file reading.  First thing you will want to do is check to
             * make sure that the file exists.  You can do this by calling
             * PHYSFS_exists(char*);
             */
            Console.WriteLine("Exists: " + Fs.PHYSFS_exists("myfile.txt"));

            /*
             * Then you can use PHYSFS_openRead(char*); to get a PHYSFS_file pointer to
             * that file.  There is also available: PHYSFS_openWrite(char*); and
             * PHYSFS_openAppend(char*);
             *
             * NOTE: If you would like to do any writing you need to set a dir to write
             * too.  You can do this by using PHYSFS_setWriteDir(const char *newDir);
             */
            IntPtr myfile = Fs.PHYSFS_openRead("myfile.txt");

            /*
             * If you are going to be reading this file into memory, you can use
             * PHYSFS_fileLength(PHYSFS_file*) to find out how many bytes you need to
             * allocate for the file.  You can also use this to check and make sure the
             * file isn't larger than the max file size you want to open.
             */
            long file_size = Fs.PHYSFS_fileLength(myfile);

            Console.WriteLine("Filesize: " + file_size);

            /*
             * Now it is time to read the file into memory.  In this tutorial I am simply
             * going to read it all into a byte array using PHYSFS_read (PHYSFS_file *fp,
             * your_buffer, size_of_object_to_read, number_of_objects_to_read); and it
             * returns the number of objects read.
             */
            byte[] array;
            Fs.PHYSFS_read(myfile, out array, 1, (uint)file_size);
            for (int i = 0; i < array.Length; i++)
            {
                Console.Write((char)array[i]);
            }

            /*
             * When you are finished with your file you need to close it.  You can do so
             * with the function PHYSFS_close(PHYSFS_file*);
             */
            Fs.PHYSFS_close(myfile);

            /*
             * When you are finished with PHYSFS completely, you need to call the
             * PHYSFS_deinit(void) function.
             *
             * From the docs:
             * This closes any files opened via PhysicsFS, blanks the search/write paths,
             * frees memory, and invalidates all of your file handles.
             */
            Fs.PHYSFS_deinit();

            /*
             * Ok that is it for the tutorial.  It should give you a rough overview of how
             * things are structured and you can check the online docs for more information
             * on using the rest of the API.
             */
            Console.ReadLine();
        }