Beispiel #1
0
        public void DownloadUrlTest()
        {
            var pathHelper = new PathHelper("http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css", @"C:\git\t2\DBC\src\DBC\wwwroot\fallback\css\bootstrap.min.css");
            pathHelper.GetRemotePath("../fonts/fontawesome-webfont.eot?v=4.3.0");
            Assert.Equal(pathHelper.GetRemotePath("../fonts/fontawesome-webfont.eot?v=4.3.0"), "http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/../fonts/fontawesome-webfont.eot?v=4.3.0");
            Assert.Equal(pathHelper.GetLocalPath("../fonts/fontawesome-webfont.eot?v=4.3.0"), @"C:\git\t2\DBC\src\DBC\wwwroot\fallback\fonts\fontawesome-webfont.eot");

             string cssContent = @"
                @font - face {
                    font - family: 'FontAwesome';
                    src: url('../fonts/fontawesome-webfont.eot?v=4.3.0');
                    src: url( '../fonts/fontawesome-webfont.eot?#iefix&v=4.3.0') format('embedded-opentype'),
                        url(""../fonts/fontawesome-webfont.woff2?v=4.3.0') format('woff2""),
                        url ( '../fonts/fontawesome-webfont.woff?v=4.3.0') format('woff'),
                        url('../fonts/fontawesome-webfont.ttf?v=4.3.0' ) format('truetype'),
                        url('../fonts/fontawesome-webfont.svg?v=4.3.0#fontawesomeregular') format('svg');
                    font - weight: normal;
                    font - style: normal;
                }";
            var urls = LinkTagHelper.Urls.Matches(cssContent);
            Assert.Equal(urls.Count, 6);

            cssContent = @"this is some stuff right here
                /* blah blah blah
                   blah blah blah
                   blah blah blah */ and this is more stuff /* blah */
                   right here stuff.";
            var result = LinkTagHelper.CommentRemove.Replace(cssContent,"");
            Assert.DoesNotContain("bla", result);
            Assert.Contains( "stuff", result);
        }
Beispiel #2
0
        private static Configuration HandleCustomSolution(string outputPath, bool generateEntryProject, IEnumerable<string> directories)
        {
            var stepManager = new StepManager();
            var pathHelper = new PathHelper(directories.Select(Path.GetFullPath));

            var uiSelectionStep = new UiStep(pathHelper);
            var robotTestsStep = new RobotTestsStep("Choose robot tests:", pathHelper);
            stepManager
                .AddStep(uiSelectionStep)
                .AddStep(new ProjectsListStep<CpuCoreProject>("Choose supported architectures:", pathHelper))
                .AddStep(new ProjectsListStep<ExtensionProject>("Choose extensions libraries:", pathHelper))
                .AddStep(new PluginStep("Choose plugins:", pathHelper))
                .AddStep(new ProjectsListStep<TestsProject>("Choose tests:", pathHelper))
                .AddStep(robotTestsStep)
                .AddStep(new ProjectsListStep<UnknownProject>("Choose other projects:", pathHelper))
                .Run();
            
            if(stepManager.IsCancelled)
            {
                return null;
            }

            return new Configuration(
                SolutionGenerator.Generate(uiSelectionStep.UIProject, generateEntryProject, outputPath,
                    stepManager.GetSteps<ProjectsListStep>().SelectMany(x => x.AdditionalProjects).Union(uiSelectionStep.UIProject.GetAllReferences())),
                robotTestsStep.SelectedTests);
        }
 // private Dictionary<string,FileSystemWatcher> _directoriesFileSystemWatchers = new Dictionary<string, FileSystemWatcher>();
 public DirectoryWatcher(TopViewModel top,IDirectoryViewModel root, PathHelper pathHelper, Dispatcher dispatcher)
 {
     Top = top;
     _pathHelper = pathHelper;
     _dispatcher = dispatcher;
     root.SubDirectories.CollectionLoaded += SubDirectories_CollectionLoaded;
 }
        public override Uri GetFileSystemObjectUrl(string path, ICloudDirectoryEntry parent)
        {
            var ph = new PathHelper(path);
            var elements = ph.GetPathElements();
            var current = parent;

            for (int i = 0; i < elements.Length; i++)
            {
                var child = current.GetChild(elements[i], false);
                if (i == elements.Length - 1)
                {
                    if (child == null || child is ICloudDirectoryEntry)
                    {
                        throw new SharpBoxException(SharpBoxErrorCodes.ErrorFileNotFound);
                    }

                    return new Uri(child.GetPropertyValue(GoogleDocsConstants.DownloadUrlProperty));
                }

                if (child == null || !(child is ICloudDirectoryEntry))
                {
                    throw new SharpBoxException(SharpBoxErrorCodes.ErrorFileNotFound);
                }

                current = (ICloudDirectoryEntry) child;
            }

            return null;
        }
        /// <summary>
        /// This method returns access ro a specific subfolder addressed via 
        /// unix like file system path, e.g. /Public/SubFolder/SubSub
        /// 
        /// Valid Exceptions are:
        ///  SharpBoxException(nSharpBoxErrorCodes.ErrorInvalidFileOrDirectoryName);
        ///  SharpBoxException(nSharpBoxErrorCodes.ErrorFileNotFound);
        /// </summary>
        /// <param name="path">The path to the target subfolder</param>
        /// <returns>Reference to the searched folder</returns>
        public ICloudDirectoryEntry GetFolder(String path)
        {
            var ph = new PathHelper(path);
            if (!ph.IsPathRooted())
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidFileOrDirectoryName);

            return GetFolder(path, null);
        }
		public void MakeFull_HandlesNegation()
		{
			var env = new Mock<IHostingEnvironment>();
			env.Setup(m => m.ContentRootPath).Returns("C:/Project/");
			var helper = new PathHelper(env.Object, "wwwroot");

			var result = helper.MakeFull("src/", "!foo.js");

			Assert.Equal("!wwwroot/src/foo.js", result);
		}
		public void MakeRelative()
		{
			var env = new Mock<IHostingEnvironment>();
			env.Setup(m => m.ContentRootPath).Returns("C:/Project/");
			var helper = new PathHelper(env.Object, "wwwroot");

			var result = helper.MakeRelative("C:/Project/wwwroot/js/foo.js");

			Assert.Equal("/js/foo.js", result);
		}
Beispiel #8
0
        // ### FileParser
        // File parser does two things: It adds types that it encounters to the specified `FoundTypes`
        // object and emits lines of code and comments as they are encountered.
        //
        // The `FoundTypes` instance will be used later on to hyperlink the files together.
        public FileParser(string path, FoundTypes foundTypes, PathHelper pathHelper)
        {
            using (StreamReader reader = new StreamReader(path))
            {
                this.tokens = Lexer.Tokenize(reader);
            }

            this.types = foundTypes;
            this.path = path;
            this.pathHelper = pathHelper;
        }
Beispiel #9
0
        public TopViewModel(PathHelper pathHelper)
        {
            _dispatcher = Dispatcher.CurrentDispatcher;
            PathHelper = pathHelper;
            NewPathSetCommand = new RelayCommand(OnCurrentPathSet);
            BackwardCommand = new RelayCommand(() => BackwardNavigation(), o => _positionHistory > 0);
            ForwardCommand = new RelayCommand(() => ForwardNavigation(), o => _positionHistory < history.Count - 1);

            DirectoryViewModelBase.OpenDirectory += DirectoryViewModelBase_OpenDirectory;
            DirectoryViewModelBase.NoExistDirectory += DirectoryViewModelBaseOnNoExistDirectory;
        }
Beispiel #10
0
        private static Solution HandleCustomSolution(IEnumerable<string> directories)
        {
            var stepManager = new StepManager();
            var pathHelper = new PathHelper(directories.Select(Path.GetFullPath));

            stepManager.AddStep(new UiStep(pathHelper));
            stepManager.AddStep(new ProjectsListStep<ExtensionProject>("Choose extensions libraries:", pathHelper));
            stepManager.AddStep(new PluginStep("Choose plugins:", pathHelper));
            stepManager.AddStep(new ProjectsListStep<TestsProject>("Choose tests:", pathHelper));
            stepManager.AddStep(new ProjectsListStep<UnknownProject>("Choose other projects:", pathHelper));

            stepManager.Run();
            return stepManager.IsCancelled ? null 
                    : SolutionGenerator.Generate(stepManager.GetStep<UiStep>().UIProject,
                stepManager.GetSteps<ProjectsListStep>().SelectMany(x => x.AdditionalProjects).Union(stepManager.GetStep<UiStep>().UIProject.GetAllReferences()));
        }
Beispiel #11
0
    private void Fill_trvReports_Reports(LoadSttate Ls, string SearchItem)
    {
        string[]             retMessage   = new string[4];
        JavaScriptSerializer JsSerializer = new JavaScriptSerializer();

        try
        {
            this.InitializeCulture();

            IList <Report> reportsList      = this.ReportBusiness.GetAllReports();
            TreeViewNode   rootRepGroupNode = new TreeViewNode();
            Report         rootRepGroup     = reportsList.Where(x => x.ParentId == 0).FirstOrDefault();
            if (rootRepGroup != null)
            {
                rootRepGroupNode.ID = rootRepGroup.ID.ToString();
                string rootRepGroupNodeText = string.Empty;
                if (GetLocalResourceObject("ReportsNode_trvReports_Reports") != null)
                {
                    rootRepGroupNodeText = GetLocalResourceObject("ReportsNode_trvReports_Reports").ToString();
                }
                else
                {
                    rootRepGroupNodeText = rootRepGroup.Name;
                }
                rootRepGroupNode.Text = rootRepGroupNodeText;



                TargetDetails targetDetails = new TargetDetails();
                targetDetails.TargetType = TargetType.ReportGroup.ToString();
                rootRepGroupNode.Value   = JsSerializer.Serialize(targetDetails);
                if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + PathHelper.GetModulePath_Nuke() + "Images\\TreeView\\group.png"))
                {
                    rootRepGroupNode.ImageUrl = PathHelper.GetModuleUrl_Nuke() + "Images/TreeView/group.png";
                }
                this.trvReports_Reports.Nodes.Add(rootRepGroupNode);
                rootRepGroupNode.Expanded = true;



                switch (Ls)
                {
                case LoadSttate.Normal:
                    this.GetChildItem_trvReports_Reports(rootRepGroupNode, rootRepGroup, reportsList);
                    break;

                case LoadSttate.Search:
                    if (!string.IsNullOrEmpty(SearchItem))
                    {
                        this.GetChildItem_trvReports_Reports(rootRepGroupNode, rootRepGroup, reportsList.Where(c => c.Name.Contains(SearchItem) || c.IsReport == false).ToList());
                    }
                    else
                    {
                        this.GetChildItem_trvReports_Reports(rootRepGroupNode, rootRepGroup, reportsList);
                    }
                    break;
                }
            }
        }
        catch (UIValidationExceptions ex)
        {
            retMessage = this.exceptionHandler.HandleException(this.Page, ExceptionTypes.UIValidationExceptions, ex, retMessage);
            this.ErrorHiddenField_Reports.Value = this.exceptionHandler.CreateErrorMessage(retMessage);
        }
        catch (UIBaseException ex)
        {
            retMessage = this.exceptionHandler.HandleException(this.Page, ExceptionTypes.UIBaseException, ex, retMessage);
            this.ErrorHiddenField_Reports.Value = this.exceptionHandler.CreateErrorMessage(retMessage);
        }
        catch (Exception ex)
        {
            retMessage = this.exceptionHandler.HandleException(this.Page, ExceptionTypes.Exception, ex, retMessage);
            this.ErrorHiddenField_Reports.Value = this.exceptionHandler.CreateErrorMessage(retMessage);
        }
    }
        /// <summary>
        /// This function allows to download a specific file
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="targetPath"></param>
        /// <param name="delProgress"></param>
        /// <returns></returns>        
        public void DownloadFile(String filePath, String targetPath, FileOperationProgressChanged delProgress)
        {
            // check parameter
            if (filePath == null || targetPath == null)
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidParameters);

            // get path and filename
            var ph = new PathHelper(filePath);
            String dir = ph.GetDirectoryName();
            String file = ph.GetFileName();

            // check if we are in root
            if (dir.Length == 0)
                dir = "/";

            // get parent container
            ICloudDirectoryEntry container = GetFolder(dir);

            // download file
            DownloadFile(container, file, targetPath, delProgress);
        }
