Esempio n. 1
0
        public DatabaseContext() : base(new SQLiteConnection
        {
            ConnectionString = new SQLiteConnectionStringBuilder
            {
                DataSource  = Path.Combine(Config.Server.AuditFilePath, "auditDB.db"),
                ForeignKeys = true
            }.ConnectionString
        }, true)
        {
            var userPrinciple = Common.Utilities.ServerUser;

            Common.Utilities.PerformActionInsideImpersonatedContext(userPrinciple, () =>
            {
                this.Configuration.AutoDetectChangesEnabled = false;
                this.Configuration.ValidateOnSaveEnabled    = false;
                var directoryWrapper = new DirectoryWrapper();
                directoryWrapper.CreateIfNotExists(Config.Server.AuditFilePath);
                DbConfiguration.SetConfiguration(new SQLiteConfiguration());
                this.Database.CreateIfNotExists();
                this.Database.Initialize(false);
                this.Database.ExecuteSqlCommand("CREATE TABLE IF NOT EXISTS \"AuditLog\" ( `Id` INTEGER PRIMARY KEY AUTOINCREMENT, `WorkflowID` TEXT, `WorkflowName` TEXT, `ExecutionID` TEXT, `VersionNumber` TEXT, `AuditType` TEXT, `PreviousActivity` TEXT, `PreviousActivityType` TEXT, `PreviousActivityID` TEXT, `NextActivity` TEXT, `NextActivityType` TEXT, `NextActivityID` TEXT, `ServerID` TEXT, `ParentID` TEXT, `ClientID` TEXT, `ExecutingUser` TEXT, `ExecutionOrigin` INTEGER, `ExecutionOriginDescription` TEXT, `ExecutionToken` TEXT, `AdditionalDetail` TEXT, `IsSubExecution` INTEGER, `IsRemoteWorkflow` INTEGER, `Environment` TEXT, `AuditDate` TEXT )");
                this.Configuration.AutoDetectChangesEnabled = false;
                this.Configuration.ValidateOnSaveEnabled    = false;
            });
        }
        private void AddPreloadCode(DirectoryWrapper data, int index, WebControl imgCtrl)
        {
            const string scriptKey = "ImagePreload";

            if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptKey))
            {
                string script = "<script language=\"JavaScript\">\n"
                                + "function PreLoadSiblings()\n{\n";

                // Script for the Next end the previous picture, to load them to the browser cache.
                if (index > 0)
                {
                    ImageWrapper i    = data.Images[index - 1] as ImageWrapper;
                    string       path = ResolveUrl(i.WebImageHref);
                    script += "objImageNext = new Image(); objImageNext.src='" + path + "';\n";
                }
                if (index < data.Images.Count - 1)
                {
                    ImageWrapper i    = data.Images[index + 1] as ImageWrapper;
                    string       path = ResolveUrl(i.WebImageHref);
                    script += "objImageNext = new Image(); objImageNext.src='" + path + "';\n";
                }

                script += "}\n</script>";

                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), scriptKey, script);

                // Register the Script for the event when the main Image is loaded.
                imgCtrl.Attributes.Add("onload", "PreLoadSiblings()");
            }
        }
Esempio n. 3
0
        public void GetLastesFileWithSameName_TenFilesWithSameNameExist_FileNameWithNumberNine()
        {
            // Arrange
            string fileName = "somefilename";

            File.WriteAllText(Path.Combine(WorkingPath, fileName + ".txt"), "");
            for (int i = 1; i < 10; i++)
            {
                File.WriteAllText(Path.Combine(WorkingPath, fileName + i + ".txt"), "");
            }

            var fileSizeComparatorMock = new Mock <IFileSizeComparator>();
            var fileNameCreatorMock    = new Mock <IFileNameCreator>();
            var directoryWrapper       = new DirectoryWrapper();

            var fileAnalyzer = new FileAnalyzer(fileSizeComparatorMock.Object, fileNameCreatorMock.Object, directoryWrapper)
            {
                LogPath  = WorkingPath,
                FileName = fileName + ".txt"
            };

            // Act
            var result = fileAnalyzer.GetLastesFileWithSameName();

            // Assert
            Assert.AreEqual(fileName + "9" + ".txt", Path.GetFileName(result));
        }
Esempio n. 4
0
        [PrincipalPermission(SecurityAction.Demand)]  // Principal must be authenticated
        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            CustomContainer.Register <IFieldAndPropertyMapper>(new FieldAndPropertyMapper());

            ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;

            Task.Factory.StartNew(() =>
            {
                var dir  = new DirectoryWrapper();
                var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), GlobalConstants.Warewolf, "Feedback");
                dir.CleanUp(path);
                dir.CleanUp(Path.Combine(GlobalConstants.TempLocation, GlobalConstants.Warewolf, "Debug"));
            });

            var localprocessGuard = new Mutex(true, GlobalConstants.WarewolfStudio, out bool createdNew);

            if (createdNew)
            {
                _processGuard = localprocessGuard;
            }
            else
            {
                Environment.Exit(Environment.ExitCode);
            }

            InitializeShell(e);
#if !(DEBUG)
            var versionChecker = new VersionChecker();
            if (versionChecker.GetNewerVersion())
            {
                WebLatestVersionDialog dialog = new WebLatestVersionDialog();
                dialog.ShowDialog();
            }
#endif
        }