Beispiel #13
0
 /// <summary>
 /// 获取某 action 的模板文件的绝对路径(包括模板的后缀名)
 /// </summary>
 /// <param name="action"></param>
 /// <returns></returns>
 public String getTemplatePathByAction(String action)
 {
     return(PathHelper.Map(getControllerDir() + "/" + action + MvcConfig.Instance.ViewExt));
 }
        public static bool DownloadSolution(string SolutionFolder, bool undoSolutionLocalChanges = false)
        {
            try
            {
                SourceControlBase mSourceControl;
                if (WorkSpace.Instance.UserProfile.SourceControlType == SourceControlBase.eSourceControlType.GIT)
                {
                    mSourceControl = new GITSourceControl();
                }
                else if (WorkSpace.Instance.UserProfile.SourceControlType == SourceControlBase.eSourceControlType.SVN)
                {
                    mSourceControl = RepositoryItemHelper.RepositoryItemFactory.GetNewSVnRepo();
                }
                else
                {
                    mSourceControl = RepositoryItemHelper.RepositoryItemFactory.GetNewSVnRepo();
                }

                if (mSourceControl != null)
                {
                    WorkSpace.Instance.UserProfile.SourceControlType = mSourceControl.GetSourceControlType;
                    mSourceControl.SourceControlURL         = WorkSpace.Instance.UserProfile.SourceControlURL;
                    mSourceControl.SourceControlUser        = WorkSpace.Instance.UserProfile.SourceControlUser;
                    mSourceControl.SourceControlPass        = WorkSpace.Instance.UserProfile.SourceControlPass;
                    mSourceControl.SourceControlLocalFolder = WorkSpace.Instance.UserProfile.SourceControlLocalFolder;
                    mSourceControl.SolutionFolder           = SolutionFolder;

                    mSourceControl.SourceControlConfigureProxy = WorkSpace.Instance.UserProfile.SolutionSourceControlConfigureProxy;
                    mSourceControl.SourceControlProxyAddress   = WorkSpace.Instance.UserProfile.SolutionSourceControlProxyAddress;
                    mSourceControl.SourceControlProxyPort      = WorkSpace.Instance.UserProfile.SolutionSourceControlProxyPort;
                    mSourceControl.SourceControlTimeout        = WorkSpace.Instance.UserProfile.SolutionSourceControlTimeout;
                    mSourceControl.supressMessage = true;
                }

                if (WorkSpace.Instance.UserProfile.SourceControlLocalFolder == string.Empty)
                {
                    Reporter.ToUser(eUserMsgKey.SourceControlConnMissingLocalFolderInput);
                }
                if (SolutionFolder.EndsWith("\\"))
                {
                    SolutionFolder = SolutionFolder.Substring(0, SolutionFolder.Length - 1);
                }

                SolutionInfo sol = new SolutionInfo();
                sol.LocalFolder = SolutionFolder;
                if (WorkSpace.Instance.UserProfile.SourceControlType == SourceControlBase.eSourceControlType.SVN && Directory.Exists(PathHelper.GetLongPath(sol.LocalFolder + Path.DirectorySeparatorChar + @".svn")))
                {
                    sol.ExistInLocaly = true;
                }
                else if (WorkSpace.Instance.UserProfile.SourceControlType == SourceControlBase.eSourceControlType.GIT && Directory.Exists(PathHelper.GetLongPath(sol.LocalFolder + Path.DirectorySeparatorChar + @".git")))
                {
                    sol.ExistInLocaly = true;
                }
                else
                {
                    sol.ExistInLocaly = false;
                }

                sol.SourceControlLocation = SolutionFolder.Substring(SolutionFolder.LastIndexOf(Path.DirectorySeparatorChar) + 1);

                if (sol == null)
                {
                    Reporter.ToUser(eUserMsgKey.AskToSelectSolution);
                    return(false);
                }

                string ProjectURI = string.Empty;
                if (WorkSpace.Instance.UserProfile.SourceControlType == SourceControlBase.eSourceControlType.SVN)
                {
                    ProjectURI = WorkSpace.Instance.UserProfile.SourceControlURL.StartsWith("SVN", StringComparison.CurrentCultureIgnoreCase) ?
                                 sol.SourceControlLocation : WorkSpace.Instance.UserProfile.SourceControlURL + sol.SourceControlLocation;
                }
                else
                {
                    ProjectURI = WorkSpace.Instance.UserProfile.SourceControlURL;
                }
                bool getProjectResult = true;
                getProjectResult = SourceControlIntegration.CreateConfigFile(mSourceControl);
                if (getProjectResult != true)
                {
                    return(false);
                }

                if (sol.ExistInLocaly == true)
                {
                    mSourceControl.RepositoryRootFolder = sol.LocalFolder;
                    if (undoSolutionLocalChanges)
                    {
                        Reporter.ToLog(eLogLevel.INFO, "Reverting local Solution changes");
                        try
                        {
                            RepositoryItemHelper.RepositoryItemFactory.Revert(sol.LocalFolder, mSourceControl);
                        }
                        catch (Exception ex)
                        {
                            Reporter.ToLog(eLogLevel.ERROR, "Failed to revert local Solution changes, error: " + ex.Message);
                        }
                    }
                    return(RepositoryItemHelper.RepositoryItemFactory.GetLatest(sol.LocalFolder, mSourceControl));
                }
                else
                {
                    return(getProjectResult = SourceControlIntegration.GetProject(mSourceControl, sol.LocalFolder, ProjectURI));
                }
            }
            catch (Exception e)
            {
                Reporter.ToLog(eLogLevel.ERROR, "Error occurred while Downloading/Updating Solution from source control", e);
                return(false);
            }
        }
 public static string CleanUriToFilename(Uri uri)
 {
     return(PathHelper.GetValidPath(WebUtility.UrlDecode(uri.ToString())));
 }
        /// <summary>
        /// This method returns a filesystem object, this can be files or folders
        /// </summary>
        /// <param name="path"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public ICloudFileSystemEntry GetFileSystemObject(string path, ICloudDirectoryEntry parent)
        {
            /*
             * This section generates for every higher object the object tree
             */
            PathHelper ph = new PathHelper(path);
            String[] elements = ph.GetPathElements();

            // create the virtual root
            ICloudDirectoryEntry current = parent ?? GetRoot();

            // build the root

            // check if we request only the root
            if (path.Equals("/"))
                return current;

            if (_Service.SupportsDirectRetrieve)
            {
                //Request directly
                return _Service.RequestResource(_Session, path.TrimStart('/'), current);
            }

            // create the path tree
            for (int i = 0; i <= elements.Length - 1; i++)
            {
                String elem = elements[i];

                if (i == elements.Length - 1)
                {
                    return current.GetChild(elem, false);
                }

                try
                {
                    current = current.GetChild(elem, true) as ICloudDirectoryEntry;
                }
                catch (SharpBoxException e)
                {
                    // if not found, create a virtual one
                    if (e.ErrorCode == SharpBoxErrorCodes.ErrorFileNotFound)
                        current = GenericStorageProviderFactory.CreateDirectoryEntry(_Session, elem, current);
                    else
                        throw;
                }
            }

            // looks like an error
            return null;
        }
        /// <summary>
        /// This mehtod allows to perform a server side renam operation which is basicly the same
        /// then a move operation in the same directory
        /// </summary>
        /// <param name="filePath">File or directory which has to be renamed</param>
        /// <param name="newName">The new name of the targeted filesystem object</param>
        /// <returns></returns>        
        public bool RenameFileSystemEntry(String filePath, String newName)
        {
            // check parameter
            if ((filePath == null) || (newName == null))
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidParameters);

            // get path and filename
            var ph = new PathHelper(filePath);
            String dir = ph.GetDirectoryName();
            String file = ph.GetFileName();

            // check if we are in root
            if (dir.Length == 0)
                dir = "/";

            // get parent container
            ICloudDirectoryEntry container = GetFolder(dir);

            // get filesystem entry
            ICloudFileSystemEntry fsEntry = GetFileSystemObject(file, container);

            // rename file
            return RenameFileSystemEntry(fsEntry, newName);
        }
        public static WebDavRequestResult CreateObjectsFromNetworkStream(Stream data, String targetUrl, IStorageProviderService service, IStorageProviderSession session, NameBaseFilterCallback callback)
        {
            var config = session.ServiceConfiguration as WebDavConfiguration;
            var results = new WebDavRequestResult();

            var queryLessUri = HttpUtilityEx.GetPathAndQueryLessUri(config.ServiceLocator).ToString().TrimEnd('/');
            var decodedTargetUrl = HttpUtility.UrlDecode(targetUrl);
                
            var s = new StreamReader(data).ReadToEnd();
            //todo:
            var xDoc = XDocument.Load(new StringReader(s.Replace("d:d:", "d:")));
            var responses = xDoc.Descendants(XName.Get("response", DavNamespace));

            foreach (var response in responses)
            {
                bool isHidden = false;
                bool isDirectory = false;
                DateTime lastModified = DateTime.Now;
                long contentLength = 0;

                var href = response.Element(XName.Get("href", DavNamespace)).ValueOrEmpty();
                var propstats = response.Descendants(XName.Get("propstat", DavNamespace));
                foreach (var propstat in propstats)
                {
                    var prop = propstat.Element(XName.Get("prop", DavNamespace));
                    var status = propstat.Element(XName.Get("status", DavNamespace)).ValueOrEmpty();

                    if (!status.Equals(HttpOk) || prop == null) continue;

                    var strLastModified = prop.Element(XName.Get("getlastmodified", DavNamespace)).ValueOrEmpty();
                    var strContentLength = prop.Element(XName.Get("getcontentlength", DavNamespace)).ValueOrEmpty();
                    var resourceType = prop.Element(XName.Get("resourcetype", DavNamespace));
                    var strIsHidden = prop.Element(XName.Get("ishidden", DavNamespace)).ValueOrEmpty();

                    if (!String.IsNullOrEmpty(strIsHidden))
                    {
                        int code;
                        if (!int.TryParse(strIsHidden, out code))
                            code = 0;
                        isHidden = Convert.ToBoolean(code);
                    }
                    if (resourceType.Element(XName.Get("collection", DavNamespace)) != null)
                        isDirectory = true;
                    if (!String.IsNullOrEmpty(strContentLength))
                        contentLength = Convert.ToInt64(strContentLength);
                    if (!String.IsNullOrEmpty(strLastModified))
                        DateTime.TryParse(strLastModified, out lastModified);
                }

                //entry not to be encluded
                if (isHidden) continue;

                var nameBase = href;

                if (callback != null)
                    nameBase = callback(targetUrl, service, session, nameBase);

                String nameBaseForSelfCheck;

                if (nameBase.StartsWith(config.ServiceLocator.ToString()))
                {
                    nameBaseForSelfCheck = HttpUtility.UrlDecode(nameBase);
                    nameBase = nameBase.Remove(0, config.ServiceLocator.ToString().Length);
                }
                else
                {
                    nameBaseForSelfCheck = queryLessUri + HttpUtilityEx.PathDecodeUTF8(nameBase);
                }

                nameBase = nameBase.TrimEnd('/');
                nameBaseForSelfCheck = nameBaseForSelfCheck.TrimEnd('/');
                if (targetUrl.EndsWith("/"))
                    nameBaseForSelfCheck += "/";

                bool isSelf = nameBaseForSelfCheck.Equals(decodedTargetUrl);

                var ph = new PathHelper(nameBase);
                var resourceName = HttpUtility.UrlDecode(ph.GetFileName());

                BaseFileEntry entry = !isDirectory
                                          ? new BaseFileEntry(resourceName, contentLength, lastModified, service, session)
                                          : new BaseDirectoryEntry(resourceName, contentLength, lastModified, service, session);

                if (isSelf)
                {
                    results.Self = entry;
                }
                else
                {
                    results.Childs.Add(entry);
                }
            }

            return results;
        }