Esempio n. 5
0
        public static Dictionary <string, JObject> ProcessCSVDirectory(DirectoryWrapper csvDirWrapper, DirectoryWrapper jsonDirWrapper)
        {
            DirectoryInfo csvDir  = csvDirWrapper.CreateInfo();
            DirectoryInfo jsonDir = jsonDirWrapper.CreateInfo();

            if (!csvDir.Exists)
            {
                throw new ArgumentException("Directory does not exist: " + csvDir + ".");
            }

            if (!jsonDir.Exists)
            {
                throw new ArgumentException("Directory does not exist: " + jsonDir + ".");
            }

            Dictionary <string, JObject> processedCsv = new Dictionary <string, JObject>();

            foreach (FileInfo csvFile in csvDir.GetFiles())
            {
                FileWrapper csvWrapper = new FileWrapper(csvFile);
                JObject     tableCsv   = ProcessCSV(csvWrapper);

                processedCsv.Add(csvWrapper.FullName, tableCsv);
            }

            return(processedCsv);
        }
Esempio n. 6
0
        public void GetLastesFileWithSameName_ThreeFilesExistWithSameNameButNumberNotOrdered_FileNameWithHigherNumber()
        {
            // Arrange
            string fileName = "somefilename";

            int higherNumber = 25;

            File.WriteAllText(Path.Combine(WorkingPath, fileName + higherNumber + ".txt"), "");
            File.WriteAllText(Path.Combine(WorkingPath, fileName + "5" + ".txt"), "");
            File.WriteAllText(Path.Combine(WorkingPath, fileName + "20" + ".txt"), "");

            var fileSizeComparatorMock = new Mock <IFileSizeComparator>();
            var fileNameCreatorMock    = new Mock <IFileNameCreator>();
            var directoryWrapper       = new DirectoryWrapper();

            var fileAnalyzer = new FileAnalyzer(fileSizeComparatorMock.Object, fileNameCreatorMock.Object, directoryWrapper)
            {
                LogPath  = WorkingPath,
                FileName = fileName + ".txt"
            };

            // Act
            var result = fileAnalyzer.GetLastesFileWithSameName();

            // Assert
            Assert.AreEqual(fileName + higherNumber + ".txt", Path.GetFileName(result));
        }
Esempio n. 7
0
        private void PlayMidi(object sender, EventArgs e)
        {
            WindowsMediaPlayer wmp = new WindowsMediaPlayer();

            wmp.URL              = DirectoryWrapper.GetPathCurrentSolution() + "/finalmidi.mid";
            wmp.PlayStateChange += new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange);
        }
Esempio n. 8
0
 void TestSetup(out IFile fileWrapper, out IDirectory directoryWrapper, out Mock <IDev2Activity> activity)
 {
     SetupDataObject();
     fileWrapper      = new FileWrapper();
     directoryWrapper = new DirectoryWrapper();
     activity         = new Mock <IDev2Activity>();
 }
    public void RaisePostBackEvent(string args)
    {
      string[] a = args.Split(';');

      if (a[0].ToLower(CultureInfo.InvariantCulture) == "picture")
      {
        DirectoryWrapper data = new DirectoryWrapper(imageTools.GetPath(a[1]), imageTools);
        int index = Convert.ToInt32(a[2]);
        BuildPicture(data, index);
      }
      else if (a[0].ToLower(CultureInfo.InvariantCulture) == "directory")
      {
        BuildDirectories(a[1], Convert.ToInt32(a[2]));
      }
      else if (a[0].ToLower(CultureInfo.InvariantCulture) == "directorysave")
      {
        DirectoryWrapper data = new DirectoryWrapper(imageTools.GetPath(a[1]), imageTools);
        data.Caption = Request[UniqueID + "$txtDirCaption"];
        data.Tooltip = Request[UniqueID + "$txtDirTooltip"];
        data.Description = Request[UniqueID + "$txtDirText"];

        BuildDirectories(a[1], Convert.ToInt32(a[2]));
      }
      else if (a[0].ToLower(CultureInfo.InvariantCulture) == "picturesave")
      {
        int index = Convert.ToInt32(a[2]);
        DirectoryWrapper directory = new DirectoryWrapper(imageTools.GetPath(a[1]), imageTools);

        DirectorySettingsHandler dirSettings = new DirectorySettingsHandler(imageTools.cfg.PictureRootDirectory + "/"
          + imageTools.GetPath(a[1]), a[1]);

        ImageWrapper i = directory.Images[index] as ImageWrapper;
        i.Caption = txtImageCaption.Text;
        i.Tooltip = txtImageTooltip.Text;
        i.Description = txtImageText.Text;

        // Show the next picture.
        if (index < (directory.Images.Count - 1))
          index++;
        BuildPicture(directory, index);
      }
      else if (a[0].ToLower(CultureInfo.InvariantCulture) == "setfolderimage")
      {
        string path = Server.MapPath(a[1]);
        string newFile = path.Substring(0, path.LastIndexOf('\\')) +
            "\\_dirimage." + path.Substring(path.LastIndexOf(".") + 1);
        string thumbFile = path.Substring(0, path.LastIndexOf('\\')) +
            "\\thumbs\\_dirimage." + path.Substring(path.LastIndexOf(".") + 1);

        System.IO.File.Copy(path, newFile, true);
        System.IO.File.Delete(thumbFile);

        BuildDirectories(a[1].Substring(0, a[1].LastIndexOf('/')), Convert.ToInt32(a[2]));
      }
      else if (a[0].ToLower(CultureInfo.InvariantCulture) == "updatepict")
      {
        UpdatePictures(imageTools.GetPath(a[1]));
        BuildDirectories(a[1], Convert.ToInt32(a[2]));
      }
    }