Beispiel #19
0
 public void Should_parse_CSProj_NewComplex_csproj_file_correctly()
 {
     Should_parse_csproj_file_correctly(PathHelper.SanitizeDirectorySeparatorChar(@"Data\CSProj_NewComplex\sampleCsProjectfile.csproj"), GenerationTargetLanguage.CSharp, "Hacapp.Web.Tests.UI", "Hacapp.Web.Tests.UI", "sampleCsProjectfile");
 }
 public QuotesDataConverter(PathHelper pathHelper)
 {
     _pathHelper = pathHelper;
 }
Beispiel #21
0
 public Task DownloadDependedCssFiles(string cssContent, PathHelper uriConv)
 {
     var files = GetUniqueFiles(cssContent, uriConv);
     Parallel.ForEach(files, async fileInfo =>
     {
         using (var webClient = new HttpClient())
         {
             try
             {
                 var file = await webClient.GetByteArrayAsync(new Uri(fileInfo.RemotePath));
                 Directory.CreateDirectory(GetDirectoryName(fileInfo.LocalPath));
                 File.WriteAllBytes(fileInfo.LocalPath, file);
             }
             catch (HttpRequestException ex)
             {
                 throw new FileNotFoundException($"The remote file:{fileInfo.RemotePath} cannot be found.", ex);
             }
         }
     });
     return Task.FromResult(0);
 }
		private void InitDependencies()
		{
			DependencyFactory.Container.RegisterInstance(new RichTextBoxAppender(rtbLog));

			_logger = DependencyFactory.Container.Resolve<IMyLogger>(new ParameterOverride("currentClassName", "MainForm"));
			_quotesDataConverter = (QuotesDataConverter)DependencyFactory.Container.Resolve<IDataConverter>("Quotes");
			_fundamentalDataConverter =
				(FundamentalDataConverter)DependencyFactory.Container.Resolve<IDataConverter>("Fundamental");
			_pathHelper = DependencyFactory.Container.Resolve<PathHelper>();
		}
        /// <summary>
        /// This function allows to create full folder pathes in the cloud storage
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public ICloudDirectoryEntry CreateFolder(String path)
        {
            // get the path elemtens
            var ph = new PathHelper(path);

            // check parameter
            if (!ph.IsPathRooted())
                return null;

            // start creation
            return CreateFolderEx(path, GetRoot());
        }
        /// <summary>
        /// This method creates a new file object in the cloud storage. Use the GetContentStream method to 
        /// get a .net stream which usable in the same way then local stream are usable
        /// </summary>
		/// <param name="filePath">The name of the targeted file</param>
        /// <returns></returns>        
        public ICloudFileSystemEntry CreateFile(String filePath)
        {
            // check parameter
            if (filePath == null)
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidParameters);

            // get path and filename
            var ph = new PathHelper(filePath);
            String dir = ph.GetDirectoryName();
            String file = ph.GetFileName();

            // check if we are in root
            if (dir.Length == 0)
                dir = "/";

            // get parent container
            ICloudDirectoryEntry container = GetFolder(dir);

            // rename file
            return CreateFile(container, file);
        }
Beispiel #25
0
 public AnalysisService(DumpStorageFilebased dumpStorage, DumpRepository dumpRepo, BundleRepository bundleRepo, PathHelper pathHelper, IOptions <SuperDumpSettings> settings, NotificationService notifications, ElasticSearchService elasticSearch)
 {
     this.dumpStorage   = dumpStorage;
     this.dumpRepo      = dumpRepo;
     this.bundleRepo    = bundleRepo;
     this.pathHelper    = pathHelper;
     this.settings      = settings;
     this.notifications = notifications;
     this.elasticSearch = elasticSearch;
 }
        public static ReverseEngineerResult GenerateFiles(ReverseEngineerCommandOptions options)
        {
            var errors   = new List <string>();
            var warnings = new List <string>();
            var reporter = new OperationReporter(
                new OperationReportHandler(
                    m => errors.Add(m),
                    m => warnings.Add(m)));
            var serviceProvider = ServiceProviderBuilder.Build(options);
            var scaffolder      = serviceProvider.GetService <IReverseEngineerScaffolder>();
            var schemas         = new List <string>();

            options.ConnectionString = SqlServerHelper.SetConnectionString(options.DatabaseType, options.ConnectionString);

            if (options.DefaultDacpacSchema != null)
            {
                schemas.Add(options.DefaultDacpacSchema);
            }

            if (options.FilterSchemas)
            {
                schemas.AddRange(options.Schemas.Select(s => s.Name));
            }

            if (options.UseNoObjectFilter)
            {
                options.Tables = new List <SerializationTableModel>();
            }

            var outputDir = !string.IsNullOrEmpty(options.OutputPath)
               ? Path.IsPathFullyQualified(options.OutputPath)
                    ? options.OutputPath
                    : Path.GetFullPath(Path.Combine(options.ProjectPath, options.OutputPath))
                : options.ProjectPath;

            var outputContextDir = !string.IsNullOrEmpty(options.OutputContextPath)
               ? Path.IsPathFullyQualified(options.OutputContextPath)
                    ? options.OutputContextPath
                    : Path.GetFullPath(Path.Combine(options.ProjectPath, options.OutputContextPath))
                : outputDir;

            var modelNamespace   = string.Empty;
            var contextNamespace = string.Empty;

            if (string.IsNullOrEmpty(options.ProjectRootNamespace))
            {
                modelNamespace = !string.IsNullOrEmpty(options.ModelNamespace)
                    ? options.ModelNamespace
                    : PathHelper.GetNamespaceFromOutputPath(outputDir, options.ProjectPath, options.ProjectRootNamespace);

                contextNamespace = !string.IsNullOrEmpty(options.ContextNamespace)
                    ? options.ContextNamespace
                    : PathHelper.GetNamespaceFromOutputPath(outputContextDir, options.ProjectPath, options.ProjectRootNamespace);
            }
            else
            {
                modelNamespace = !string.IsNullOrEmpty(options.ModelNamespace)
                    ? options.ProjectRootNamespace + "." + options.ModelNamespace
                    : PathHelper.GetNamespaceFromOutputPath(outputDir, options.ProjectPath, options.ProjectRootNamespace);

                contextNamespace = !string.IsNullOrEmpty(options.ContextNamespace)
                    ? options.ProjectRootNamespace + "." + options.ContextNamespace
                    : PathHelper.GetNamespaceFromOutputPath(outputContextDir, options.ProjectPath, options.ProjectRootNamespace);
            }

            var             entityTypeConfigurationPaths = new List <string>();
            SavedModelFiles procedurePaths = null;
            SavedModelFiles functionPaths  = null;

            SavedModelFiles filePaths = ReverseEngineerScaffolder.GenerateDbContext(options, serviceProvider, schemas, outputContextDir, modelNamespace, contextNamespace);

            if (options.SelectedToBeGenerated != 2)
            {
                procedurePaths = ReverseEngineerScaffolder.GenerateStoredProcedures(options, ref errors, serviceProvider, outputContextDir, modelNamespace, contextNamespace);

                functionPaths = ReverseEngineerScaffolder.GenerateFunctions(options, ref errors, serviceProvider, outputContextDir, modelNamespace, contextNamespace);
#if CORE50
#else
                RemoveOnConfiguring(filePaths.ContextFile, options.IncludeConnectionString);
#endif
                if (!options.UseHandleBars)
                {
                    PostProcess(filePaths.ContextFile);
                }

                entityTypeConfigurationPaths = SplitDbContext(filePaths.ContextFile, options.UseDbContextSplitting, contextNamespace, options.UseNullableReferences);
            }
            else if (options.SelectedToBeGenerated == 2 &&
                     (options.Tables.Count(t => t.ObjectType == ObjectType.Procedure) > 0 ||
                      options.Tables.Count(t => t.ObjectType == ObjectType.ScalarFunction) > 0))
            {
                warnings.Add("Selected stored procedures/scalar functions will not be generated, as 'Entity Types only' was selected");
            }

            if (!options.UseHandleBars)
            {
                foreach (var file in filePaths.AdditionalFiles)
                {
                    PostProcess(file);
                }
            }

            var cleanUpPaths = CreateCleanupPaths(procedurePaths, functionPaths, filePaths);

            CleanUp(cleanUpPaths, entityTypeConfigurationPaths);

            var allfiles = filePaths.AdditionalFiles.ToList();
            if (procedurePaths != null)
            {
                allfiles.AddRange(procedurePaths.AdditionalFiles);
                allfiles.Add(procedurePaths.ContextFile);
            }
            if (functionPaths != null)
            {
                allfiles.AddRange(functionPaths.AdditionalFiles);
                allfiles.Add(functionPaths.ContextFile);
            }

            var result = new ReverseEngineerResult
            {
                EntityErrors                  = errors,
                EntityWarnings                = warnings,
                EntityTypeFilePaths           = allfiles,
                ContextFilePath               = filePaths.ContextFile,
                ContextConfigurationFilePaths = entityTypeConfigurationPaths,
            };

            return(result);
        }
Beispiel #27
0
 //Ignore duplicate urls and fontface tricks like '../fonts/fontawesome-webfont.eot?#iefix&v=4.3.0'
 //But still downloading the correct version
 public static IEnumerable<FileInfo> GetUniqueFiles(string cssContent, PathHelper uriConv)
 {
     cssContent = CommentRemove.Replace(cssContent, "");
     var urls =
         from Match url in Urls.Matches(cssContent)
         where !url.Groups["url"].Value.Trim(' ').StartsWith("http://", StringComparison.OrdinalIgnoreCase)
         group url by uriConv.GetLocalPath(url.Groups["url"].Value)
         into g
         select
             new FileInfo { RemotePath = uriConv.GetRemotePath(g.First().Groups["url"].Value), LocalPath = g.Key };
     return urls;
 }
Beispiel #28
0
        public async Task <IActionResult> DownloadExportFile(int id, string name, bool?isDeployment)
        {
            if (PathHelper.HasInvalidFileNameChars(name))
            {
                throw new BadHttpRequestException("Invalid file name: " + name.NaIfEmpty());
            }

            string message = null;
            IFile  file    = null;

            if (await Services.Permissions.AuthorizeAsync(Permissions.Configuration.Export.Read))
            {
                if (isDeployment ?? false)
                {
                    var deployment = await _db.ExportDeployments.FindByIdAsync(id, false);

                    if (deployment != null)
                    {
                        var deploymentDir = await _exportProfileService.GetDeploymentDirectoryAsync(deployment);

                        file = await deploymentDir?.GetFileAsync(name);
                    }
                }
                else
                {
                    var profile = await _db.ExportProfiles.FindByIdAsync(id, false);

                    if (profile != null)
                    {
                        var dir = await _exportProfileService.GetExportDirectoryAsync(profile, "Content");

                        file = await dir.GetFileAsync(name);

                        if (!(file?.Exists ?? false))
                        {
                            file = await dir.Parent.GetFileAsync(name);
                        }
                    }
                }

                if (file?.Exists ?? false)
                {
                    try
                    {
                        var stream = await file.OpenReadAsync();

                        return(new FileStreamResult(stream, MimeTypes.MapNameToMimeType(file.PhysicalPath))
                        {
                            FileDownloadName = file.Name
                        });
                    }
                    catch (IOException)
                    {
                        message = T("Admin.Common.FileInUse");
                    }
                }
            }
            else
            {
                message = T("Admin.AccessDenied.Description");
            }

            if (message.IsEmpty())
            {
                message = T("Admin.Common.ResourceNotFound");
            }

            return(File(Encoding.UTF8.GetBytes(message), MediaTypeNames.Text.Plain, "DownloadExportFile.txt"));
        }