Esempio n. 10
0
        public void Startup()
        {
            _directoryWrapper = new DirectoryWrapper();
            if (_directoryWrapper.Exists(ResourcesBackup))
            {
                _directoryWrapper.Delete(ResourcesBackup, true);
            }
            if (_directoryWrapper.Exists(EnvironmentVariables.ResourcePath))
            {
                _directoryWrapper.Move(EnvironmentVariables.ResourcePath, ResourcesBackup);
            }
            var    serverUnderTest = Process.GetProcessesByName("Warewolf Server")[0];
            string exePath;

            try
            {
                exePath = Path.GetDirectoryName(serverUnderTest.MainModule?.FileName);
            }
            catch (Win32Exception)
            {
                exePath = Environment.CurrentDirectory;
            }
            var destDirName = Path.Combine(exePath, "Resources");

            if (!_directoryWrapper.Exists(destDirName))
            {
                _directoryWrapper.Move(Path.Combine(exePath, "Resources - Release", "Resources"), destDirName);
            }
        }
Esempio n. 11
0
        public void Setup()
        {
            _sfp                  = new StandardFolderProvider();
            _folderInfo           = new Mock <IFolderInfo>();
            _fileInfo             = new Mock <IFileInfo>();
            _fileWrapper          = new Mock <IFile>();
            _directoryWrapper     = new Mock <IDirectory>();
            _folderManager        = new Mock <IFolderManager>();
            _fileManager          = new Mock <IFileManager>();
            _pathUtils            = new Mock <IPathUtils>();
            _portalControllerMock = new Mock <IPortalController>();
            _portalControllerMock.Setup(p => p.GetPortalSettings(Constants.CONTENT_ValidPortalId))
            .Returns(GetPortalSettingsDictionaryMock());
            _portalControllerMock.Setup(p => p.GetCurrentPortalSettings()).Returns(GetPortalSettingsMock());
            _cryptographyProviderMock = new Mock <CryptographyProvider>();
            _cryptographyProviderMock.Setup(c => c.EncryptParameter(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Guid.NewGuid().ToString("N"));
            _localeControllerMock = new Mock <ILocaleController>();
            _localeControllerMock.Setup(l => l.GetLocales(Constants.CONTENT_ValidPortalId)).Returns(new Dictionary <string, Locale>
            {
                { "en-us", new Locale() }
            });

            FileWrapper.RegisterInstance(_fileWrapper.Object);
            DirectoryWrapper.RegisterInstance(_directoryWrapper.Object);
            FolderManager.RegisterInstance(_folderManager.Object);
            FileManager.RegisterInstance(_fileManager.Object);
            PathUtils.RegisterInstance(_pathUtils.Object);
            PortalController.SetTestableInstance(_portalControllerMock.Object);
            ComponentFactory.RegisterComponentInstance <CryptographyProvider>("CryptographyProviderMock", _cryptographyProviderMock.Object);
            LocaleController.RegisterInstance(_localeControllerMock.Object);
        }
Esempio n. 12
0
        private static void BuildStream(string workspacePath, string[] folders, List <ResourceBuilderTO> streams)
        {
            var dir = new DirectoryWrapper();

            foreach (var path in folders.Where(f => !string.IsNullOrEmpty(f)).Select(f => Path.Combine(workspacePath, f)))
            {
                if (!Directory.Exists(path))
                {
                    continue;
                }
                var files = dir.GetFilesByExtensions(path, ".xml", ".bite");
                foreach (var file in files)
                {
                    var fa = File.GetAttributes(file);

                    if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    {
                        Dev2Logger.Info("Removed READONLY Flag from [ " + file + " ]", GlobalConstants.WarewolfInfo);
                        File.SetAttributes(file, FileAttributes.Normal);
                    }

                    // Use the FileStream class, which has an option that causes asynchronous I/O to occur at the operating system level.
                    // In many cases, this will avoid blocking a ThreadPool thread.
                    var sourceStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, true);
                    streams.Add(new ResourceBuilderTO {
                        _filePath = file, _fileStream = sourceStream
                    });
                }
            }
        }
Esempio n. 13
0
 public TestCatalog()
 {
     _directoryWrapper = new DirectoryWrapper();
     _fileWrapper      = new FileWrapper();
     _directoryWrapper.CreateIfNotExists(EnvironmentVariables.TestPath);
     Tests       = new ConcurrentDictionary <Guid, List <IServiceTestModelTO> >();
     _serializer = new Dev2JsonSerializer();
 }
Esempio n. 14
0
        public void UpdateAll()
        {
            // Rebuild the thumbails.
            string           path      = m_imageTools.GetPath(m_path);
            DirectoryWrapper directory = new DirectoryWrapper(path, m_imageTools);

            UpdateDirectory(directory);
        }
Esempio n. 15
0
 public TestCoverageCatalog(IResourceCatalog resourceCatalog)
 {
     _directoryWrapper = new DirectoryWrapper();
     _fileWrapper      = new FileWrapper();
     _directoryWrapper.CreateIfNotExists(EnvironmentVariables.TestCoveragePath);
     _serializer = new Dev2JsonSerializer();
     _serviceAllTestsCoverageModelToFactory = CustomContainer.Get <IServiceTestCoverageModelToFactory>() ?? new ServiceTestCoverageModelToFactory(resourceCatalog);
 }