Beispiel #29
0
 internal static unsafe string NormalizePath(string path, bool fullCheck, int maxPathLength)
 {
     if (fullCheck)
       {
     path = path.TrimEnd(Path.TrimEndChars);
     Path.CheckInvalidPathChars(path);
       }
       int index1 = 0;
       PathHelper pathHelper;
       if (path.Length <= Path.MaxPath)
       {
     char* charArrayPtr = stackalloc char[Path.MaxPath];
     pathHelper = new PathHelper(charArrayPtr, Path.MaxPath);
       }
       else
     pathHelper = new PathHelper(path.Length + Path.MaxPath, maxPathLength);
       uint num1 = 0U;
       uint num2 = 0U;
       bool flag1 = false;
       uint num3 = 0U;
       int num4 = -1;
       bool flag2 = false;
       bool flag3 = true;
       bool flag4 = false;
       int num5 = 0;
       if (path.Length > 0 && ((int) path[0] == (int) Path.DirectorySeparatorChar || (int) path[0] == (int) Path.AltDirectorySeparatorChar))
       {
     pathHelper.Append('\\');
     ++index1;
     num4 = 0;
       }
       for (; index1 < path.Length; ++index1)
       {
     char ch1 = path[index1];
     if ((int) ch1 == (int) Path.DirectorySeparatorChar || (int) ch1 == (int) Path.AltDirectorySeparatorChar)
     {
       if ((int) num3 == 0)
       {
     if (num2 > 0U)
     {
       int index2 = num4 + 1;
       if ((int) path[index2] != 46)
         throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
       if (num2 >= 2U)
       {
         if (flag2 && num2 > 2U)
           throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
         if ((int) path[index2 + 1] == 46)
         {
           for (int index3 = index2 + 2; (long) index3 < (long) index2 + (long) num2; ++index3)
           {
             if ((int) path[index3] != 46)
               throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
           }
           num2 = 2U;
         }
         else
         {
           if (num2 > 1U)
             throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
           num2 = 1U;
         }
       }
       if ((int) num2 == 2)
         pathHelper.Append('.');
       pathHelper.Append('.');
       flag1 = false;
     }
     if (num1 > 0U && flag3 && index1 + 1 < path.Length && ((int) path[index1 + 1] == (int) Path.DirectorySeparatorChar || (int) path[index1 + 1] == (int) Path.AltDirectorySeparatorChar))
       pathHelper.Append(Path.DirectorySeparatorChar);
       }
       num2 = 0U;
       num1 = 0U;
       if (!flag1)
       {
     flag1 = true;
     pathHelper.Append(Path.DirectorySeparatorChar);
       }
       num3 = 0U;
       num4 = index1;
       flag2 = false;
       flag3 = false;
       if (flag4)
       {
     pathHelper.TryExpandShortFileName();
     flag4 = false;
       }
       int num6 = pathHelper.Length - 1;
       if (num6 - num5 > Path.MaxDirectoryLength)
     throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
       num5 = num6;
     }
     else if ((int) ch1 == 46)
       ++num2;
     else if ((int) ch1 == 32)
     {
       ++num1;
     }
     else
     {
       if ((int) ch1 == 126)
     flag4 = true;
       flag1 = false;
       if (flag3 && (int) ch1 == (int) Path.VolumeSeparatorChar)
       {
     char ch2 = index1 > 0 ? path[index1 - 1] : ' ';
     if ((int) num2 != 0 || num3 < 1U || (int) ch2 == 32)
       throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
     flag2 = true;
     if (num3 > 1U)
     {
       int index2 = 0;
       while (index2 < pathHelper.Length && (int) pathHelper[index2] == 32)
         ++index2;
       if ((long) num3 - (long) index2 == 1L)
       {
         pathHelper.Length = 0;
         pathHelper.Append(ch2);
       }
     }
     num3 = 0U;
       }
       else
     num3 += 1U + num2 + num1;
       if (num2 > 0U || num1 > 0U)
       {
     int num6 = num4 >= 0 ? index1 - num4 - 1 : index1;
     if (num6 > 0)
     {
       for (int index2 = 0; index2 < num6; ++index2)
         pathHelper.Append(path[num4 + 1 + index2]);
     }
     num2 = 0U;
     num1 = 0U;
       }
       pathHelper.Append(ch1);
       num4 = index1;
     }
       }
       if (pathHelper.Length - 1 - num5 > Path.MaxDirectoryLength)
     throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
       if ((int) num3 == 0 && num2 > 0U)
       {
     int index2 = num4 + 1;
     if ((int) path[index2] != 46)
       throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
     if (num2 >= 2U)
     {
       if (flag2 && num2 > 2U)
     throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
       if ((int) path[index2 + 1] == 46)
       {
     for (int index3 = index2 + 2; (long) index3 < (long) index2 + (long) num2; ++index3)
     {
       if ((int) path[index3] != 46)
         throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
     }
     num2 = 2U;
       }
       else
       {
     if (num2 > 1U)
       throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
     num2 = 1U;
       }
     }
     if ((int) num2 == 2)
       pathHelper.Append('.');
     pathHelper.Append('.');
       }
       if (pathHelper.Length == 0)
     throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
       if (fullCheck && (pathHelper.OrdinalStartsWith("http:", false) || pathHelper.OrdinalStartsWith("file:", false)))
     throw new ArgumentException(Environment.GetResourceString("Argument_PathUriFormatNotSupported"));
       if (flag4)
     pathHelper.TryExpandShortFileName();
       int num7 = 1;
       if (fullCheck)
       {
     num7 = pathHelper.GetFullPathName();
     bool flag5 = false;
     for (int index2 = 0; index2 < pathHelper.Length && !flag5; ++index2)
     {
       if ((int) pathHelper[index2] == 126)
     flag5 = true;
     }
     if (flag5 && !pathHelper.TryExpandShortFileName())
     {
       int lastSlash = -1;
       for (int index2 = pathHelper.Length - 1; index2 >= 0; --index2)
       {
     if ((int) pathHelper[index2] == (int) Path.DirectorySeparatorChar)
     {
       lastSlash = index2;
       break;
     }
       }
       if (lastSlash >= 0)
       {
     if (pathHelper.Length >= maxPathLength)
       throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
     int lenSavedName = pathHelper.Length - lastSlash - 1;
     pathHelper.Fixup(lenSavedName, lastSlash);
       }
     }
       }
       if (num7 != 0 && pathHelper.Length > 1 && ((int) pathHelper[0] == 92 && (int) pathHelper[1] == 92))
       {
     int index2;
     for (index2 = 2; index2 < num7; ++index2)
     {
       if ((int) pathHelper[index2] == 92)
       {
     ++index2;
     break;
       }
     }
     if (index2 == num7)
       throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegalUNC"));
     if (pathHelper.OrdinalStartsWith("\\\\?\\globalroot", true))
       throw new ArgumentException(Environment.GetResourceString("Arg_PathGlobalRoot"));
       }
       if (pathHelper.Length >= maxPathLength)
     throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
       if (num7 == 0)
       {
     int errorCode = Marshal.GetLastWin32Error();
     if (errorCode == 0)
       errorCode = 161;
     __Error.WinIOError(errorCode, path);
     return (string) null;
       }
       else
       {
     string a = pathHelper.ToString();
     if (string.Equals(a, path, StringComparison.Ordinal))
       a = path;
     return a;
       }
 }
        /// <summary>
        /// This function allows to create full folder pathes in the cloud storage
        /// </summary>
        /// <param name="path"></param>
        /// <param name="entry"></param>
        /// <returns></returns>
        public ICloudDirectoryEntry CreateFolderEx(String path, ICloudDirectoryEntry entry)
        {
            // get the path elemtens
            var ph = new PathHelper(path);

            String[] pes = ph.GetPathElements();

            // check which elements are existing            
            foreach (String el in pes)
            {
                // check if subfolder exists, if it doesn't, create it
                ICloudDirectoryEntry cur = GetFolder(el, entry, false);

                // create if needed
                if (cur == null)
                {
                    ICloudDirectoryEntry newFolder = CreateFolder(el, entry);
                    if (newFolder == null)
                        throw new SharpBoxException(SharpBoxErrorCodes.ErrorCreateOperationFailed);
                    else
                        cur = newFolder;
                }

                // go ahead
                entry = cur;
            }

            // return 
            return entry;
        }
Beispiel #31
0
 public void Should_parse_ToolsVersion4_vbproj_file_correctly()
 {
     Should_parse_csproj_file_correctly(PathHelper.SanitizeDirectorySeparatorChar(@"Data\VBProj_ToolsVersion_4\sampleCsProjectfile.vbproj"), GenerationTargetLanguage.VB, "Hacapp.Web.Tests.UI", "Hacapp.Web.Tests.UI", "sampleCsProjectfile");
 }
Beispiel #32
0
 public bool InRange(Point2D p, int range)
 {
     return(PathHelper.InRange(X - p.X, Y - p.Y, range));
 }
Beispiel #33
0
        public static WebDavRequestResult CreateObjectsFromNetworkStream(Stream data, String targetUrl, IStorageProviderService service, IStorageProviderSession session, NameBaseFilterCallback callback)
        {
            var config  = session.ServiceConfiguration as WebDavConfiguration;
            var results = new WebDavRequestResult();

            var queryLessUri     = HttpUtilityEx.GetPathAndQueryLessUri(config.ServiceLocator).ToString().TrimEnd('/');
            var decodedTargetUrl = HttpUtility.UrlDecode(targetUrl);

            var s = new StreamReader(data).ReadToEnd();
            //todo:
            var xDoc      = XDocument.Load(new StringReader(s.Replace("d:d:", "d:")));
            var responses = xDoc.Descendants(XName.Get("response", DavNamespace));

            foreach (var response in responses)
            {
                bool     isHidden      = false;
                bool     isDirectory   = false;
                DateTime lastModified  = DateTime.Now;
                long     contentLength = 0;

                var href      = response.Element(XName.Get("href", DavNamespace)).ValueOrEmpty();
                var propstats = response.Descendants(XName.Get("propstat", DavNamespace));
                foreach (var propstat in propstats)
                {
                    var prop   = propstat.Element(XName.Get("prop", DavNamespace));
                    var status = propstat.Element(XName.Get("status", DavNamespace)).ValueOrEmpty();

                    if (!status.Equals(HttpOk) || prop == null)
                    {
                        continue;
                    }

                    var strLastModified  = prop.Element(XName.Get("getlastmodified", DavNamespace)).ValueOrEmpty();
                    var strContentLength = prop.Element(XName.Get("getcontentlength", DavNamespace)).ValueOrEmpty();
                    var resourceType     = prop.Element(XName.Get("resourcetype", DavNamespace));
                    var strIsHidden      = prop.Element(XName.Get("ishidden", DavNamespace)).ValueOrEmpty();

                    if (!String.IsNullOrEmpty(strIsHidden))
                    {
                        int code;
                        if (!int.TryParse(strIsHidden, out code))
                        {
                            code = 0;
                        }
                        isHidden = Convert.ToBoolean(code);
                    }
                    if (resourceType.Element(XName.Get("collection", DavNamespace)) != null)
                    {
                        isDirectory = true;
                    }
                    if (!String.IsNullOrEmpty(strContentLength))
                    {
                        contentLength = Convert.ToInt64(strContentLength);
                    }
                    if (!String.IsNullOrEmpty(strLastModified) && DateTime.TryParse(strLastModified, out lastModified))
                    {
                        lastModified = lastModified.ToUniversalTime();
                    }
                }

                //entry not to be encluded
                if (isHidden)
                {
                    continue;
                }

                var nameBase = href;

                if (callback != null)
                {
                    nameBase = callback(targetUrl, service, session, nameBase);
                }

                String nameBaseForSelfCheck;

                if (nameBase.StartsWith(config.ServiceLocator.ToString()))
                {
                    nameBaseForSelfCheck = HttpUtility.UrlDecode(nameBase);
                    nameBase             = nameBase.Remove(0, config.ServiceLocator.ToString().Length);
                }
                else
                {
                    nameBaseForSelfCheck = queryLessUri + HttpUtilityEx.PathDecodeUTF8(nameBase);
                }

                nameBase             = nameBase.TrimEnd('/');
                nameBaseForSelfCheck = nameBaseForSelfCheck.TrimEnd('/');
                if (targetUrl.EndsWith("/"))
                {
                    nameBaseForSelfCheck += "/";
                }

                bool isSelf = nameBaseForSelfCheck.Equals(decodedTargetUrl);

                var ph           = new PathHelper(nameBase);
                var resourceName = HttpUtility.UrlDecode(ph.GetFileName());

                BaseFileEntry entry = !isDirectory
                                          ? new BaseFileEntry(resourceName, contentLength, lastModified, service, session)
                                          : new BaseDirectoryEntry(resourceName, contentLength, lastModified, service, session);

                if (isSelf)
                {
                    results.Self = entry;
                }
                else
                {
                    results.Childs.Add(entry);
                }
            }

            return(results);
        }
Beispiel #34
0
 public void Setup()
 {
     this.outputDirectory = PathHelper.GetTempDir();
 }
Beispiel #35
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // if qms file
            //      load it (it includes folder)
            // else
            //      load default qms

            // if not folder
            //      open dialog for folder
            //

            QuickMediaSorterProject qms = null;

            if ((args != null) && (args.Any()))
            {
                string path = args[0];
                if (PathHelper.IsFolder(path))
                {
                    // We have only path
                    // - Read or generate default project
                    qms = QmsFactory.GetDefault();
                    // - Set its path
                    qms.Folder = path;
                }
                else
                {
                    // We have a qms file - try to read it
                    try
                    {
                        qms = QmsFactory.Load(path);
                    }
                    catch (Exception ex)
                    {
                        ErrorHandler.Handle(ex, "Couldn't load file", true);
                    }
                }
            }
            else
            {
                // No arguments - read or generate default project
                qms = QmsFactory.GetDefault();
            }

            if (qms != null && qms.Folder == null)
            {
                // Our project has no folder - open browse window to the user
                String f = qms.Folder;
                if (DialogHelper.BrowseOpenFolderDialog(ref f))
                {
                    qms.Folder = f;
                }
            }

            qms.InitializeActions();

            MainWindow view = new MainWindow(qms);

            view.ReadFiles();

            Application.Run(view);
        }
Beispiel #36
0
 private bool IsBicepFile(string inputPath) => PathHelper.HasBicepExtension(PathHelper.FilePathToFileUrl(inputPath));
        private RuleSet CreateProjectRuleSetWithIncludes(int rules, string solutionRuleSetToInclude, IncludeType solutionIncludeType, RuleAction defaultAction = RuleAction.Warning, params string[] otherIncludes)
        {
            string projectRuleSetFilePath = Path.Combine(this.ProjectRuleSetFolder, Guid.NewGuid() + ".ruleset");
            string solutionInclude        = solutionIncludeType == IncludeType.AsIs ? solutionRuleSetToInclude : PathHelper.CalculateRelativePath(projectRuleSetFilePath, solutionRuleSetToInclude);

            string[] includes = new[] { solutionInclude };
            if ((otherIncludes?.Length ?? 0) > 0)
            {
                includes = includes.Concat(otherIncludes).ToArray();
            }

            RuleSet ruleSet = TestRuleSetHelper.CreateTestRuleSet(rules, includes);

            ruleSet.Rules.ToList().ForEach(r => r.Action = defaultAction);
            ruleSet.FilePath = projectRuleSetFilePath;
            ruleSet.WriteToFile(ruleSet.FilePath);

            this.temporaryFiles.AddFile(ruleSet.FilePath, false);

            return(ruleSet);
        }
 public UserSecretsTestFixture()
 {
     _disposables.Push(() => TryDelete(Path.GetDirectoryName(PathHelper.GetSecretsPathFromSecretsId(TestSecretsId))));
 }
Beispiel #39
0
        /// <summary>
        /// Deletes items from the project, and optionally from disk.
        /// Note: Delete and Remove commands are handled via IVsHierarchyDeleteHandler3, not by
        /// IAsyncCommandGroupHandler and first asks us we CanRemove nodes. If yes then RemoveAsync is called.
        /// We can remove only nodes that are standard and based on project items, i.e. nodes that
        /// are created by default IProjectDependenciesSubTreeProvider implementations and have
        /// DependencyNode.GenericDependencyFlags flags and IRule with Context != null, in order to obtain
        /// node's itemSpec. ItemSpec then used to remove a project item having same Include.
        /// </summary>
        /// <param name="nodes">The nodes that should be deleted.</param>
        /// <param name="deleteOptions">A value indicating whether the items should be deleted from disk as well as
        /// from the project file.
        /// </param>
        /// <exception cref="InvalidOperationException">Thrown when <see cref="IProjectTreeProvider.CanRemove"/>
        /// would return <c>false</c> for this operation.</exception>
        public override async Task RemoveAsync(IImmutableSet <IProjectTree> nodes,
                                               DeleteOptions deleteOptions = DeleteOptions.None)
        {
            if (deleteOptions.HasFlag(DeleteOptions.DeleteFromStorage))
            {
                throw new NotSupportedException();
            }

            // Get the list of shared import nodes.
            IEnumerable <IProjectTree> sharedImportNodes = nodes.Where(node =>
                                                                       node.Flags.Contains(DependencyTreeFlags.SharedProjectFlags));

            // Get the list of normal reference Item Nodes (this excludes any shared import nodes).
            IEnumerable <IProjectTree> referenceItemNodes = nodes.Except(sharedImportNodes);

            Assumes.NotNull(ActiveConfiguredProject);

            await _projectAccessor.OpenProjectForWriteAsync(ActiveConfiguredProject, project =>
            {
                // Handle the removal of normal reference Item Nodes (this excludes any shared import nodes).
                foreach (IProjectTree node in referenceItemNodes)
                {
                    if (node.BrowseObjectProperties?.Context == null)
                    {
                        // if node does not have an IRule with valid ProjectPropertiesContext we can not
                        // get its itemsSpec. If nodes provided by custom IProjectDependenciesSubTreeProvider
                        // implementation, and have some custom IRule without context, it is not a problem,
                        // since they would not have DependencyNode.GenericDependencyFlags and we would not
                        // end up here, since CanRemove would return false and Remove command would not show
                        // up for those nodes.
                        continue;
                    }

                    IProjectPropertiesContext nodeItemContext = node.BrowseObjectProperties.Context;
                    ProjectItem?unresolvedReferenceItem       = project.GetItemsByEvaluatedInclude(nodeItemContext.ItemName)
                                                                .FirstOrDefault(
                        (item, t) => string.Equals(item.ItemType, t, StringComparisons.ItemTypes),
                        nodeItemContext.ItemType);

                    Report.IfNot(unresolvedReferenceItem != null, "Cannot find reference to remove.");
                    if (unresolvedReferenceItem != null)
                    {
                        project.RemoveItem(unresolvedReferenceItem);
                    }
                }

                DependenciesSnapshot snapshot = _dependenciesSnapshotProvider.CurrentSnapshot;
                Requires.NotNull(snapshot, nameof(snapshot));
                if (snapshot == null)
                {
                    return;
                }

                // Handle the removal of shared import nodes.
                ProjectRootElement projectXml = project.Xml;
                foreach (IProjectTree sharedImportNode in sharedImportNodes)
                {
                    string sharedFilePath = UnconfiguredProject.MakeRelative(sharedImportNode.FilePath);
                    if (string.IsNullOrEmpty(sharedFilePath))
                    {
                        continue;
                    }

                    IDependency?sharedProjectDependency = snapshot.FindDependency(sharedFilePath, topLevel: true);
                    if (sharedProjectDependency != null)
                    {
                        sharedFilePath = sharedProjectDependency.Path;
                    }

                    // Find the import that is included in the evaluation of the specified ConfiguredProject that
                    // imports the project file whose full path matches the specified one.
                    IEnumerable <ResolvedImport> matchingImports = from import in project.Imports
                                                                   where import.ImportingElement.ContainingProject == projectXml &&
                                                                   PathHelper.IsSamePath(import.ImportedProject.FullPath, sharedFilePath)
                                                                   select import;
                    foreach (ResolvedImport importToRemove in matchingImports)
                    {
                        ProjectImportElement importingElementToRemove = importToRemove.ImportingElement;
                        Report.IfNot(importingElementToRemove != null,
                                     "Cannot find shared project reference to remove.");
                        if (importingElementToRemove != null)
                        {
                            importingElementToRemove.Parent.RemoveChild(importingElementToRemove);
                        }
                    }
                }
            });
        }
        internal static unsafe string NormalizePath(string path, bool fullCheck, int maxPathLength)
        {
            if (fullCheck)
            {
                path = path.TrimEnd(TrimEndChars);
                CheckInvalidPathChars(path);
            }
            int num = 0;
            PathHelper helper = null;
            if (path.Length <= MaxPath)
            {
                char* charArrayPtr = (char*) stackalloc byte[(((IntPtr) MaxPath) * 2)];
                helper = new PathHelper(charArrayPtr, MaxPath);
            }
            else
            {
                helper = new PathHelper(path.Length + MaxPath, maxPathLength);
            }
            uint num2 = 0;
            uint num3 = 0;
            bool flag = false;
            uint num4 = 0;
            int num5 = -1;
            bool flag2 = false;
            bool flag3 = true;
            bool flag4 = false;
            int num6 = 0;
            if ((path.Length > 0) && ((path[0] == DirectorySeparatorChar) || (path[0] == AltDirectorySeparatorChar)))
            {
                helper.Append('\\');
                num++;
                num5 = 0;
            }
            while (num < path.Length)
            {
                char ch = path[num];
                if ((ch == DirectorySeparatorChar) || (ch == AltDirectorySeparatorChar))
                {
                    if (num4 == 0)
                    {
                        if (num3 > 0)
                        {
                            int num7 = num5 + 1;
                            if (path[num7] != '.')
                            {
                                throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                            }
                            if (num3 >= 2)
                            {
                                if (flag2 && (num3 > 2))
                                {
                                    throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                                }
                                if (path[num7 + 1] == '.')
                                {
                                    for (int i = num7 + 2; i < (num7 + num3); i++)
                                    {
                                        if (path[i] != '.')
                                        {
                                            throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                                        }
                                    }
                                    num3 = 2;
                                }
                                else
                                {
                                    if (num3 > 1)
                                    {
                                        throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                                    }
                                    num3 = 1;
                                }
                            }
                            if (num3 == 2)
                            {
                                helper.Append('.');
                            }
                            helper.Append('.');
                            flag = false;
                        }
                        if ((((num2 > 0) && flag3) && ((num + 1) < path.Length)) && ((path[num + 1] == DirectorySeparatorChar) || (path[num + 1] == AltDirectorySeparatorChar)))
                        {
                            helper.Append(DirectorySeparatorChar);
                        }
                    }
                    num3 = 0;
                    num2 = 0;
                    if (!flag)
                    {
                        flag = true;
                        helper.Append(DirectorySeparatorChar);
                    }
                    num4 = 0;
                    num5 = num;
                    flag2 = false;
                    flag3 = false;
                    if (flag4)
                    {
                        helper.TryExpandShortFileName();
                        flag4 = false;
                    }
                    int num9 = helper.Length - 1;
                    if ((num9 - num6) > MaxDirectoryLength)
                    {
                        throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
                    }
                    num6 = num9;
                }
                else
                {
                    switch (ch)
                    {
                        case '.':
                            num3++;
                            goto Label_0352;

                        case ' ':
                            num2++;
                            goto Label_0352;

                        case '~':
                            flag4 = true;
                            break;
                    }
                    flag = false;
                    if (flag3 && (ch == VolumeSeparatorChar))
                    {
                        char ch2 = (num > 0) ? path[num - 1] : ' ';
                        if (((num3 != 0) || (num4 < 1)) || (ch2 == ' '))
                        {
                            throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                        }
                        flag2 = true;
                        if (num4 > 1)
                        {
                            int num10 = 0;
                            while ((num10 < helper.Length) && (helper[num10] == ' '))
                            {
                                num10++;
                            }
                            if ((num4 - num10) == 1L)
                            {
                                helper.Length = 0;
                                helper.Append(ch2);
                            }
                        }
                        num4 = 0;
                    }
                    else
                    {
                        num4 += (1 + num3) + num2;
                    }
                    if ((num3 > 0) || (num2 > 0))
                    {
                        int num11 = (num5 >= 0) ? ((num - num5) - 1) : num;
                        if (num11 > 0)
                        {
                            for (int j = 0; j < num11; j++)
                            {
                                helper.Append(path[(num5 + 1) + j]);
                            }
                        }
                        num3 = 0;
                        num2 = 0;
                    }
                    helper.Append(ch);
                    num5 = num;
                }
            Label_0352:
                num++;
            }
            if (((helper.Length - 1) - num6) > MaxDirectoryLength)
            {
                throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
            }
            if ((num4 == 0) && (num3 > 0))
            {
                int num13 = num5 + 1;
                if (path[num13] != '.')
                {
                    throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                }
                if (num3 >= 2)
                {
                    if (flag2 && (num3 > 2))
                    {
                        throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                    }
                    if (path[num13 + 1] == '.')
                    {
                        for (int k = num13 + 2; k < (num13 + num3); k++)
                        {
                            if (path[k] != '.')
                            {
                                throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                            }
                        }
                        num3 = 2;
                    }
                    else
                    {
                        if (num3 > 1)
                        {
                            throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                        }
                        num3 = 1;
                    }
                }
                if (num3 == 2)
                {
                    helper.Append('.');
                }
                helper.Append('.');
            }
            if (helper.Length == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
            }
            if (fullCheck && (helper.OrdinalStartsWith("http:", false) || helper.OrdinalStartsWith("file:", false)))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_PathUriFormatNotSupported"));
            }
            if (flag4)
            {
                helper.TryExpandShortFileName();
            }
            int fullPathName = 1;
            if (fullCheck)
            {
                fullPathName = helper.GetFullPathName();
                flag4 = false;
                for (int m = 0; (m < helper.Length) && !flag4; m++)
                {
                    if (helper[m] == '~')
                    {
                        flag4 = true;
                    }
                }
                if (flag4 && !helper.TryExpandShortFileName())
                {
                    int lastSlash = -1;
                    for (int n = helper.Length - 1; n >= 0; n--)
                    {
                        if (helper[n] == DirectorySeparatorChar)
                        {
                            lastSlash = n;
                            break;
                        }
                    }
                    if (lastSlash >= 0)
                    {
                        if (helper.Length >= maxPathLength)
                        {
                            throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
                        }
                        int lenSavedName = (helper.Length - lastSlash) - 1;
                        helper.Fixup(lenSavedName, lastSlash);
                    }
                }
            }
            if (((fullPathName != 0) && (helper.Length > 1)) && ((helper[0] == '\\') && (helper[1] == '\\')))
            {
                int num20 = 2;
                while (num20 < fullPathName)
                {
                    if (helper[num20] == '\\')
                    {
                        num20++;
                        break;
                    }
                    num20++;
                }
                if (num20 == fullPathName)
                {
                    throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegalUNC"));
                }
                if (helper.OrdinalStartsWith(@"\\?\globalroot", true))
                {
                    throw new ArgumentException(Environment.GetResourceString("Arg_PathGlobalRoot"));
                }
            }
            if (helper.Length >= maxPathLength)
            {
                throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
            }
            if (fullPathName == 0)
            {
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode == 0)
                {
                    errorCode = 0xa1;
                }
                __Error.WinIOError(errorCode, path);
                return null;
            }
            string a = helper.ToString();
            if (string.Equals(a, path, StringComparison.Ordinal))
            {
                a = path;
            }
            return a;
        }
 private static string MakeRooted(string basePath, string path)
 {
     basePath = basePath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
     return(PathHelper.MakeRooted(basePath + Path.DirectorySeparatorChar, path));
 }