Esempio n. 16
0
 static void DeleteDir(string rootFolder)
 {
     if (Directory.Exists(rootFolder + @"\Dev2\"))
     {
         var dir = new DirectoryWrapper();
         dir.CleanUp(rootFolder + @"\Dev2\");
     }
 }
Esempio n. 17
0
        public static void ProcessCSVs(DirectoryWrapper csvDir, DirectoryWrapper customCsvDir, DirectoryWrapper jsonDir)
        {
            ProccessRegularCSVs(csvDir, jsonDir);

            csvDir.GetChildFile("pokemon_moves.csv");

            FileWrapper pokemonMovesFile = csvDir.GetChildFile("pokemon_moves.csv");
        }
        public void Given_Null_Path_When_CreateDirectory_Invoked_Then_It_Should_Throw_Exception()
        {
            var wrapper = new DirectoryWrapper();

            Action action = () => wrapper.CreateDirectory(null);

            action.Should().Throw <ArgumentNullException>();
        }
Esempio n. 19
0
        private void BuildDirectories(string vPath)
        {
            ImageViewPanel.Visible    = false;
            ImageBrowserPanel.Visible = true;

            string           path = imageTools.GetPath(vPath);
            DirectoryWrapper data = new DirectoryWrapper(path, imageTools);

            // draw navigation
            HtmlTools.RendenderLinkPath(ImageBrowserPanel.Controls, path, this, imageTools.cfg);

            ImageBrowserPanel.Controls.Add(HtmlTools.HR);

            if (ModuleHasEditRights)
            {
                TextBox editblurb = new TextBox();
                editblurb.ID       = "editblurb";
                editblurb.Text     = data.Blurb;
                editblurb.Width    = new Unit("100%");
                editblurb.Height   = new Unit("100px");
                editblurb.TextMode = TextBoxMode.MultiLine;
                ImageBrowserPanel.Controls.Add(editblurb);

                HyperLink lnkSave = new HyperLink();
                lnkSave.NavigateUrl = Page.GetPostBackClientHyperlink(this, "directorysave;" + vPath);
                lnkSave.Text        = "Save";
                ImageBrowserPanel.Controls.Add(lnkSave);

                ImageBrowserPanel.Controls.Add(HtmlTools.HR);
            }
            else
            {
                // pump out the blurb
                Label blurb = new Label();
                blurb.Text = data.Blurb;
                ImageBrowserPanel.Controls.Add(blurb);

                // draw a line if appropriate
                if (blurb.Text.Length > 0 && (data.Directories.Count > 0 || data.Images.Count > 0))
                {
                    ImageBrowserPanel.Controls.Add(HtmlTools.HR);
                }
            }


            // draw subdirectories
            ImageBrowserPanel.Controls.Add(HtmlTools.RenderDirectoryTable(4, data, this));


            // draw a line if appropriate
            if (data.Directories.Count > 0 && data.Images.Count > 0)
            {
                ImageBrowserPanel.Controls.Add(HtmlTools.HR);
            }

            // draw images
            ImageBrowserPanel.Controls.Add(HtmlTools.RenderImageTable(7, 0, data, this));
        }
        private void TestSetup(out IFile fileWrapper, out IDirectory directoryWrapper, out Mock <IDev2Activity> activity)
        {
            // setup
            var mockedDataObject = SetupDataObject();

            fileWrapper      = new FileWrapper();
            directoryWrapper = new DirectoryWrapper();
            activity         = new Mock <IDev2Activity>();
        }
        /// <summary>
        ///  This creates a Table object with all the subdirectories in it
        /// </summary>
        /// <param name="x">Subdirectories wide</param>
        /// <param name="data">The directory to render</param>
        /// <param name="url">The URL to use in the links</param>
        /// <returns></returns>
        public static Table RenderDirectoryTable(int x, DirectoryWrapper data /*, string url*/, System.Web.UI.Control ctrl)
        {
            Table table = new Table();

            table.CellPadding = 10;
            table.CellSpacing = 10;
            table.Width       = Unit.Percentage(100);

            TableRow tr = null;

            foreach (SubDirectoryWrapper dir in data.Directories)
            {
                if (tr == null)
                {
                    tr = new TableRow();
                }

                TableCell td = new TableCell();
                td.Attributes["align"] = "center";

                HyperLink h = new HyperLink();

                h.ImageUrl    = dir.Src;
                h.CssClass    = "LinkButton";
                h.NavigateUrl = ctrl.Page.GetPostBackClientHyperlink(ctrl, "directory;" + dir.HREF);
                h.Text        = dir.Name;

                td.Controls.Add(h);

                td.Controls.Add(BR);

                h             = new HyperLink();
                h.CssClass    = "LinkButton";
                h.NavigateUrl = ctrl.Page.GetPostBackClientHyperlink(ctrl, "directory;" + dir.HREF);
                h.Text        = dir.Name;


                td.Controls.Add(h);

                tr.Cells.Add(td);

                if (tr.Cells.Count == x)
                {
                    table.Rows.Add(tr);
                    tr = null;
                }
            }

            if (tr != null)
            {
                table.Rows.Add(tr);
            }

            return(table);
        }
Esempio n. 22
0
        public void SmartCopyDeletesFilesThatDontExistInSourceIfNoPrevious()
        {
            DirectoryWrapper sourceDirectory      = GetDirectory(@"a:\test\", filePaths: new[] { @"a.txt", "b.txt" });
            DirectoryWrapper destinationDirectory = GetDirectory(@"b:\foo\", filePaths: new[] { "c.txt" });

            DeploymentHelper.SmartCopy(@"a:\test\", @"b:\foo\", null, sourceDirectory.Directory, destinationDirectory.Directory, path => GetDirectory(path, exists: false).Directory);

            sourceDirectory.VerifyCopied("a.txt", @"b:\foo\a.txt");
            sourceDirectory.VerifyCopied("b.txt", @"b:\foo\b.txt");
            destinationDirectory.VerifyDeleted("c.txt");
        }
Esempio n. 23
0
        private static void TestSetup(out IFile fileWrapper, out IDirectory directoryWrapper, out Dev2JsonStateLogger dev2StateLogger, out Mock <IDev2Activity> activity, out DetailedLogFile detailedLog)
        {
            // setup
            Mock <IDSFDataObject> mockedDataObject = SetupDataObject();

            fileWrapper      = new FileWrapper();
            directoryWrapper = new DirectoryWrapper();
            activity         = new Mock <IDev2Activity>();
            dev2StateLogger  = GetDev2JsonStateLogger(fileWrapper, mockedDataObject);
            detailedLog      = SetupDetailedLog(dev2StateLogger);
        }
        public void Given_Path_When_CreateDirectory_Invoked_Then_It_Should_Return_Result(string directory, bool expected)
        {
            var baseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var path          = Path.Combine(baseDirectory, directory);

            var wrapper = new DirectoryWrapper();

            var result = wrapper.CreateDirectory(path);

            result.Exists.Should().Be(expected);
        }
 public FileSystem()
 {
     DriveInfo         = new DriveInfoFactory(this);
     DirectoryInfo     = new DirectoryInfoFactory(this);
     FileInfo          = new FileInfoFactory(this);
     Path              = new PathWrapper(this);
     File              = new FileWrapper(this);
     Directory         = new DirectoryWrapper(this);
     FileStream        = new FileStreamFactory();
     FileSystemWatcher = new FileSystemWatcherFactory();
 }
Esempio n. 26
0
        /// <summary>
        ///  This creates a Table object with all the subdirectories in it
        /// </summary>
        /// <param name="x">Subdirectories wide</param>
        /// <param name="data">The directory to render</param>
        /// <param name="url">The URL to use in the links</param>
        /// <returns></returns>
        public static Table RenderDirectoryTable(int x, DirectoryWrapper data, string url)
        {
            Table table = new Table();

            table.CellPadding = 10;
            table.CellSpacing = 10;
            table.Width       = Unit.Percentage(100);

            TableRow tr = null;

            foreach (SubDirectoryWrapper dir in data.Directories)
            {
                if (tr == null)
                {
                    tr = new TableRow();
                }

                TableCell td = new TableCell();
                td.Attributes["align"] = "center";

                HyperLink h = new HyperLink();

                h.ImageUrl    = dir.Src;
                h.NavigateUrl = url + dir.HREF;
                h.Text        = dir.Name;

                td.Controls.Add(h);

                td.Controls.Add(BR);

                h             = new HyperLink();
                h.NavigateUrl = url + dir.HREF;
                h.Text        = dir.Name;


                td.Controls.Add(h);

                tr.Cells.Add(td);

                if (tr.Cells.Count == x)
                {
                    table.Rows.Add(tr);
                    tr = null;
                }
            }

            if (tr != null)
            {
                table.Rows.Add(tr);
            }

            return(table);
        }
Esempio n. 27
0
        public void SmartCopyDeletesSubDirectoryIfNoPreviousAndDirectoryDoesnotExistInSource()
        {
            DirectoryWrapper sourceDirectory = GetDirectory(@"a:\source\", filePaths: new[] { "b.txt" });

            DirectoryWrapper destinationSub       = GetDirectory(@"b:\target\sub3", filePaths: new[] { "o.js" });
            DirectoryWrapper destinationDirectory = GetDirectory(@"b:\target\", directories: new[] { destinationSub });

            DeploymentHelper.SmartCopy(@"a:\source\", @"b:\target\", null, sourceDirectory.Directory, destinationDirectory.Directory, path => GetDirectory(path).Directory);

            destinationSub.VerifyDeleted();
            sourceDirectory.VerifyCopied("b.txt", @"b:\target\b.txt");
        }
Esempio n. 28
0
        public static string GetServerLogSettingsConfigFile()
        {
            var localAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            var serverLogFolder    = Path.Combine(localAppDataFolder, "Warewolf", "Server Log");

            IDirectory directory = new DirectoryWrapper();

            directory.CreateIfNotExists(serverLogFolder);

            var serverLogFile = Path.Combine(serverLogFolder, "warewolf-Server.log");

            return(serverLogFile);
        }
Esempio n. 29
0
        public void EnvironmentVariables_WorkflowDetailLogPath_ShouldReturnDetailedLogsInProgramData()
        {
            //------------Setup for test--------------------------
            const string folderPart = "ProgramData\\Warewolf\\DetailedLogs";
            //------------Execute Test---------------------------
            var folderPath = EnvironmentVariables.WorkflowDetailLogPath(It.IsAny <Guid>(), It.IsAny <string>());

            //------------Assert Results-------------------------
            StringAssert.Contains(folderPath, folderPart);
            var directory = new DirectoryWrapper();

            directory.Delete(folderPath, true);
        }
Esempio n. 30
0
        public void SmartCopyCopiesFilesFromSourceToDestination()
        {
            DirectoryWrapper sourceDirectory      = GetDirectory(@"a:\test\", filePaths: new[] { @"a.txt", "b.txt", ".bar", ".deployment" });
            DirectoryWrapper destinationDirectory = GetDirectory(@"b:\foo\", exists: false);

            DeploymentHelper.SmartCopy(@"a:\test\", @"b:\foo\", null, sourceDirectory.Directory, destinationDirectory.Directory, path => GetDirectory(path, exists: false).Directory);

            destinationDirectory.VerifyCreated();
            sourceDirectory.VerifyCopied("a.txt", @"b:\foo\a.txt");
            sourceDirectory.VerifyCopied("b.txt", @"b:\foo\b.txt");
            sourceDirectory.VerifyCopied(".bar", @"b:\foo\.bar");
            sourceDirectory.VerifyNotCopied(".deployment", @"b:\foo\.deployment");
        }
Esempio n. 31
0
        public void Load()
        {
            Tests = new ConcurrentDictionary <Guid, List <IServiceTestModelTO> >();
            var resourceTestDirectories = _directoryWrapper.GetDirectories(EnvironmentVariables.TestPath);

            foreach (var resourceTestDirectory in resourceTestDirectories)
            {
                var resIdString = DirectoryWrapper.GetDirectoryName(resourceTestDirectory);
                if (Guid.TryParse(resIdString, out Guid resId))
                {
                    Tests.AddOrUpdate(resId, GetTestList(resourceTestDirectory), (id, list) => GetTestList(resourceTestDirectory));
                }
            }
        }
        public void RaisePostBackEvent(string args)
        {
            string[] a = args.Split(';');

            if(a[0].ToLower() == "picture")
            {
                BuildPicture(a[1]);
            }
            else if(a[0].ToLower() == "directory")
            {
                BuildDirectories(a[1]);
            }
            else if(a[0].ToLower() == "directorysave")
            {
                DirectoryWrapper data = new DirectoryWrapper(imageTools.GetPath(a[1]), imageTools);
                data.Blurb = Request[UniqueID + ":editblurb"];

                BuildDirectories(a[1]);
            }
            else if(a[0].ToLower() == "picturesave")
            {
                ImageWrapper i = imageTools.GetImageWrapper(imageTools.GetPath(a[1]));
                i.Blurb = txtImageText.Text;

                BuildDirectories(a[1].Substring(0, a[1].LastIndexOf('/')));
            }
            else if(a[0].ToLower() == "setfolderimage")
            {
                string path = Server.MapPath(a[1]);
                string newFile = path.Substring(0, path.LastIndexOf('\\')) +
                    "\\_dirimage." + path.Substring(path.LastIndexOf(".") + 1);
                string thumbFile = path.Substring(0, path.LastIndexOf('\\')) +
                    "\\thumbs\\_dirimage." + path.Substring(path.LastIndexOf(".") + 1);

                System.IO.File.Copy(path, newFile, true);
                System.IO.File.Delete(thumbFile);

                BuildDirectories(a[1].Substring(0, a[1].LastIndexOf('/')));
            }
        }
        private void BuildDirectories(string vPath)
        {
            ImageViewPanel.Visible = false;
            ImageBrowserPanel.Visible = true;

            string path = imageTools.GetPath(vPath);
            DirectoryWrapper data = new DirectoryWrapper(path, imageTools);

            // draw navigation
            HtmlTools.RendenderLinkPath( ImageBrowserPanel.Controls, path, this, imageTools.cfg );

            ImageBrowserPanel.Controls.Add(HtmlTools.HR);

            if(ModuleHasEditRights)
            {
                TextBox editblurb = new TextBox();
                editblurb.ID = "editblurb";
                editblurb.Text = data.Blurb;
                editblurb.Width = new Unit("100%");
                editblurb.Height = new Unit("100px");
                editblurb.TextMode = TextBoxMode.MultiLine;
                ImageBrowserPanel.Controls.Add(editblurb);

                HyperLink lnkSave = new HyperLink();
                lnkSave.NavigateUrl = Page.GetPostBackClientHyperlink(this, "directorysave;" + vPath);
                lnkSave.Text = "Save";
                ImageBrowserPanel.Controls.Add(lnkSave);

                ImageBrowserPanel.Controls.Add(HtmlTools.HR);
            }
            else
            {
                // pump out the blurb
                Label blurb = new Label();
                blurb.Text = data.Blurb;
                ImageBrowserPanel.Controls.Add(blurb);

                // draw a line if appropriate
                if ( blurb.Text.Length > 0 && ( data.Directories.Count > 0 || data.Images.Count > 0)  )
                {
                    ImageBrowserPanel.Controls.Add(HtmlTools.HR);
                }
            }

            // draw subdirectories
            ImageBrowserPanel.Controls.Add( HtmlTools.RenderDirectoryTable(4,data, this) );

            // draw a line if appropriate
            if ( data.Directories.Count > 0 && data.Images.Count > 0 )
            {
                ImageBrowserPanel.Controls.Add(HtmlTools.HR);
            }

            // draw images
            ImageBrowserPanel.Controls.Add( HtmlTools.RenderImageTable(7,0,data, this ) );
        }
    private void BuildDirectories(string vPath, int currIndex)
    {
      ImageViewPanel.Visible = false;
      ImageBrowserPanel.Visible = true;

      string path = imageTools.GetPath(vPath);
      DirectoryWrapper data = new DirectoryWrapper(path, imageTools);

      if (currIndex >= data.Images.Count)  // Out of range?
        currIndex = data.Images.Count - 1;

      // draw navigation
      HtmlTools.RendenderLinkPath(Path.Controls, path, this, imageTools.cfg);

      directoryContent.Controls.Add(HtmlTools.HR);

      if (ModuleHasEditRights)
      {
        txtDirCaption.Text = data.Caption;
        txtDirTooltip.Text = data.Tooltip;
        txtDirText.Text = data.Description; ;

        lnkSave.NavigateUrl = Page.GetPostBackClientHyperlink(this, "directorysave;" + vPath + ";" + currIndex.ToString());

        lnkSave.Visible = true;
        lnkUpdatePictures.Visible = true;
        lnkUpdatePictures.NavigateUrl = Page.GetPostBackClientHyperlink(this, "updatePict;" + vPath + ";" + currIndex.ToString());

        string insertJs = "document.getElementById('{0}').value=document.getElementById('{1}').value";
        btnDirTTInsSD.Attributes["onClick"] = string.Format(insertJs, txtDirTooltip.ClientID, txtDirCaption.ClientID);
        btnDirTTInsD.Attributes["onClick"] = string.Format(insertJs, txtDirTooltip.ClientID, txtDirText.ClientID);
        btnDirSDInsTT.Attributes["onClick"] = string.Format(insertJs, txtDirCaption.ClientID, txtDirTooltip.ClientID);
        btnDirSDInsD.Attributes["onClick"] = string.Format(insertJs, txtDirCaption.ClientID, txtDirText.ClientID);
        btnDirDInsTT.Attributes["onClick"] = string.Format(insertJs, txtDirText.ClientID, txtDirTooltip.ClientID);
        btnDirDInsDS.Attributes["onClick"] = string.Format(insertJs, txtDirText.ClientID, txtDirCaption.ClientID);
      }
      else
      {
        DirEditOps.Visible = false;

        // pump out the blurb
        Label blurb = new Label();
        blurb.Text = data.Description;
        directoryContent.Controls.Add(blurb);

        // draw a line if appropriate
        if (blurb.Text.Length > 0 && (data.Directories.Count > 0 || data.Images.Count > 0))
        {
          directoryContent.Controls.Add(HtmlTools.HR);
        }
      }


      // draw subdirectories
      directoryContent.Controls.Add(HtmlTools.RenderDirectoryTable(4, data, this));


      // draw a line if appropriate
      if (data.Directories.Count > 0 && data.Images.Count > 0)
      {
        directoryContent.Controls.Add(HtmlTools.HR);
      }

      // Calculate index of the first image on the current page.
      int imageCols = imageTools.cfg.ThumbnailCols;
      int imageRows = imageTools.cfg.ThumbnailRows;
      int startIndex = ((int)(currIndex / (imageCols * imageRows))) * (imageCols * imageRows);

      // draw images
      directoryContent.Controls.Add(HtmlTools.RenderImageTable(imageCols, imageRows, startIndex, data, this));

      // draw the Page Navigation.
      HtmlTools.RendenderPageNavigation(pageNavigation.Controls, path, imageCols * imageRows, data.Images.Count - 1,
                                        startIndex, this);
    }
    private void AddPreloadCode(DirectoryWrapper data, int index, WebControl imgCtrl)
    {
      const string scriptKey = "ImagePreload";
      if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptKey))
      {
        string script = "<script language=\"JavaScript\">\n"
          + "function PreLoadSiblings()\n{\n";

        // Script for the Next end the previous picture, to load them to the browser cache.
        if (index > 0)
        {
          ImageWrapper i = data.Images[index - 1] as ImageWrapper;
          string path = ResolveUrl(i.WebImageHref);
          script += "objImageNext = new Image(); objImageNext.src='" + path + "';\n";
        }
        if (index < data.Images.Count - 1)
        {
          ImageWrapper i = data.Images[index + 1] as ImageWrapper;
          string path = ResolveUrl(i.WebImageHref);
          script += "objImageNext = new Image(); objImageNext.src='" + path + "';\n";
        }

        script += "}\n</script>";

        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), scriptKey, script);

        // Register the Script for the event when the main Image is loaded.
        imgCtrl.Attributes.Add("onload", "PreLoadSiblings()");
      }

    }
    private void BuildPicture(DirectoryWrapper directory, int index)
    {
      ImageViewPanel.Visible = true;
      ImageBrowserPanel.Visible = false;

      ImageWrapper i = directory.Images[index] as ImageWrapper;

      lnkBack.NavigateUrl = Page.GetPostBackClientHyperlink(this, "directory;" + directory.VirtualPath + ";" + index.ToString());

      int shadowWidth = 0;
      if (imageTools.cfg.PreviewCfg.Shadow)
        shadowWidth = imageTools.cfg.PreviewCfg.ShadowWidth;
      System.Web.UI.WebControls.Image image = null;
      Control imgCtrl = HtmlTools.RenderImagePreview(i, shadowWidth, out image);
      imagePosition.Controls.Add(imgCtrl);
      AddPreloadCode(directory, index, image);

      if (index > 0)
      {
        lnkMovePrevious.NavigateUrl = Page.GetPostBackClientHyperlink(this, "picture;" + directory.VirtualPath + ";"
          + Convert.ToString(index - 1));
        lnkMovePrevious.Visible = true;
      }
      else
        lnkMovePrevious.Visible = false;

      if (index < directory.Images.Count - 1)
      {
        lnkMoveNext.NavigateUrl = Page.GetPostBackClientHyperlink(this, "picture;" + directory.VirtualPath + ";"
          + Convert.ToString(index + 1));
        lnkMoveNext.Visible = true;
      }
      else
        lnkMoveNext.Visible = false;



      if (ModuleHasEditRights)
      {
        txtImageTooltip.Text = i.Tooltip;
        txtImageCaption.Text = i.Caption;
        txtImageText.Text = i.Description;

        lnkSaveImageText.NavigateUrl = Page.GetPostBackClientHyperlink(this, "picturesave;" + directory.VirtualPath + ";" + index.ToString());
        lnkSetFolderImage.NavigateUrl = Page.GetPostBackClientHyperlink(this, "setfolderimage;" + i.FullImageHref + ";" + index.ToString());

        string insertJs = "document.getElementById('{0}').value=document.getElementById('{1}').value";
        btnTTInsSD.Attributes["onClick"] = string.Format(insertJs, txtImageTooltip.ClientID, txtImageCaption.ClientID);
        btnTTInsD.Attributes["onClick"] = string.Format(insertJs, txtImageTooltip.ClientID, txtImageText.ClientID);
        btnSDInsTT.Attributes["onClick"] = string.Format(insertJs, txtImageCaption.ClientID, txtImageTooltip.ClientID);
        btnSDInsD.Attributes["onClick"] = string.Format(insertJs, txtImageCaption.ClientID, txtImageText.ClientID);
        btnDInsTT.Attributes["onClick"] = string.Format(insertJs, txtImageText.ClientID, txtImageTooltip.ClientID);
        btnDInsDS.Attributes["onClick"] = string.Format(insertJs, txtImageText.ClientID, txtImageCaption.ClientID);
        lbImageText.Visible = false;
      }
      else
      {
        lbImageText.Text = i.Description;
        lbImageText.Visible = true;
        PhotoEditOpts.Visible = false;
      }
    }
Esempio n. 37
0
        public void CanBundleNestedLessInDifferentDirectoriesMultiThreaded()
        {
            // This test is dependant on a race condition so may not cause a
            // failure every time even when a bug is present. However on a
            // multicore machine it seems to have a high failure rate.

            string importCssA =
                @"
                @import 'other.less';
                .cssA {
                    color: #AAAAAA;
                }";

            string importCssB =
                @"
                @import 'other.less';
                .cssB {
                    color: #BBBBBB;
                }";

            cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css_A\test.less"), importCssA);
            cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css_B\test.less"), importCssB);

            TestUtilities.CreateFile("css_A/test.less", importCssA);
            TestUtilities.CreateFile("css_B/test.less", importCssB);

            TestUtilities.CreateFile("css_A/other.less", "#cssA{color:#ffffff}");
            TestUtilities.CreateFile("css_B/other.less", "#cssB{color:#000000}");

            var dirWrapper = new DirectoryWrapper();

            CSSBundle cssBundleA = cssBundleFactory
                .WithCurrentDirectoryWrapper(dirWrapper)
                .WithDebuggingEnabled(false)
                //.WithContents(importCssA)
                .Create()
                .WithPreprocessor(new LessPreprocessor());

            CSSBundle cssBundleB = cssBundleFactory
                .WithCurrentDirectoryWrapper(dirWrapper)
                .WithDebuggingEnabled(false)
                //.WithContents(importCssB)
                .Create()
                .WithPreprocessor(new LessPreprocessor());

            // Trigger the parsing of two different .less files in different
            // directories at the same time. Both import a file called other.less
            // which should be found in their own directory, but issues with
            // changing the current directory at the wrong time could cause
            // them to pick up the imported file from the incorrect location.
            var taskA = Task.Factory.StartNew(() =>
            {
                var sa = cssBundleA
                    .Add("css_A/test.less")
                    .Render("css_A/output_test.css");
            });

            var taskB = Task.Factory.StartNew(() =>
            {
                var sb = cssBundleB
                   .Add("css_B/test.less")
                   .Render("css_B/output_test.css");
            });

            taskA.Wait();
            taskB.Wait();

            TestUtilities.DeleteFile("css_A/test.less");
            TestUtilities.DeleteFile("css_B/test.less");
            TestUtilities.DeleteFile("css_A/other.less");
            TestUtilities.DeleteFile("css_B/other.less");

            Assert.AreEqual("#cssA{color:#fff}.cssA{color:#aaa}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css_A\output_test.css")]);
            Assert.AreEqual("#cssB{color:#000}.cssB{color:#bbb}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css_B\output_test.css")]);
            Assert.Contains(FileSystem.ResolveAppRelativePathToFileSystem("css_A/other.less"), cssBundleA.bundleState.DependentFiles);
            Assert.Contains(FileSystem.ResolveAppRelativePathToFileSystem("css_B/other.less"), cssBundleB.bundleState.DependentFiles);
        }