Beispiel #42
0
        private void RecurseDirectories(string[] subFolders, TreeNode treeNode, XmlNode parentDirectoryElement)
        {
            foreach (string folder in subFolders)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(folder);

                if (FileImport.NeedToIgnore(dirInfo.Name))
                {
                    continue;
                }

                XmlElement newElement = parentDirectoryElement.OwnerDocument.CreateElement("Directory", WixFiles.WixNamespaceUri);

                newElement.SetAttribute("Id", FileImport.GenerateValidIdentifier(dirInfo.Name, newElement, wixFiles));

                newElement.SetAttribute(WixEditSettings.Instance.LongName, FileImport.GenerateValidLongName(dirInfo.Name));
                if (WixEditSettings.Instance.IsUsingWix2())
                {
                    newElement.SetAttribute(WixEditSettings.Instance.ShortName, FileImport.GenerateValidShortName(PathHelper.GetShortDirectoryName(dirInfo, wixFiles, parentDirectoryElement)));
                }

                TreeNode newNode = new TreeNode(newElement.GetAttribute(WixEditSettings.Instance.LongName));
                newNode.Tag = newElement;

                if (firstShowableNode == null)
                {
                    firstShowableNode = newNode;
                }

                int imageIndex = ImageListFactory.GetImageIndex("Directory");
                if (imageIndex >= 0)
                {
                    newNode.ImageIndex         = imageIndex;
                    newNode.SelectedImageIndex = imageIndex;
                }

                XmlNodeList sameNodes = parentDirectoryElement.SelectNodes("wix:Directory", wixFiles.WxsNsmgr);
                if (sameNodes.Count > 0)
                {
                    parentDirectoryElement.InsertAfter(newElement, sameNodes[sameNodes.Count - 1]);
                }
                else
                {
                    parentDirectoryElement.AppendChild(newElement);
                }

                treeNode.Nodes.Add(newNode);

                string[] subFiles = Directory.GetFiles(dirInfo.FullName);
                if (subFiles.Length > 0)
                {
                    FileImport.AddFiles(wixFiles, subFiles, newNode, newElement);
                }

                string[] subSubFolders = Directory.GetDirectories(dirInfo.FullName);
                RecurseDirectories(subSubFolders, newNode, newElement);
            }
        }
Beispiel #43
0
 public void Cleanup()
 {
     PathHelper.DeleteTempDir(this.outputDirectory);
 }
Beispiel #44
0
 files = files.Concat(cfg.Include.Select(x => PathHelper.ToUrl(x))
                      .Where(x => x.StartsWith("../", StringComparison.Ordinal) &&
Beispiel #45
0
        //
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            bool useSiteMinJs = UseSiteMinJs?.Contains(HostingEnvironment.EnvironmentName, StringComparison.OrdinalIgnoreCase) == true;
            if (WarnIfTestIsInvalid?.Contains(HostingEnvironment.EnvironmentName, StringComparison.OrdinalIgnoreCase) == true)
            {
                var x = await output.GetChildContentAsync();
                if (!useSiteMinJs)
                    output.PreElement.AppendHtml(string.Format(_preTest, FallbackTest, $"Script `{RemotePath}` already loaded. Did you create the correct test"));
                output.PostElement.AppendHtml(string.Format(_postTest, FallbackTest, $"Script `{RemotePath}` still not loaded. Did you create the correct test"));
            }
            var LocalRelPath = "";
            if (CopySrcToFallback?.Contains(HostingEnvironment.EnvironmentName, StringComparison.OrdinalIgnoreCase) == true)
            {
                try
                {
                    var scheme = Context.HttpContext.Request.Scheme;
                    RemotePath = RemotePath.StartsWith("//")
                        ? scheme + ":" + RemotePath
                        : RemotePath.ToLower().StartsWith("/") || RemotePath.ToLower().StartsWith("~/")
                        ? scheme + "://" + Context.HttpContext.Request.Host + RemotePath.Replace("~", "")
                        : RemotePath;

                    LocalRelPath = (useSiteMinJs == false) ?
                        "/js/" + new Uri(RemotePath).Segments.Last()
                        : FallbackSrc ?? "/fallback/js/" + new Uri(RemotePath).Segments.Last();
                    var localPath = HostingEnvironment.MapPath(LocalRelPath.TrimStart('/'));
                    var pathHelper = new PathHelper(RemotePath, localPath);
                    if (!File.Exists(localPath))
                    {
                        using (var webClient = new HttpClient())
                        {
                            var file = await webClient.GetStringAsync(new Uri(RemotePath));
                            Directory.CreateDirectory(pathHelper.LocalDirectory);
                            File.WriteAllText(localPath, file);
                            if (RemotePath.Contains(".min.") && UseSiteMinJs != null)//copy full version to let gulp minify this verion to site.css
                            {
                                file = await webClient.GetStringAsync(new Uri(RemotePath.Replace(".min", "")));
                                File.WriteAllText(localPath, file);
                            }
                            if (!RemotePath.Contains(".min.") && UseMinified != null)
                            {
                                file = await webClient.GetStringAsync(new Uri(RemotePath.Replace(".js", ".min.js")));
                                File.WriteAllText(localPath, file);
                            }

                        }
                    }
                }
                catch (HttpRequestException ex)
                {
                    throw new FileNotFoundException($"The remote file:{RemotePath} cannot be found.", ex);
                }
            }
            if (context.AllAttributes.ContainsName("src"))
            {
                output.CopyHtmlAttribute("src", context);
                if (UseLocal?.Contains(HostingEnvironment.EnvironmentName, StringComparison.OrdinalIgnoreCase) == true)
                    output.Attributes["src"].Value = LocalRelPath;
                string href = output.Attributes["src"].Value.ToString();
                if (UseMinified?.Contains(HostingEnvironment.EnvironmentName, StringComparison.OrdinalIgnoreCase) == true && !href.Contains(".min."))
                    output.Attributes["src"] = href.Replace(".js", ".min.js");
                if (useSiteMinJs)
                    output.Attributes["src"].Value = "";
            }
        }
Beispiel #46
0
 .Select(x => PathHelper.ToPath(x))
 .Where(x => File.Exists(x)));
 public FundamentalDataConverter(PathHelper pathHelper)
 {
     _pathHelper = pathHelper;
 }
Beispiel #48
0
        public List <ExternalType> List()
        {
            var tsconfig = Path.Combine(projectDir, "tsconfig.json");
            IEnumerable <string> files = null;

            if (File.Exists(tsconfig))
            {
                var cfg = JSON.ParseTolerant <TSConfig>(File.ReadAllText(tsconfig));
                if (!cfg.Files.IsEmptyOrNull())
                {
                    files = cfg.Files.Where(x => File.Exists(Path.Combine(projectDir, PathHelper.ToPath(x))))
                            .Select(x => Path.GetFullPath(Path.Combine(projectDir, PathHelper.ToPath(x))));
                }
                else if (!cfg.Include.IsEmptyOrNull())
                {
                    var typeRoots = cfg.CompilerOptions?.TypeRoots?.IsEmptyOrNull() == true ?
                                    new string[] { "./node_modules/types" } : cfg.CompilerOptions.TypeRoots;

                    var types = new HashSet <string>(cfg.CompilerOptions?.Types ?? Array.Empty <string>(),
                                                     StringComparer.OrdinalIgnoreCase);

                    files = typeRoots.Select(typeRoot => Path.Combine(projectDir, typeRoot))
                            .Where(typeRoot => Directory.Exists(typeRoot))
                            .Select(typeRoot => Path.GetFullPath(typeRoot))
                            .SelectMany(typeRoot =>
                                        Directory.GetDirectories(typeRoot)
                                        .Where(typing => (cfg.CompilerOptions?.Types == null) || types.Contains(Path.GetDirectoryName(typing)))
                                        .Where(typing => Path.GetFileName(typing).Contains("serenity", StringComparison.OrdinalIgnoreCase) ||
                                               !PathHelper.ToUrl(typing).Contains("/node_modules/", StringComparison.OrdinalIgnoreCase))
                                        .Select(typing => Path.Combine(typing, "index.d.ts"))
                                        .Where(typing => File.Exists(typing)))
                            .ToList();

                    var includePatterns = cfg.Include
                                          .Select(x => PathHelper.ToUrl(x))
                                          .Where(x => !x.StartsWith("../", StringComparison.Ordinal))
                                          .Select(x => x.StartsWith("./", StringComparison.Ordinal) ? x[2..] :
Beispiel #49
0
 /// <summary>
 /// 获取某模板文件的绝对路径,文件名必须从视图 view 的根目录算起
 /// </summary>
 /// <param name="fileName"></param>
 /// <returns></returns>
 public String getTemplatePathByFile(String fileName)
 {
     return(PathHelper.Map(strUtil.Join(MvcConfig.Instance.ViewDir, fileName) + MvcConfig.Instance.ViewExt));
 }
Beispiel #50
0
 .Select(x => PathHelper.ToPath(x));
Beispiel #51
0
    private void GetChildItem_trvReports_Reports(TreeViewNode parentReportNode, Report parentReport, IList <Report> reportsList)
    {
        JavaScriptSerializer JsSerializer = new JavaScriptSerializer();
        string imageName = string.Empty;

        foreach (Report childItem in reportsList.Where(x => x.ParentId == parentReport.ID))
        {
            TreeViewNode childItemNode = new TreeViewNode();
            childItemNode.ID   = childItem.ID.ToString();
            childItemNode.Text = childItem.Name;
            TargetDetails targetDetails = new TargetDetails();
            if (childItem.IsReport)
            {
                if (!childItem.IsDesignedReport)
                {
                    targetDetails.TargetType             = TargetType.Report.ToString();
                    targetDetails.FileID                 = childItem.ReportFile.ID.ToString();
                    targetDetails.FileName               = childItem.ReportFile.Name;
                    targetDetails.Description            = childItem.ReportFile.Description;
                    targetDetails.HasParameter           = childItem.HasParameter;
                    targetDetails.IsDesigned             = childItem.IsDesignedReport;
                    targetDetails.DesignedTypeCustomCode = "";
                    targetDetails.IsContainsForm         = childItem.IsContainsForm;
                }
                else
                {
                    targetDetails.TargetType             = TargetType.Report.ToString();
                    targetDetails.FileID                 = "0";
                    targetDetails.FileName               = "";
                    targetDetails.Description            = childItem.Description;
                    targetDetails.HasParameter           = childItem.HasParameter;
                    targetDetails.IsDesigned             = childItem.IsDesignedReport;
                    targetDetails.DesignedTypeCustomCode = childItem.DesignedType.CustomCode.ToString();
                    targetDetails.IsContainsForm         = childItem.IsContainsForm;
                }
                imageName = "report.png";
            }
            else
            {
                targetDetails.TargetType = TargetType.ReportGroup.ToString();
                imageName = "group.png";
            }
            childItemNode.Value = JsSerializer.Serialize(targetDetails);
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + PathHelper.GetModulePath_Nuke() + "\\Images\\TreeView\\" + imageName))
            {
                childItemNode.ImageUrl = PathHelper.GetModuleUrl_Nuke() + "Images/TreeView/" + imageName;
            }
            parentReportNode.Nodes.Add(childItemNode);
            try
            {
                if (parentReportNode.Parent.Parent == null)
                {
                    parentReportNode.Expanded = true;
                }
            }
            catch
            { }
            if (this.ReportBusiness.GetReportChilds(childItem.ID).Count > 0)
            {
                this.GetChildItem_trvReports_Reports(childItemNode, childItem, reportsList);
            }
        }
    }
Beispiel #52
0
 public string CombinePath(string[] virtualPath)
 {
     return(Name + PathHelper.CombinePath(virtualPath));
 }
        public void Should_be_able_to_combine_path()
        {
            string path = PathHelper.CombinePath("~/scripts/", "/script.js");

            Assert.Equal("~/scripts/script.js", path);
        }
Beispiel #54
0
 protected override string GetDir()
 {
     return(PathHelper.Map("/html/recent/"));
 }
Beispiel #55
0
        private static void DeleteAnyExistingReportsForThisJobIdentifier(string jobIdentifier)
        {
            IFileSystem fileSystem = new FileSystem();

            IPathHelper pathHelper = new PathHelper(fileSystem, new TestReportConfiguration());

            var reportsPathResponse = pathHelper.GetReportsPath(jobIdentifier);

            Assert.IsTrue(reportsPathResponse.IsSuccessful, "Cannot determine output path for reports");

            var folder = reportsPathResponse.Result;

            foreach (var existingReportFile in fileSystem.Directory.EnumerateFiles(folder))
            {
                Console.WriteLine("Deleting existing report file before running test: {0}", existingReportFile);
                fileSystem.File.Delete(existingReportFile);
            }
        }
Beispiel #56
0
        public Configuration LoadConfiguration()
        {
            string userAppDataDir        = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string userAppDataPath       = PathHelper.Combine(userAppDataDir, JENKINS_TRAY_DIRECTORY);
            string userConfigurationFile = PathHelper.Combine(userAppDataPath, PROPERTIES_FILE);

            // create the directory in case it does not exist
            Directory.CreateDirectory(userAppDataPath);

            // read the properties file
            PropertiesFile propertiesFile = PropertiesFile.ReadPropertiesFile(userConfigurationFile);

            // load the servers
            var servers     = new HashedSet <Server>();
            var serverMap   = new Dictionary <int, Server>();
            int serverCount = propertiesFile.GetGroupCount("servers");

            for (int serverId = 0; serverId < serverCount; serverId++)
            {
                // read the server configuration
                Server server = new Server();
                server.Url         = propertiesFile.GetGroupRequiredStringValue("servers", serverId, "url");
                server.DisplayName = propertiesFile.GetGroupStringValue("servers", serverId, "displayName");
                server.IgnoreUntrustedCertificate = propertiesFile.GetGroupBoolValue("servers", serverId, "ignoreUntrustedCertificate", false);

                // credentials
                string username = propertiesFile.GetGroupStringValue("servers", serverId, "username");
                if (username != null)
                {
                    string passwordBase64 = propertiesFile.GetGroupRequiredStringValue("servers", serverId, "passwordBase64");
                    string password       = Encoding.UTF8.GetString(Convert.FromBase64String(passwordBase64));
                    server.Credentials = new Credentials(username, password);
                }

#if DEBUG//FIXME
                server.Credentials = new Credentials("plop", "bam");
#endif

                // keep the server
                servers.Add(server);

                // temporary keep for projects loading
                serverMap.Add(serverId, server);
            }

            // load the projects
            int projectCount = propertiesFile.GetGroupCount("projects");
            for (int projectId = 0; projectId < projectCount; projectId++)
            {
                // read the project configuration
                int     serverId = propertiesFile.GetGroupRequiredIntValue("projects", projectId, "server");
                Server  server   = serverMap[serverId];
                Project project  = new Project();
                project.Server = server;
                project.Name   = propertiesFile.GetGroupRequiredStringValue("projects", projectId, "name");
                project.Url    = propertiesFile.GetGroupRequiredStringValue("projects", projectId, "url");

                // keep the project
                server.Projects.Add(project);
            }

            var notificationSettings = new NotificationSettings();
            notificationSettings.FailedSoundPath       = propertiesFile.GetStringValue("sounds.Failed");
            notificationSettings.FixedSoundPath        = propertiesFile.GetStringValue("sounds.Fixed");
            notificationSettings.StillFailingSoundPath = propertiesFile.GetStringValue("sounds.StillFailing");
            notificationSettings.SucceededSoundPath    = propertiesFile.GetStringValue("sounds.Succeeded");
            notificationSettings.TreatUnstableAsFailed = propertiesFile.GetBoolValue("sounds.TreatUnstableAsFailed") ?? true;

            var generalSettings = new GeneralSettings();
            generalSettings.RefreshIntervalInSeconds = propertiesFile.GetIntValue("general.RefreshTimeInSeconds", DEFAULT_TIME_BETWEEN_UPDATES);
            generalSettings.UpdateMainWindowIcon     = propertiesFile.GetBoolValue("general.UpdateMainWindowIcon", true);
            generalSettings.IntegrateWithClaimPlugin = propertiesFile.GetBoolValue("general.IntegrateWithClaimPlugin", true);

            var res = new Configuration
            {
                Servers = servers,
                NotificationSettings = notificationSettings,
                GeneralSettings      = generalSettings
            };
            return(res);
        }
Beispiel #57
0
        internal unsafe static String NormalizePath(String path, bool fullCheck, int maxPathLength, bool expandShortPaths) {

            Contract.Requires(path != null, "path can't be null");
            // If we're doing a full path check, trim whitespace and look for
            // illegal path characters.
            if (fullCheck) {
                // Trim whitespace off the end of the string.
                // Win32 normalization trims only U+0020. 
                path = path.TrimEnd(TrimEndChars);

                // Look for illegal path characters.
                CheckInvalidPathChars(path);
            }

            int index = 0;
            // We prefer to allocate on the stack for workingset/perf gain. If the 
            // starting path is less than MaxPath then we can stackalloc; otherwise we'll
            // use a StringBuilder (PathHelper does this under the hood). The latter may
            // happen in 2 cases:
            // 1. Starting path is greater than MaxPath but it normalizes down to MaxPath.
            // This is relevant for paths containing escape sequences. In this case, we
            // attempt to normalize down to MaxPath, but the caller pays a perf penalty 
            // since StringBuilder is used. 
            // 2. IsolatedStorage, which supports paths longer than MaxPath (value given 
            // by maxPathLength.
            PathHelper newBuffer;
            if (path.Length + 1 <= MaxPath) {
                char* m_arrayPtr = stackalloc char[MaxPath];
                newBuffer = new PathHelper(m_arrayPtr, MaxPath);
            } else {
                newBuffer = new PathHelper(path.Length + Path.MaxPath, maxPathLength);
            }
            
            uint numSpaces = 0;
            uint numDots = 0;
            bool fixupDirectorySeparator = false;
            // Number of significant chars other than potentially suppressible
            // dots and spaces since the last directory or volume separator char
            uint numSigChars = 0;
            int lastSigChar = -1; // Index of last significant character.
            // Whether this segment of the path (not the complete path) started
            // with a volume separator char.  Reject "c:...".
            bool startedWithVolumeSeparator = false;
            bool firstSegment = true;
            int lastDirectorySeparatorPos = 0;

            bool mightBeShortFileName = false;

            // LEGACY: This code is here for backwards compatibility reasons. It 
            // ensures that \\foo.cs\bar.cs stays \\foo.cs\bar.cs instead of being
            // turned into \foo.cs\bar.cs.
            if (path.Length > 0 && (path[0] == DirectorySeparatorChar || path[0] == AltDirectorySeparatorChar)) {
                newBuffer.Append('\\');
                index++;
                lastSigChar = 0;
            }

            // Normalize the string, stripping out redundant dots, spaces, and 
            // slashes.
            while (index < path.Length) {
                char currentChar = path[index];

                // We handle both directory separators and dots specially.  For 
                // directory separators, we consume consecutive appearances.  
                // For dots, we consume all dots beyond the second in 
                // succession.  All other characters are added as is.  In 
                // addition we consume all spaces after the last other char
                // in a directory name up until the directory separator.

                if (currentChar == DirectorySeparatorChar || currentChar == AltDirectorySeparatorChar) {
                    // If we have a path like "123.../foo", remove the trailing dots.
                    // However, if we found "c:\temp\..\bar" or "c:\temp\...\bar", don't.
                    // Also remove trailing spaces from both files & directory names.
                    // This was agreed on with the OS team to fix undeletable directory
                    // names ending in spaces.

                    // If we saw a '\' as the previous last significant character and
                    // are simply going to write out dots, suppress them.
                    // If we only contain dots and slashes though, only allow
                    // a string like [dot]+ [space]*.  Ignore everything else.
                    // Legal: "\.. \", "\...\", "\. \"
                    // Illegal: "\.. .\", "\. .\", "\ .\"
                    if (numSigChars == 0) {
                        // Dot and space handling
                        if (numDots > 0) {
                            // Look for ".[space]*" or "..[space]*"
                            int start = lastSigChar + 1;
                            if (path[start] != '.')
                                throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

                            // Only allow "[dot]+[space]*", and normalize the 
                            // legal ones to "." or ".."
                            if (numDots >= 2) {
                                // Reject "C:..."
                                if (startedWithVolumeSeparator && numDots > 2)

                                    throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

                                if (path[start + 1] == '.') {
                                    // Search for a space in the middle of the
                                    // dots and throw
                                    for(int i=start + 2; i < start + numDots; i++) {
                                        if (path[i] != '.')
                                            throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                                    }

                                    numDots = 2;
                                }
                                else {
                                    if (numDots > 1)
                                        throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                                    numDots = 1;
                                }
                            }
                                    
                            if (numDots == 2) {
                                newBuffer.Append('.');
                            }

                            newBuffer.Append('.');
                            fixupDirectorySeparator = false;

                            // Continue in this case, potentially writing out '\'.
                        }

                        if (numSpaces > 0 && firstSegment) {
                            // Handle strings like " \\server\share".
                            if (index + 1 < path.Length && 
                                (path[index + 1] == DirectorySeparatorChar || path[index + 1] == AltDirectorySeparatorChar))
                            {
                                newBuffer.Append(DirectorySeparatorChar);
                            }
                        }
                    }
                    numDots = 0;
                    numSpaces = 0;  // Suppress trailing spaces

                    if (!fixupDirectorySeparator) {
                        fixupDirectorySeparator = true;
                        newBuffer.Append(DirectorySeparatorChar);
                    }
                    numSigChars = 0;
                    lastSigChar = index;
                    startedWithVolumeSeparator = false;
                    firstSegment = false;

                    // For short file names, we must try to expand each of them as
                    // soon as possible.  We need to allow people to specify a file
                    // name that doesn't exist using a path with short file names
                    // in it, such as this for a temp file we're trying to create:
                    // C:\DOCUME~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp
                    // We could try doing this afterwards piece by piece, but it's
                    // probably a lot simpler to do it here.
                    if (mightBeShortFileName) {
                        newBuffer.TryExpandShortFileName(); 
                        mightBeShortFileName = false;
                    }

                    int thisPos = newBuffer.Length - 1;
                    if (thisPos - lastDirectorySeparatorPos > MaxDirectoryLength)
                    {
                        throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
                    }
                    lastDirectorySeparatorPos = thisPos;
                } // if (Found directory separator)
                else if (currentChar == '.') {
                    // Reduce only multiple .'s only after slash to 2 dots. For
                    // instance a...b is a valid file name.
                    numDots++;
                    // Don't flush out non-terminal spaces here, because they may in
                    // the end not be significant.  Turn "c:\ . .\foo" -> "c:\foo"
                    // which is the conclusion of removing trailing dots & spaces,
                    // as well as folding multiple '\' characters.
                }
                else if (currentChar == ' ') {
                    numSpaces++;
                }
                else {  // Normal character logic
                    if (currentChar == '~' && expandShortPaths)
                        mightBeShortFileName = true;

                    fixupDirectorySeparator = false;

                    // To reject strings like "C:...\foo" and "C  :\foo"
                    if (firstSegment && currentChar == VolumeSeparatorChar) {
                        // Only accept "C:", not "c :" or ":"
                        // Get a drive letter or ' ' if index is 0.
                        char driveLetter = (index > 0) ? path[index-1] : ' ';
                        bool validPath = ((numDots == 0) && (numSigChars >= 1) && (driveLetter != ' '));
                        if (!validPath)
                            throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

                        startedWithVolumeSeparator = true;
                        // We need special logic to make " c:" work, we should not fix paths like "  foo::$DATA"
                        if (numSigChars > 1) { // Common case, simply do nothing
                            int spaceCount = 0; // How many spaces did we write out, numSpaces has already been reset.
                            while((spaceCount < newBuffer.Length) && newBuffer[spaceCount] == ' ') 
                                spaceCount++;
                            if (numSigChars - spaceCount == 1) {
                                //Safe to update stack ptr directly
                                newBuffer.Length = 0;
                                newBuffer.Append(driveLetter); // Overwrite spaces, we need a special case to not break "  foo" as a relative path.
                            }
                        }
                        numSigChars = 0;
                    }
                    else 
                    {
                        numSigChars += 1 + numDots + numSpaces;
                    }

                    // Copy any spaces & dots since the last significant character
                    // to here.  Note we only counted the number of dots & spaces,
                    // and don't know what order they're in.  Hence the copy.
                    if (numDots > 0 || numSpaces > 0) {
                        int numCharsToCopy = (lastSigChar >= 0) ? index - lastSigChar - 1 : index;
                        if (numCharsToCopy > 0) {
                            for (int i=0; i<numCharsToCopy; i++) {
                                newBuffer.Append(path[lastSigChar + 1 + i]);
                            }
                        }
                        numDots = 0;
                        numSpaces = 0;
                    }

                    newBuffer.Append(currentChar);
                    lastSigChar = index;
                }
                
                index++;
            } // end while

            if (newBuffer.Length - 1 - lastDirectorySeparatorPos > MaxDirectoryLength)
            {
                throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
            }

            // Drop any trailing dots and spaces from file & directory names, EXCEPT
            // we MUST make sure that "C:\foo\.." is correctly handled.
            // Also handle "C:\foo\." -> "C:\foo", while "C:\." -> "C:\"
            if (numSigChars == 0) {
                if (numDots > 0) {
                    // Look for ".[space]*" or "..[space]*"
                    int start = lastSigChar + 1;
                    if (path[start] != '.')
                        throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

                    // Only allow "[dot]+[space]*", and normalize the 
                    // legal ones to "." or ".."
                    if (numDots >= 2) {
                        // Reject "C:..."
                        if (startedWithVolumeSeparator && numDots > 2)
                            throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

                        if (path[start + 1] == '.') {
                            // Search for a space in the middle of the
                            // dots and throw
                            for(int i=start + 2; i < start + numDots; i++) {
                                if (path[i] != '.')
                                    throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                            }
                            
                            numDots = 2;
                        }
                        else {
                            if (numDots > 1)
                                throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                            numDots = 1;
                        }
                    }

                    if (numDots == 2) {
                        newBuffer.Append('.');
                    }

                    newBuffer.Append('.');
                }
            } // if (numSigChars == 0)

            // If we ended up eating all the characters, bail out.
            if (newBuffer.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

            // Disallow URL's here.  Some of our other Win32 API calls will reject
            // them later, so we might be better off rejecting them here.
            // Note we've probably turned them into "file:\D:\foo.tmp" by now.
            // But for compatibility, ensure that callers that aren't doing a 
            // full check aren't rejected here.
            if (fullCheck) {
                if ( newBuffer.OrdinalStartsWith("http:", false) ||
                     newBuffer.OrdinalStartsWith("file:", false))
                {
                    throw new ArgumentException(Environment.GetResourceString("Argument_PathUriFormatNotSupported")); 
                }
            }

            // If the last part of the path (file or directory name) had a tilde,
            // expand that too.
            if (mightBeShortFileName) {
                newBuffer.TryExpandShortFileName(); 
            }

            // Call the Win32 API to do the final canonicalization step.
            int result = 1;

            if (fullCheck) {
                // NOTE: Win32 GetFullPathName requires the input buffer to be big enough to fit the initial 
                // path which is a concat of CWD and the relative path, this can be of an arbitrary 
                // size and could be > MAX_PATH (which becomes an artificial limit at this point), 
                // even though the final normalized path after fixing up the relative path syntax 
                // might be well within the MAX_PATH restriction. For ex,
                // "c:\SomeReallyLongDirName(thinkGreaterThan_MAXPATH)\..\foo.txt" which actually requires a
                // buffer well with in the MAX_PATH as the normalized path is just "c:\foo.txt"
                // This buffer requirement seems wrong, it could be a 


                
                // Ideally we would get the required buffer length first by calling GetFullPathName
                // once without the buffer and use that in the later call but this doesn't always work
                // due to Win32 GetFullPathName 





                result = newBuffer.GetFullPathName();

                // If we called GetFullPathName with something like "foo" and our
                // command window was in short file name mode (ie, by running edlin or
                // DOS versions of grep, etc), we might have gotten back a short file
                // name.  So, check to see if we need to expand it.
                mightBeShortFileName = false;
                for(int i=0; i < newBuffer.Length && !mightBeShortFileName; i++) {
                    if (newBuffer[i] == '~' && expandShortPaths)
                        mightBeShortFileName = true;
                }

                if (mightBeShortFileName) {
                    bool r = newBuffer.TryExpandShortFileName();
                    // Consider how the path "Doesn'tExist" would expand.  If
                    // we add in the current directory, it too will need to be
                    // fully expanded, which doesn't happen if we use a file
                    // name that doesn't exist.
                    if (!r) {
                        int lastSlash = -1;

                        for (int i = newBuffer.Length - 1; i >= 0; i--) { 
                            if (newBuffer[i] == DirectorySeparatorChar) {
                                lastSlash = i;
                                break;
                            }
                        }

                        if (lastSlash >= 0) {
                            
                            // This bounds check is for safe memcpy but we should never get this far 
                            if (newBuffer.Length >= maxPathLength)
                                throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));

                            int lenSavedName = newBuffer.Length - lastSlash - 1;
                            Contract.Assert(lastSlash < newBuffer.Length, "path unexpectedly ended in a '\'");

                            newBuffer.Fixup(lenSavedName, lastSlash);
                        }
                    }
                }
            }

            if (result != 0) {
                /* Throw an ArgumentException for paths like \\, \\server, \\server\
                   This check can only be properly done after normalizing, so
                   \\foo\.. will be properly rejected.  Also, reject \\?\GLOBALROOT\
                   (an internal kernel path) because it provides aliases for drives. */
                if (newBuffer.Length > 1 && newBuffer[0] == '\\' && newBuffer[1] == '\\') {
                    int startIndex = 2;
                    while (startIndex < result) {
                        if (newBuffer[startIndex] == '\\') {
                            startIndex++;
                            break;
                        }
                        else {
                            startIndex++;
                        }
                    }
                    if (startIndex == result)
                        throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegalUNC"));

                    // Check for \\?\Globalroot, an internal mechanism to the kernel
                    // that provides aliases for drives and other undocumented stuff.
                    // The kernel team won't even describe the full set of what
                    // is available here - we don't want managed apps mucking 
                    // with this for security reasons.
                    if ( newBuffer.OrdinalStartsWith("\\\\?\\globalroot", true))
                        throw new ArgumentException(Environment.GetResourceString("Arg_PathGlobalRoot"));
                }
            }

            // Check our result and form the managed string as necessary.
            if (newBuffer.Length >= maxPathLength)
                throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));

            if (result == 0) {
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode == 0)
                    errorCode = Win32Native.ERROR_BAD_PATHNAME;
                __Error.WinIOError(errorCode, path);
                return null;  // Unreachable - silence a compiler error.
            }

            String returnVal = newBuffer.ToString();
            if (String.Equals(returnVal, path, StringComparison.Ordinal))
            {
                returnVal = path;
            }
            return returnVal;

        }
Beispiel #58
0
		private void EnsureInitialized(dynamic deps)
		{
			if (_pathHelper == null)
			{
				_webroot = deps.config.webroot;
				_pathHelper = new PathHelper(_env, _webroot);
			}
		}