Beispiel #1
0
        public void Home_Page_With_Default_Action(string path) {

            // Arrange
            var pathData = new PathData();
            var mapper = new Mock<IControllerMapper>();
            var container = new Mock<IContainer>();

            mapper.Setup(x => x.GetControllerName(typeof(DummyController))).Returns("Dummy");
            container.Setup(x => x.GetInstance<IDocumentSession>()).Returns(_store.OpenSession());
            mapper.Setup(x => x.ControllerHasAction("Dummy", "index")).Returns(true);

            // Act
            IPathData data;

            using (var session = _store.OpenSession()) {

                // create and store a new page
                var pageModel = new StandardPage { Parent = null };
                session.Store(pageModel);
                session.SaveChanges();

                // try to resovle the page via the path
                var resolver = new PathResolver(session, pathData, mapper.Object, container.Object);
                data = resolver.ResolvePath(new RouteData(), path);

            }

            // Assert
            Assert.NotNull(data);
            Assert.AreEqual("index", data.Action);
            Assert.AreEqual("Dummy", data.Controller);
        }
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public override void Execute()
        {
            this.ValidateObject();

            tracer.Info(
                Resources.ValidatePatternModelCommand_TraceInitial, this.CurrentElement.InstanceName, this.TargetPath);

            var resolver = new PathResolver(this.CurrentElement, this.UriService,
                this.TargetPath);

            resolver.Resolve();

            if (!string.IsNullOrEmpty(resolver.Path))
            {
                var itemContainer = this.Solution.Find(resolver.Path).FirstOrDefault();

                if (itemContainer != null)
                {
                    tracer.Info(
                        Resources.ValidatePatternModelCommand_TraceValidating, this.CurrentElement.InstanceName, itemContainer.PhysicalPath);

                    if (!PatternModelDocHelper.ValidateDocument(itemContainer.PhysicalPath))
                    {
                        tracer.Info(
                            Resources.ValidatePatternModelCommand_TraceOpeningForResolution, this.CurrentElement.InstanceName, itemContainer.Name);
                    }
                }
            }
            else
            {
                tracer.Warn(
                    Resources.ValidatePatternModelCommand_TraceDesignerNotFound, this.CurrentElement.InstanceName);
            }
        }
        /// <summary>
        /// Transforms the Templates
        /// </summary>
        public override void Execute()
        {
            this.ValidateObject();

            tracer.Info(
                Resources.SetBuildActionCommand_TraceInitial, this, CurrentElement.InstanceName, this.TargetPath, this.BuildAction);

            var resolver = new PathResolver(this.CurrentElement, this.UriService,
                this.TargetPath, this.CurrentElement.InstanceName);
            resolver.Resolve();

            if (!string.IsNullOrEmpty(resolver.Path))
            {
                var item = this.Solution.Find<IItem>(resolver.Path).FirstOrDefault();
                if (item == null)
                {
                    throw new InvalidOperationException(
                        string.Format(CultureInfo.CurrentCulture, Resources.SetBuildActionCommand_ErrorTargetPathNotAnItem, this.CurrentElement.InstanceName, this.TargetPath));
                }
                else
                {
                    tracer.Info(
                        Resources.SetBuildActionCommand_TraceBuildAction, this, CurrentElement.InstanceName, this.BuildAction, item.GetLogicalPath());

                    item.Data.ItemType = BuildAction.ToString();
                }
            }
        }
        public void WhenPathEndsWithSlash_ThenItIsRemoved()
        {
            var resolver = new PathResolver(Mock.Of<IProductElement>(), Mock.Of<IUriReferenceService>(), @"Folder\SubFolder\");

            resolver.Resolve();

            Assert.Equal(@"Folder\SubFolder", resolver.Path);
        }
Beispiel #5
0
 public MainWindow()
     : base("Katahdin Debugger")
 {
     SetDefaultSize(500, 400);
     
     try
     {
         PathResolver pathResolver = new PathResolver();
         SetIconFromFile(pathResolver.Resolve("katahdin.svg"));
     }
     catch
     {
     }
     
     Destroyed += delegate
     {
         if (runtimeThread != null)
             runtimeThread.Shutdown();
     };
     
     VBox vertical = new VBox();
     Add(vertical);
     
     MenuBuilder menuBuilder = new MenuBuilder();
     
     MenuBar menuBar = menuBuilder.StartMenuBar();
     vertical.PackStart(menuBar, false, false, 0);
     
     menuBuilder.StartMenu("Debug");
     debugRun = menuBuilder.Add("Run", OnDebugRun);
     menuBuilder.End();
     
     menuBuilder.StartMenu("View");
     viewGrammar = menuBuilder.AddCheck("Grammar", OnViewGrammarToggled);
     viewParseTrace = menuBuilder.AddCheck("Parse Trace", OnViewParseTraceToggled);
     viewParseTree = menuBuilder.AddCheck("Parse Tree", OnViewParseTreeToggled);
     menuBuilder.Separate();
     menuBuilder.Add("View runtime object", OnViewRuntimeModule);
     menuBuilder.End();
     
     menuBuilder.End();
     
     console = new ConsoleWidget();
     vertical.PackStart(console, true, true, 0);
     
     vertical.PackStart(new HSeparator(), false, false, 0);
     
     HBox statusBar = new HBox();
     vertical.PackStart(statusBar, false, false, 1);
     
     progress = new ProgressBar();
     statusBar.PackStart(progress, false, false, 1);
     
     statusLabel = new Label();
     statusLabel.SetAlignment(0, (float) 0.5);
     statusLabel.LineWrap = true;
     statusBar.PackStart(statusLabel, true, true, 0);
 }
        /// <summary>
        /// Gets the solution items from resolving the path and filename.
        /// </summary>
        /// <returns></returns>
        protected override IEnumerable<IItemContainer> GetSolutionItems()
        {
            var resolver = new PathResolver(this.CurrentElement, this.UriReferenceService, this.TargetPath, this.TargetFileName);
            resolver.Resolve();

            var container = this.Solution.Find(resolver.Path).FirstOrDefault();
            var item = container.Items.FirstOrDefault(i => i.Name == resolver.FileName);
            return (item == null) ? Enumerable.Empty<IItemContainer>() : new[] { item };
        }
        public void GetLiveSitePath_WithApplicationsPath_CombinesNameAndPathWithSiteAdded()
        {
            Mock<IKuduConfiguration> mock = new Mock<IKuduConfiguration>();
            mock.Setup(x => x.ApplicationsPath).Returns("C:\\Dummy\\Path");

            IPathResolver resolver = new PathResolver(mock.Object);

            Assert.Equal(resolver.GetLiveSitePath("Foo"), "C:\\Dummy\\Path\\Foo\\site");
        }
Beispiel #8
0
        /// <summary>
        /// Performs a standard path lookup.
        /// </summary>
        /// <param name="rootDirectory">The root directory.</param>
        /// <param name="path">The path to resolve.</param>
        /// <returns>The directory entry of the resolved path.</returns>
        /// <exception cref="System.Security.SecurityException">The caller does not have access to the path or a component. For example the caller does not have the right to traverse the path.</exception>
        /// <exception cref="System.IO.PathTooLongException">The path is too long to traverse. This can be the result of circular symbolic links in the path.</exception>
        /// <exception cref="System.IO.FileNotFoundException">The file or folder path not found.</exception>
        /// <exception cref="System.IO.DirectoryNotFoundException">A path component was not found.</exception>
        /// <remarks>
        /// This call my result in other exceptions not specified in the above list. Other exceptions can be thrown by IVfsNode implementations, which are visited during the traversal
        /// process. For example a network file system node may throw an exception, if the server is unreachable.
        /// </remarks>
        public static DirectoryEntry Resolve(DirectoryEntry rootDirectory, ref string path)
        {
            // FIXME: Remove the root argument. The filesystem root should be unique for a process as part of a security model similar to jails, e.g. give apps from
            // untrusted sources their private filesystem regions.

            // FIXME: Get the root from the thread execution block
            DirectoryEntry current = rootDirectory;
            PathResolver resolver = new PathResolver(rootDirectory, current);
            return resolver.Resolve(ref path, PathResolutionFlags.None);
        }
Beispiel #9
0
        public void SimpleGetPath()
        {
            var pr = new PathResolver(Settings);
            var d = new GetDescriptor<ElasticSearchProject>()
                .Id(1);
            var expected = "/nest_test_data/elasticsearchprojects/1";
            var path = pr.CreateGetPath(d);

            Assert.AreEqual(expected, path);
        }
Beispiel #10
0
        public void UrlParamSetWhenCount()
        {
            var p = new PathResolver(this._settings);
            var s = new SearchDescriptor<ElasticSearchProject>()
                .From(0)
                .Size(10)
                .MatchAll()
                .SearchType(Nest.SearchType.Count);

            var path = p.GetSearchPathForTyped(s);
            StringAssert.Contains("search_type=count", path);
        }
Beispiel #11
0
        public void UrlParamSetWhenDfsQueryAndFetch()
        {
            var p = new PathResolver(this._settings);
            var s = new SearchDescriptor<ElasticSearchProject>()
                .From(0)
                .Size(10)
                .MatchAll()
                .SearchType(Nest.SearchType.DfsQueryAndFetch);

            var path = p.GetSearchPathForTyped(s);
            StringAssert.Contains("search_type=dfs_query_and_fetch", path);
        }
Beispiel #12
0
 public void ResolvesToTypeIndex()
 {
     var clientSettings = new ConnectionSettings(Test.Default.Uri)
         .SetDefaultIndex("mydefaultindex")
         .MapDefaultTypeIndices(p =>
             p.Add(typeof(ElasticSearchProject), "mysuperindex")
     );
     var c = new PathResolver(clientSettings);
     var searchPath = c.GetSearchPathForTyped(new SearchDescriptor<ElasticSearchProject>());
     StringAssert.StartsWith("mysuperindex", searchPath);
     searchPath = c.GetSearchPathForTyped(new SearchDescriptor<GeoLocation>());
     StringAssert.StartsWith("mydefaultindex", searchPath);
 }
Beispiel #13
0
        public void UrlParamSetScanAndScroll()
        {
            var p = new PathResolver(this._settings);
            var s = new SearchDescriptor<ElasticSearchProject>()
                .From(0)
                .Size(10)
                .MatchAll()
                .SearchType(Nest.SearchType.Scan)
                .Scroll("5s");

            var path = p.GetSearchPathForTyped(s);
            StringAssert.Contains("search_type=scan", path);
            StringAssert.Contains("scroll=5s", path);
        }
Beispiel #14
0
        public void ComplexGetPath()
        {
            var pr = new PathResolver(Settings);
            var d = new GetDescriptor<ElasticSearchProject>()
                .Index("newindex")
                .Type("myothertype")
                .Refresh()
                .Routing("routing")
                .ExecuteOnPrimary()
                .Id(1);
            var expected = "/newindex/myothertype/1?refresh=true&preference=_primary&routing=routing";
            var path = pr.CreateGetPath(d);

            Assert.AreEqual(expected, path, path);
        }
        /// <summary>
        /// Evaluates this provider.
        /// </summary>
        public override object Evaluate()
        {
            this.ValidateObject();

            tracer.Info(
                Resources.VsProjectPropertyValueProvider_TraceInitial, this.CurrentElement.InstanceName, this.ProjectPath);

            // Ensure the path resolves to some solution item
            var resolver = new PathResolver(this.CurrentElement, this.UriService, 
                (!String.IsNullOrEmpty(this.ProjectPath)) ? this.ProjectPath : String.Empty);
            if (!resolver.TryResolve(i => i.Kind == ItemKind.Project))
            {
                tracer.Error(
                    Resources.VsProjectPropertyValueProvider_TraceNotResolved, this.ProjectPath);

                return string.Empty;
            }

            // Verify project still item exists
            var item = this.Solution.Find(resolver.Path).FirstOrDefault();
            if (item == null)
            {
                tracer.Warn(
                    Resources.VsProjectPropertyValueProvider_TraceNoItemFound, this.ProjectPath, resolver.Path);

                return string.Empty;
            }
            else
            {
                if (item.Kind == ItemKind.Project)
                {
                    var project = (IProject)item;
                    var propValue = GetPropertyValue(project);

                    tracer.Info(
                        Resources.VsProjectPropertyValueProvider_TraceEvaluation, this.CurrentElement.InstanceName, this.ProjectPath, propValue);

                    return propValue;
                }
                else
                {
                    tracer.Warn(
                        Resources.VsProjectPropertyValueProvider_TraceItemNotProject, this.ProjectPath, resolver.Path, item.Kind);

                    return string.Empty;
                }
            }
        }
        public void BuildPackage(string basePath, IList <string> includes, ManifestMetadata metadata, string outFolder, bool overwrite)
        {
            var filename = metadata.Id + "." + metadata.Version + ".zip";
            var output   = fileSystem.GetFullPath(Path.Combine(outFolder, filename));

            if (fileSystem.FileExists(output) && !overwrite)
            {
                throw new CommandException("The package file already exists and --overwrite was not specified");
            }

            log.Information("Saving {Filename} to {OutFolder}...", filename, outFolder);

            fileSystem.EnsureDirectoryExists(outFolder);

            var basePathLength = fileSystem.GetFullPath(basePath).Length;

            using (var stream = fileSystem.OpenFile(output, FileAccess.Write))
                using (var archive = new ZipArchive(stream, ZipArchiveMode.Create))
                {
                    foreach (var pattern in includes)
                    {
                        log.Debug("Adding files from {Path} matching pattern {Pattern}", basePath, pattern);
                        foreach (var file in PathResolver.PerformWildcardSearch(basePath, pattern))
                        {
                            var fullFilePath = fileSystem.GetFullPath(file);
                            if (string.Equals(fullFilePath, output, StringComparison.CurrentCultureIgnoreCase))
                            {
                                continue;
                            }

                            var relativePath = UseCrossPlatformDirectorySeparator(
                                fullFilePath.Substring(basePathLength).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
                            log.Debug("Adding file: {Path}", relativePath);

                            var entry = archive.CreateEntry(relativePath, CompressionLevel.Optimal);
                            entry.LastWriteTime = new DateTimeOffset(new FileInfo(file).LastWriteTime);

                            using (var entryStream = entry.Open())
                                using (var sourceStream = File.OpenRead(file))
                                {
                                    sourceStream.CopyTo(entryStream);
                                }
                        }
                    }
                }
        }
Beispiel #17
0
        public static void Init()
        {
            Languages = Directory.EnumerateFiles(PathResolver.GetResourceFolder("LyricInputHelper", "lang"),
                                                 "*.txt", SearchOption.TopDirectoryOnly).Select(n => Path.GetFileNameWithoutExtension(n)).ToArray();
            var lang_file = PathResolver.GetResourceFile("LyricInputHelper", "lang", "lang");

            if (File.Exists(lang_file))
            {
                string filename = File.ReadAllText(lang_file).Trim(' ', '\n', '\r');
                if (Languages.Contains(filename))
                {
                    Set(filename);
                    return;
                }
            }
            Set(_default);
        }
Beispiel #18
0
        static void Save(string filename)
        {
            var lang_file = PathResolver.GetResourceFile("LyricInputHelper", "lang", "lang");

            try
            {
                if (!File.Exists(lang_file))
                {
                    File.Create(lang_file);
                }
                File.WriteAllText(lang_file, filename);
            }
            catch (Exception ex)
            {
                Errors.Log($"Failed to save lang file. \n\n{ex.Message}\n{ex.StackTrace}");
            }
        }
Beispiel #19
0
        public void TypesShouldMakeItIntoPaths()
        {
            var clientSettings = new ConnectionSettings(Test.Default.Uri)
                                 .SetDefaultIndex("mydefaultindex")
                                 .MapDefaultTypeNames(p => p
                                                      .Add(typeof(Car), "automobile")
                                                      .Add(typeof(Person), "human")
                                                      .Add(typeof(Organization), "organisation")
                                                      .Add(typeof(Developer), "codemonkey")
                                                      );
            var c          = new PathResolver(clientSettings);
            var searchPath = c.GetSearchPathForTyped(new SearchDescriptor <Person>());

            StringAssert.Contains("/human/", searchPath);
            searchPath = c.GetSearchPathForTyped(new SearchDescriptor <Developer>());
            StringAssert.Contains("/codemonkey/", searchPath);
        }
Beispiel #20
0
        protected override Expression VisitPathExpression(PathExpression pex)
        {
            var bindingContext = CompilationContext.Args.BindingContext;
            var configuration  = CompilationContext.Configuration;
            var pathInfo       = PathInfoStore.Shared.GetOrAdd(pex.Path);

            var resolvePath = Call(() => PathResolver.ResolvePath(bindingContext, pathInfo));

            if (pex.Context == PathExpression.ResolutionContext.Parameter)
            {
                return(resolvePath);
            }
            if (pathInfo.IsVariable || pathInfo.IsThis)
            {
                return(resolvePath);
            }
            if (!pathInfo.IsValidHelperLiteral && !configuration.Compatibility.RelaxedHelperNaming)
            {
                return(resolvePath);
            }

            var pathInfoLight = new PathInfoLight(pathInfo);

            if (!configuration.Helpers.TryGetValue(pathInfoLight, out var helper))
            {
                var lateBindHelperDescriptor = new LateBindHelperDescriptor(pathInfo);
                helper = new Ref <IHelperDescriptor <HelperOptions> >(lateBindHelperDescriptor);
                configuration.Helpers.AddOrReplace(pathInfoLight, helper);
            }
            else if (configuration.Compatibility.RelaxedHelperNaming)
            {
                pathInfoLight = pathInfoLight.TagComparer();
                if (!configuration.Helpers.ContainsKey(pathInfoLight))
                {
                    var lateBindHelperDescriptor = new LateBindHelperDescriptor(pathInfo);
                    helper = new Ref <IHelperDescriptor <HelperOptions> >(lateBindHelperDescriptor);
                    configuration.Helpers.AddOrReplace(pathInfoLight, helper);
                }
            }

            var options      = New(() => new HelperOptions(bindingContext));
            var context      = New(() => new Context(bindingContext));
            var argumentsArg = New(() => new Arguments(0));

            return(Call(() => helper.Value.Invoke(options, context, argumentsArg)));
        }
Beispiel #21
0
        public void a_non_rooted_file_found_in_the_tranformer_path_the_file_name_is_combined_with_the_tranformer_path()
        {
            var fileSystem   = new Mock <IFileSystem>();
            var pathResolver = new PathResolver(fileSystem.Object);

            var path            = "this is a non rooted path";
            var transformerPath = "this is a transformer path";
            var combinedPath    = "this is a combined path";

            fileSystem.Setup(f => f.IsPathRooted(path)).Returns(false);
            fileSystem.Setup(f => f.Combine(transformerPath, path)).Returns(combinedPath);
            fileSystem.Setup(f => f.FileExists(combinedPath)).Returns(true);

            var result = pathResolver.ResolvePath(path, transformerPath);

            Assert.AreEqual(result, combinedPath);
        }
Beispiel #22
0
        void ReadInclude(XElement includeElement, ISyncConfiguration configuration, IPathResolver pathResolver)
        {
            var includePath = pathResolver.GetAbsolutePath(includeElement.RequireAttributeValue(XmlAttributeNames.Path));

            if (!File.Exists(includePath))
            {
                throw new ConfigurationException(String.Format("Included configuration file '{0}' not found", includePath));
            }

            var configurationDocument = XDocument.Load(includePath);

            configurationDocument = m_Migrator.UpgradeConfigurationFile(configurationDocument);

            var includePathResolver = new PathResolver(Path.GetDirectoryName(includePath));

            ReadSyncConfiguration(configurationDocument, configuration, includePathResolver);
        }
Beispiel #23
0
        private static IEnvironment GetEnvironment()
        {
            string root                     = PathResolver.ResolveRootPath();
            string deployPath               = Path.Combine(root, Constants.WebRoot);
            string deployCachePath          = Path.Combine(root, Constants.DeploymentCachePath);
            string deploymentRepositoryPath = Path.Combine(root, Constants.RepositoryPath);
            string tempPath                 = Path.GetTempPath();
            string deploymentTempPath       = Path.Combine(tempPath, Constants.RepositoryPath);

            return(new Environment(root,
                                   tempPath,
                                   () => deploymentRepositoryPath,
                                   () => ResolveRepositoryPath(),
                                   deployPath,
                                   deployCachePath,
                                   AppSettings.NuGetCachePath));
        }
Beispiel #24
0
        private async Task AddBuiltinTypesToPathResolverAsync(CancellationToken cancellationToken = default)
        {
            var analyzer = Services.GetService <IPythonAnalyzer>();
            await analyzer.GetAnalysisAsync(BuiltinsModule, Timeout.Infinite, cancellationToken);

            Check.InvalidOperation(!(BuiltinsModule.Analysis is EmptyAnalysis), "Builtins analysis did not complete correctly.");

            // Add built-in module names
            var builtinModuleNamesMember = BuiltinsModule.GetAnyMember("__builtin_module_names__");
            var value = (builtinModuleNamesMember as IVariable)?.Value ?? builtinModuleNamesMember;

            if (value.TryGetConstant <string>(out var s))
            {
                var builtinModuleNames = s.Split(',').Select(n => n.Trim());
                PathResolver.SetBuiltins(builtinModuleNames);
            }
        }
        public static void CreateImage(string color)
        {
            Bitmap   RoundedImage = new Bitmap(96, 61);
            Graphics g            = Graphics.FromImage(RoundedImage);

            g.SmoothingMode      = SmoothingMode.AntiAlias;
            g.CompositingQuality = CompositingQuality.HighQuality;
            Color cc = (Color) new ColorConverter().ConvertFromString(color);

            DrawRoundedRectangle(g, new Rectangle(0, 0, 96, 61), 15, new Pen(new SolidBrush(Color.Black)), cc);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            string basePath = PathResolver.MapPath("images");

            color = color.Remove(0, 1);
            RoundedImage.Save(string.Format(@"{0}\{1}.png", basePath, color), ImageFormat.Png);
        }
Beispiel #26
0
        private void WriteResponsesCsv()
        {
            string resultsFilePath = Path.Combine(ArchivePath, PathResolver.GetFileNameByDate(Result.StartedAt) + ".csv");
            int    responsesCount  = Result.CompletedRequests.Length;

            using (FileStream fs = File.OpenWrite(resultsFilePath))
            {
                byte[] header = Encoding.UTF8.GetBytes("StartedAt;ResponseTime\n");
                fs.Write(header, 0, header.Length);
                for (int i = 0; i < responsesCount; i++)
                {
                    TimeSpan completedBy = Result.CompletedRequests[i].CompletedBy;
                    byte[]   buffer      = Encoding.UTF8.GetBytes($"{Result.CompletedRequests[i].StartedAt};{completedBy}\n");
                    fs.Write(buffer, 0, buffer.Length);
                }
            }
        }
        /// <summary>
        /// Evaluates this provider.
        /// </summary>
        public override object Evaluate()
        {
            this.ValidateObject();

            tracer.Info(
                Resources.ItemPropertyValueProvider_TraceInitial, this.CurrentElement.InstanceName, this.ItemPath);

            var resolver = new PathResolver(this.CurrentElement, this.UriService, path: (!String.IsNullOrEmpty(this.ItemPath)) ? this.ItemPath : String.Empty);

            if (!resolver.TryResolve(i => i.Kind == ItemKind.Item))
            {
                tracer.Error(
                    Resources.VsProjectPropertyValueProvider_TraceNotResolved, this.ItemPath);

                return(string.Empty);
            }

            var item = this.Solution.Find(resolver.Path).FirstOrDefault();

            if (item == null)
            {
                tracer.Warn(
                    Resources.VsProjectPropertyValueProvider_TraceNoItemFound, this.ItemPath, resolver.Path);

                return(string.Empty);
            }
            else
            {
                if (item.Kind == ItemKind.Item)
                {
                    var propValue = GetPropertyValue((IItem)item);

                    tracer.Info(
                        Resources.ItemPropertyValueProvider_TraceEvaluation, this.CurrentElement.InstanceName, this.ItemPath, propValue);

                    return(propValue);
                }
                else
                {
                    tracer.Warn(
                        Resources.ItemPropertyValueProvider_TraceNotItem, this.ItemPath, resolver.Path, item.Kind);

                    return(string.Empty);
                }
            }
        }
Beispiel #28
0
        /// <summary>
        /// Creates a new node in the (virtual) filesystem.
        /// </summary>
        /// <param name="path">The path to create.</param>
        /// <param name="type">The type of the node to create.</param>
        /// <param name="settings">Settings used to initialize the node.</param>
        /// <param name="access">Requests the specified access modes on the created object.</param>
        /// <param name="share">Requests the specified sharing settings on the object.</param>
        /// <returns>The created filesystem object.</returns>
        /// <remarks>
        /// This function creates new nodes in the virtual filesystem. In contrast to *nix this call
        /// creates all node types, e.g. files, directories, devices and more. Specific types may
        /// require additional settings, which are specified in a settings object passed as the third
        /// parameter.
        /// </remarks>
        public static object Create(string path, VfsNodeType type, object settings, System.IO.FileAccess access, System.IO.FileShare share)
        {
            // Retrieve the parent directory
            DirectoryEntry parent = PathResolver.Resolve(rootNode, ref path, PathResolutionFlags.RetrieveParent);

            // Check if the caller has write access in the directory
            AccessCheck.Perform(parent, AccessMode.Write, AccessCheckFlags.None);

            // Yes, we do have write access. Create the new vfs node
            IVfsNode node = parent.Node.Create(path, type, settings);

            // FIXME: Assert(null != node);
            DirectoryEntry entry = DirectoryEntry.Allocate(parent, path, node);

            // FIXME: Fix the permissions for this call. *nix does this using its bitmasks, Win32 through its huge CreateFile API.
            return(node.Open(access, share));
        }
        internal async Task LoadBuiltinTypesAsync(CancellationToken cancellationToken = default)
        {
            var analyzer = _services.GetService <IPythonAnalyzer>();
            await analyzer.GetAnalysisAsync(BuiltinsModule, -1, cancellationToken);

            Check.InvalidOperation(!(BuiltinsModule.Analysis is EmptyAnalysis), "After await");

            // Add built-in module names
            var builtinModuleNamesMember = BuiltinsModule.GetAnyMember("__builtin_module_names__");
            var value = (builtinModuleNamesMember as IVariable)?.Value ?? builtinModuleNamesMember;

            if (value.TryGetConstant <string>(out var s))
            {
                var builtinModuleNames = s.Split(',').Select(n => n.Trim());
                PathResolver.SetBuiltins(builtinModuleNames);
            }
        }
        public IEnumerable <LocalPackageInfo> FindPackagesById(string packageId)
        {
            if (string.IsNullOrEmpty(packageId))
            {
                throw new ArgumentNullException(nameof(packageId));
            }

            // packages\{packageId}\{version}\{packageId}.nuspec
            return(_cache.GetOrAdd(packageId, id =>
            {
                var packages = new List <LocalPackageInfo>();

                var packageIdRoot = PathResolver.GetVersionListPath(id);

                if (!Directory.Exists(packageIdRoot))
                {
                    return packages;
                }

                foreach (var fullVersionDir in Directory.EnumerateDirectories(packageIdRoot))
                {
                    var versionPart = fullVersionDir.Substring(packageIdRoot.Length).TrimStart(Path.DirectorySeparatorChar);

                    // Get the version part and parse it
                    NuGetVersion version;
                    if (!NuGetVersion.TryParse(versionPart, out version))
                    {
                        continue;
                    }

                    var hashPath = PathResolver.GetHashPath(id, version);

                    // The hash file is written last. If this file does not exist then the package is
                    // incomplete and should not be used.
                    if (File.Exists(hashPath))
                    {
                        var manifestPath = PathResolver.GetManifestFilePath(id, version);
                        var zipPath = PathResolver.GetPackageFilePath(id, version);

                        packages.Add(new LocalPackageInfo(id, version, fullVersionDir, manifestPath, zipPath));
                    }
                }

                return packages;
            }));
        }
Beispiel #31
0
        /// <summary>
        /// Implementation of slot.
        /// </summary>
        /// <param name="signaler">Signaler used to raise the signal.</param>
        /// <param name="input">Arguments to slot.</param>
        public void Signal(ISignaler signaler, Node input)
        {
            var zipFile = PathResolver.CombinePaths(
                _rootResolver.RootFolder,
                input.GetEx <string>());

            var folderNode = input.Children
                             .FirstOrDefault(x => x.Name == "folder")?
                             .GetEx <string>();

            var targetFolder = folderNode == null?
                               Path.GetDirectoryName(zipFile) : PathResolver.CombinePaths(_rootResolver.RootFolder, folderNode).Replace("/", "\\");

            var fastZip = new FastZip();

            fastZip.ExtractZip(zipFile, targetFolder, null);
        }
Beispiel #32
0
        private static void Execute(string[] args)
        {
            var options = OptParser.Parse <CommandLineOptions>(args);

            assume(options != null);

            var logger = new ConsoleLogger(options);

            var container = new Container(Rules.Default.WithAutoConcreteTypeResolution());

            container.RegisterInstance <ILogger>(logger);

            var problems = options.GetProblems().ToList();

            if (problems.Any())
            {
                foreach (var problem in problems)
                {
                    System.Console.Error.WriteLine(problem);
                }
                Environment.Exit(1);
            }

            assume(options.MainScreenFilename != null);
            System.Console.WriteLine($"loading screen {Path.GetFullPath(options.MainScreenFilename)}");

            var initialScreenConfiguration = ScreenConfiguration.Load(options.MainScreenFilename);
            var pathResolver = new PathResolver(Path.GetDirectoryName(Path.GetFullPath(options.MainScreenFilename)));

            container.RegisterInstance <IPathResolver>(pathResolver);

            var deck = new DeckRunner(container, logger, pathResolver);

            container.RegisterInstance <IStreamDeckServices>(deck);

            deck.InitializeScreen(initialScreenConfiguration);

            //AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs eventArgs)
            //                                           {
            //                                               System.Console.WriteLine(eventArgs.Name);

            //                                               return null;
            //                                           };

            deck.Run().GetAwaiter().GetResult();
        }
        /// <summary>
        /// Evaluates this provider.
        /// </summary>
        public override object Evaluate()
        {
            this.ValidateObject();

            tracer.Info(
                Resources.ItemPropertyValueProvider_TraceInitial, this.CurrentElement.InstanceName, this.ItemPath);

            var resolver = new PathResolver(this.CurrentElement, this.UriService, path: (!String.IsNullOrEmpty(this.ItemPath)) ? this.ItemPath : String.Empty);
            if (!resolver.TryResolve(i => i.Kind == ItemKind.Item))
            {
                tracer.Error(
                    Resources.VsProjectPropertyValueProvider_TraceNotResolved, this.ItemPath);

                return string.Empty;
            }

            var item = this.Solution.Find(resolver.Path).FirstOrDefault();

            if (item == null)
            {
                tracer.Warn(
                    Resources.VsProjectPropertyValueProvider_TraceNoItemFound, this.ItemPath, resolver.Path);

                return string.Empty;
            }
            else
            {
                if (item.Kind == ItemKind.Item)
                {
                    var propValue = GetPropertyValue((IItem)item);

                    tracer.Info(
                        Resources.ItemPropertyValueProvider_TraceEvaluation, this.CurrentElement.InstanceName, this.ItemPath, propValue);

                    return propValue;
                }
                else
                {
                    tracer.Warn(
                        Resources.ItemPropertyValueProvider_TraceNotItem, this.ItemPath, resolver.Path, item.Kind);

                    return string.Empty;
                }
            }
        }
Beispiel #34
0
        void Awake()
        {
            IFileSystem fileSystem;

            _mConsole = new MiniConsole(scrollRect, text, 100);
            _rt       = ScriptEngine.CreateRuntime();
            var asyncManager = new DefaultAsyncManager();
            var pathResolver = new PathResolver();

            pathResolver.AddSearchPath("node_modules");

            if (fileLoader == FileLoader.Resources)
            {
                fileSystem = new ResourcesFileSystem(_mConsole);
                pathResolver.AddSearchPath("dist"); // 这里的路径相对于 Unity Resources 空间
            }
            else if (fileLoader == FileLoader.HMR)
            {
                Debug.LogWarningFormat("功能未完成");
                fileSystem = new HttpFileSystem(_mConsole, baseUrl);
            }
            else
            {
                // 演示了一般文件系统的访问, 实际项目中典型的情况需要自行实现基于 AssetBundle(或 7z/zip) 的文件访问层
                fileSystem = new DefaultFileSystem(_mConsole);
                pathResolver.AddSearchPath("Scripts/out");
                // pathResolver.AddSearchPath("../Scripts/out");
                // _rt.AddSearchPath("Assets/Examples/Scripts/dist");
            }

            _rt.withStacktrace = stacktrace;
            if (sourceMap)
            {
                _rt.EnableSourceMap();
            }
            _rt.Initialize(new ScriptRuntimeArgs {
                useReflectBind      = useReflectBind,
                fileSystem          = fileSystem,
                pathResolver        = pathResolver,
                listener            = this,
                asyncManager        = asyncManager,
                logger              = _mConsole,
                byteBufferAllocator = new ByteBufferPooledAllocator()
            });
        }
Beispiel #35
0
        protected string[] LinkLinuxTarget(List <string> outputBitcodeFiles, string outputExecutablePath)
        {
            // Define the tool type to use.
            ToolType tool = ToolType.GenericLld;

            // Resolve the Unix-like LLD tool's root path.
            string toolRoot = this.context.Options.PathResolver.ToolRoot(tool);

            // Join all output bitcode files onto a string.
            string targetFiles = string.Join(" ", outputBitcodeFiles);

            // Abstract the path resolver from the context's options.
            PathResolver resolver = this.context.Options.PathResolver;

            // TODO: Finish implementation.
            // Prepare the arguments.
            List <string> args = new List <string>
            {
                "-m",
                "elf_x86_64",
                "-dynamic-linker",
                resolver.ToolResource(tool, "ld-2.27.so"),
                "-o",
                outputExecutablePath,
                resolver.ToolResource(tool, "crt1.o"),
                resolver.ToolResource(tool, "crti.o"),
                resolver.ToolResource(tool, "crtbegin.o"),
                $"-L{resolver.ToolResourcesFolder(tool)}",
                targetFiles,
                "-lgcc",
                "--as-needed",
                "-lgcc_s",
                "--no-as-needed",
                "-lc",
                "-lgcc",
                "--as-needed",
                "-lgcc_s",
                "--no-as-needed",
                resolver.ToolResource(tool, "crtend.o"),
                resolver.ToolResource(tool, "crtn.o")
            };

            // Return the resulting arguments.
            return(args.ToArray());
        }
 /// <inheritdoc/>
 public void Render(object source, HtmlTextWriter htmlWriter, TemplateDefinition liveDefinition)
 {
     if (!string.IsNullOrEmpty(liveDefinition.TemplateVirtualPath))
     {
         var     resolver = new PathResolver(liveDefinition.Folder);
         dynamic model    = new ExpandoObject();
         model.Source       = source;
         model.ControlID    = DNNContext.Current.HostControl.ClientID;
         model.Options      = ConvertToJson(liveDefinition.ClientOptions);
         model.DNNPath      = resolver.Resolve("/", PathResolver.RelativeTo.Dnn);
         model.ManifestPath = resolver.Resolve("/", PathResolver.RelativeTo.Manifest);
         model.PortalPath   = resolver.Resolve("/", PathResolver.RelativeTo.Portal);
         model.SkinPath     = resolver.Resolve("/", PathResolver.RelativeTo.Skin);
         var modelDictionary = model as IDictionary <string, object>;
         liveDefinition.TemplateArguments.ForEach(a => modelDictionary.Add(a.Name, a.Value));
         htmlWriter.Write(this.RenderTemplate(liveDefinition.TemplateVirtualPath, model));
     }
 }
Beispiel #37
0
        public void a_non_rooted_file_is_not_found_in_the_tranformer_path_nor_an_entry_assembly_path_is_available_the_path_is_returend()
        {
            var fileSystem   = new Mock <IFileSystem>();
            var pathResolver = new PathResolver(fileSystem.Object);

            var path            = "this is a non rooted path";
            var transformerPath = "this is a transformer path";
            var combinedPath    = "this is a combined path";

            fileSystem.Setup(f => f.IsPathRooted(path)).Returns(false);
            fileSystem.Setup(f => f.Combine(transformerPath, path)).Returns(combinedPath);
            fileSystem.Setup(f => f.FileExists(combinedPath)).Returns(false);
            fileSystem.Setup(f => f.EntryAssemblyLocation).Returns((string)null);

            var result = pathResolver.ResolvePath(path, transformerPath);

            Assert.AreEqual(result, path);
        }
        public async Task ReloadAsync(CancellationToken cancellationToken = default)
        {
            ModuleCache = new ModuleCache(_interpreter, _services);

            _pathResolver = new PathResolver(_interpreter.LanguageVersion);

            var addedRoots = _pathResolver.SetRoot(_root);

            ReloadModulePaths(addedRoots);

            var interpreterPaths = await GetSearchPathsAsync(cancellationToken);

            addedRoots = _pathResolver.SetInterpreterSearchPaths(interpreterPaths);
            ReloadModulePaths(addedRoots);

            addedRoots = _pathResolver.SetUserSearchPaths(_interpreter.Configuration.SearchPaths);
            ReloadModulePaths(addedRoots);
        }
Beispiel #39
0
        public LogEntry Apply(string lastCommit, IGitTreeModifier treeBuilder, ITfsWorkspace workspace, IDictionary <string, GitObject> initialTree, Action <Exception> ignorableErrorHandler)
        {
            if (initialTree.Empty())
            {
                Summary.Remote.Repository.GetObjects(lastCommit, initialTree);
            }
            var resolver = new PathResolver(Summary.Remote, initialTree);
            var sieve    = new ChangeSieve(_changeset, resolver);

            _changeset.Get(workspace, sieve.GetChangesToFetch(), ignorableErrorHandler);
            foreach (var change in sieve.GetChangesToApply())
            {
                ignorableErrorHandler.Catch(() => {
                    Apply(change, treeBuilder, workspace, initialTree);
                });
            }
            return(MakeNewLogEntry());
        }
        public void ResolveParent(string targetPath, string targetFileName)
        {
            var resolver = new PathResolver(this.currentElement, this.uriService,
                    string.IsNullOrEmpty(targetPath) ? @"\" : targetPath,
                    string.IsNullOrEmpty(targetFileName) ? this.currentElement.InstanceName : targetFileName);
            resolver.Resolve();

            if (string.IsNullOrEmpty(targetPath))
            {
                ParentItem = GetUnfoldParent(this.currentElement, theTemplate.Type);
            }
            else
            {
                ParentItem = solution.FindOrCreate(resolver.Path);
            }

            this.FileName = resolver.FileName;
        }
Beispiel #41
0
        public void PerformWildcardSearch_WithDirectory_FindsMatchingEmptyDirectory()
        {
            string normalizedBasePath;
            IEnumerable <PathResolver.SearchPathResult> actualResults = PathResolver.PerformWildcardSearch(
                _fixture.Path, "dir*",
                includeEmptyDirectories: true,
                normalizedBasePath: out normalizedBasePath);

            Assert.Collection(actualResults, result =>
            {
                Assert.False(result.IsFile);

                var expectedRelativePath = string.Format("{0}dir5", Path.DirectorySeparatorChar);
                var actualRelativePath   = result.Path.Substring(_fixture.Path.Length);

                Assert.Equal(expectedRelativePath, actualRelativePath);
            });
        }
Beispiel #42
0
        private void Init(IHostingEnvironment env)
        {
            var dataPath = Path.Combine(env.WebRootPath, "data");
            var files    = PathResolver.PerformWildcardSearch(dataPath, "*.gitattributes");

            var q = from file in files
                    let filename                       = Path.GetFileNameWithoutExtension(file)
                                              let name = filename.ToLowerInvariant()
                                                         orderby name
                                                         select new FileTemplateInfo
            {
                Id   = name,
                Name = filename,
                Path = file
            };

            this.files = q.ToList();
        }
Beispiel #43
0
        public IEnumerable <TfsTreeEntry> GetFullTree()
        {
            var treeInfo = Summary.Remote.Repository.CreateObjectsDictionary();
            var resolver = new PathResolver(Summary.Remote, "", treeInfo);

            IItem[] tfsItems;
            if (Summary.Remote.TfsRepositoryPath != null)
            {
                tfsItems = _changeset.VersionControlServer.GetItems(Summary.Remote.TfsRepositoryPath, _changeset.ChangesetId, TfsRecursionType.Full);
            }
            else
            {
                tfsItems = Summary.Remote.TfsSubtreePaths.SelectMany(x => _changeset.VersionControlServer.GetItems(x, _changeset.ChangesetId, TfsRecursionType.Full)).ToArray();
            }
            var tfsItemsWithGitPaths = tfsItems.Select(item => new { item, gitPath = resolver.GetPathInGitRepo(item.ServerItem) });

            return(tfsItemsWithGitPaths.Where(x => x.gitPath != null).Select(x => new TfsTreeEntry(x.gitPath, x.item)));
        }
Beispiel #44
0
        internal static IEnumerable <PhysicalPackageFile> ResolveSearchPattern(string basePath, string searchPath, string targetPath, bool includeEmptyDirectories)
        {
            string normalizedBasePath;
            IEnumerable <PathResolver.SearchPathResult> searchResults = PathResolver.PerformWildcardSearch(basePath, searchPath, includeEmptyDirectories, out normalizedBasePath);

            return(searchResults.Select(result =>
                                        result.IsFile
                    ? new PhysicalPackageFile
            {
                SourcePath = result.Path,
                TargetPath = ResolvePackagePath(normalizedBasePath, searchPath, result.Path, targetPath)
            }
                    : new EmptyFrameworkFolderFile(ResolvePackagePath(normalizedBasePath, searchPath, result.Path, targetPath))
            {
                SourcePath = result.Path
            }
                                        ));
        }
        public void PathResolver_PerformWildcardSearch_WithGlobstarAndFileNamePatternRecursivelyFindsAllMatchingFiles_OnWindows(string searchPath)
        {
            var actualFullPaths = PathResolver.PerformWildcardSearch(_fixture.Path, searchPath);

            Verify(new[]
            {
                @"\file1.txt",
                @"\file2.txt",
                @"\dir1\file1.txt",
                @"\dir1\file2.txt",
                @"\dir1\dir2\file1.txt",
                @"\dir1\dir2\file2.txt",
                @"\dir1\dir2\dir3\file1.txt",
                @"\dir1\dir2\dir3\file2.txt",
                @"\dir1\dir4\file1.txt",
                @"\dir1\dir4\file2.txt"
            }, actualFullPaths);
        }
Beispiel #46
0
        public void GetAbsoluteResolvedPath_WithInvalidNestedVariablePath_ShouldReturnUnresolvedPath()
        {
            // Arrange
            string       testPath      = $@"{ PathResolver.delimiter }UserPath{ PathResolver.delimiter }";
            PathResolver pathFormatter = new PathResolver(testFileSystem.Object);

            testFileSystem.Setup(m => m.Path.GetFullPath(It.IsAny <string>())).Returns <string>(val => val);

            var testVariables = new List <Variable>(new Variable[] {
                new Variable("UserPath", $@"C:/Users/{ PathResolver.delimiter }User{ PathResolver.delimiter }/Desktop")
            });

            // Act
            string result = pathFormatter.GetAbsoluteResolvedPath(testPath, testVariables);

            // Assert
            Assert.AreEqual($@"C:/Users/{ PathResolver.delimiter }User{ PathResolver.delimiter }/Desktop", result);
        }
Beispiel #47
0
        public override void RemovePackage(IPackage package)
        {
            string fileName = PathResolver.GetPackageFileName(package);

            if (EnableDelisting)
            {
                var fullPath = FileSystem.GetFullPath(fileName);
                File.SetAttributes(fullPath, File.GetAttributes(fullPath) | FileAttributes.Hidden);
                // changing file attributes doesn't mark the file as modified. We want to mark the file as modified to
                // ensure the various caches will properly reprocess this package
                File.SetLastWriteTime(fullPath, DateTime.Now);
            }
            else
            {
                FileSystem.DeleteFile(fileName);
                DeleteData(package);
            }
        }
Beispiel #48
0
        public void Home_Page_With_Custom_Action(string virtualUrl) {

            // Arrange
            var pathData = new PathData();
            var mapper = new Mock<IControllerMapper>();
            var container = new Mock<IContainer>();

            mapper.Setup(x => x.GetControllerName(typeof(DummyController))).Returns("Dummy");
            mapper.Setup(x => x.ControllerHasAction("Dummy", "myaction")).Returns(true);
            container.Setup(x => x.GetInstance<IDocumentSession>()).Returns(_store.OpenSession());

            // Act
            IPathData data;
            using (var session = _store.OpenSession()) {

                var page = new StandardPage {Parent = null };
                session.Store(page);

                session.SaveChanges();

                var resolver = new PathResolver(session, pathData, mapper.Object, container.Object);
                data = resolver.ResolvePath(new RouteData(), virtualUrl);
            }

            // Assert
            Assert.NotNull(data);
            Assert.AreEqual("myaction", data.Action);
            Assert.AreEqual("Dummy", data.Controller);
           
        }
Beispiel #49
0
        public void Can_Lookup_Controller_Without_ControllerType_Specified(string virtualUrl) {
            // Arrange
            var pathData = new PathData();
            var mapper = new Mock<IControllerMapper>();
            var container = new Mock<IContainer>();

            //mapper.Setup(x => x.GetControllerName(typeof(DummyModelWithoutControllerType))).Returns("DummyModelWithoutControllerType");
            //mapper.Setup(x => x.ControllerHasAction("DummyModelWithoutControllerTypeController", "myaction")).Returns(true);
            container.Setup(x => x.GetInstance<IDocumentSession>()).Returns(_store.OpenSession());

            mapper.Setup(m => m.ControllerHasAction("DummyModelWithoutControllerTypeController", "myaction")).Returns(true);

            // Act
            IPathData data;
            using (var session = _store.OpenSession()) {
                // create and store a new page model

                var page = new DummyModelWithoutControllerType { Parent = null };
                session.Store(page);

                session.SaveChanges();

                var resolver = new PathResolver(session, pathData, mapper.Object, container.Object);
                data = resolver.ResolvePath(new RouteData(), virtualUrl);
            }

            // Assert
            Assert.NotNull(data);
            Assert.AreEqual("myaction", data.Action);
            Assert.AreEqual("DummyModelWithoutControllerTypeController", data.Controller);

        }
        private void EnsureTargetContainer()
        {
            var resolver = new PathResolver(this.currentElement, this.uriService, this.targetPath);
            resolver.Resolve();
            if (!string.IsNullOrEmpty(resolver.Path))
            {
                this.TargetContainer = this.solution.Find(resolver.Path).FirstOrDefault();
                if (this.TargetContainer == null)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                        Resources.WindowsFileImporter_ErrorTargetContainerNotExist, resolver.Path));
                }
            }
            else
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                    Resources.WindowsFileImporter_ErrorTargetPathResolvedFailed, this.targetPath));
            }

            tracer.Info(
                Resources.WindowsFileImporter_TraceTargetContainer, this.TargetContainer.GetLogicalPath());
        }
            public void WhenPathReferencesNoTag_ThenResolvesFirstArtifactLink()
            {
                this.resolver = new PathResolver(this.element.Object, this.uriService.Object);
                this.resolver.Path = @"..\..\~\Bar2";

                this.resolver.Resolve();

                Assert.Equal(@"Foo\Bar2", this.resolver.Path);
            }
            public void WhenPathNavigatesDownAncestorHierarchyWithWrongCardinalityDescendant_ThenThrows()
            {
                this.resolver = new PathResolver(this.element.Object, this.uriService.Object);
                this.resolver.Path = @"..\..\child\descendant\~\Bar";

                Assert.Throws<InvalidOperationException>(()=> this.resolver.Resolve());
            }
            public void WhenPathNavigatesDownHierarchyWithSingleCardinalityDescendant_ThenResolvesArtifactLink()
            {
                this.resolver = new PathResolver(this.ancestor.Object, this.uriService.Object);
                this.resolver.Path = @"child\descendant\~\Bar";

                this.child.Setup(c => c.Info.Cardinality).Returns(Cardinality.OneToOne);
                this.descendant.Setup(d => d.Info.Cardinality).Returns(Cardinality.OneToOne);

                this.resolver.Resolve();

                Assert.Equal(@"Foo\Bar", this.resolver.Path);
            }
        /// <summary>
        /// Runs the configured template data against the element.
        /// </summary>
        public override void Execute()
        {
            //tracer.TraceData(TraceEventType.Verbose, Resources.GenerateProductCodeCommand_StartedEvent, this.CurrentElement);

            // Note: we are NOT doing this.ValidateObject() thing here as we are setting the base class 
            // properties ourselves. This will be a problem if this is automatically validated by the runtime.
            if (this.PatternManager != null)
            {
                if (!this.PatternManager.IsOpen)
                    throw new InvalidOperationException(Resources.GenerateProductCodeCommand_PatternManagerNotOpen);

                this.ModelFile = this.PatternManager.StoreFile;

                tracer.Info(
                    Resources.GenerateProductCodeCommand_TraceModelFile, this.ModelFile);
            }

            this.ModelElement = this.CurrentElement as ModelElement;

            Guard.NotNull(() => this.Settings, this.Settings);

            IItemContainer existingArtifact = null;
            var originalTargetFilename = this.TargetFileName;

            // If there is an existing artifact that we can resolve, override the configured settings and 
            // reuse that one instead.
            var existingArtifactLink = SolutionArtifactLinkReference
                .GetReferenceValues(this.CurrentElement, r => GetIdFromReferenceTag(r) == this.Settings.Id)
                .FirstOrDefault();
            if (existingArtifactLink != null)
            {
                // Try to locate the existing solution item
                existingArtifact = this.UriService.TryResolveUri<IItemContainer>(existingArtifactLink);
                if (existingArtifact != null)
                {
                    // If the item exists, then we'll override the configured paths to point 
                    // to the located element.
                    this.TargetPath = existingArtifact.Parent.GetLogicalPath();
                    this.TargetFileName = existingArtifact.Name;

                    tracer.Verbose(
                        Resources.GenerateProductCodeCommand_Trace_ExistingArtifactUsed, existingArtifact.GetLogicalPath());
                }
                else
                {
                    // Otherwise, we'll use the configured path and filename.
                    tracer.Info(Resources.GenerateProductCodeCommand_Trace_ExistingArtifactUriNotFound, existingArtifactLink);
                }
            }

            //Re-evaluate all properties of current element
            RefreshProvidedValues();

            // Generate the file according to current settings and porperty values
            base.Execute();

            //Restore targetfilename
            if (existingArtifactLink != null)
            {
                if (existingArtifact != null)
                {
                    this.TargetFileName = originalTargetFilename;
                }
            }

            // If an item was generated
            if (this.GeneratedItem != null)
            {
                tracer.Verbose(
                    Resources.GenerateProductCodeCommand_Trace_GeneratedArtifact, this.GeneratedItem.GetLogicalPath());

                // Add new artifact link
                if (existingArtifactLink == null)
                {
                    // Add the new link and set the tag to our settings, so that we know 
                    // it's the link generated by this command instance.
                    var newLink = this.UriService.CreateUri(this.GeneratedItem);

                    SolutionArtifactLinkReference
                        .AddReference(this.CurrentElement, newLink)
                        .Tag = BindingSerializer.Serialize(new ReferenceTag
                        {
                            Tag = this.Tag ?? string.Empty,
                            SyncNames = this.SyncName,
                            TargetFileName = this.TargetFileName,
                            Id = this.Settings.Id
                        });

                    tracer.Verbose(
                        Resources.GenerateProductCodeCommand_Trace_NewArtifactLinkAdded, newLink);
                }
                else
                {
                    // Update existing artifact link

                    // If existing artifact was not found (perhaps its now deleted), a new 
                    // link will be generated for the newly added item, so we must update the existing reference.
                    if (existingArtifact == null)
                    {
                        var newLink = this.UriService.CreateUri(this.GeneratedItem);

                        var reference = this.CurrentElement.References.First(r => GetIdFromReferenceTag(r) == Settings.Id);
                        SolutionArtifactLinkReference.SetReference(reference, newLink);

                        tracer.Verbose(
                            Resources.GenerateProductCodeCommand_Trace_UpdatedExistingArtifactLink, newLink);
                    }
                    else
                    {
                        // Existing artifact found
                        if (this.SyncName)
                        {
                            // Must rename the file to the new filename, (paths remains the same)

                            // Recalculate the filename
                            var resolver = new PathResolver(this.ModelElement, this.UriService, this.TargetPath,
                                (!string.IsNullOrEmpty(this.TargetFileName)) ? this.TargetFileName : ((IProductElement)this.ModelElement).InstanceName);
                            resolver.Resolve();

                            var proposedItemName = resolver.FileName;
                            if (this.SanitizeName)
                            {
                                proposedItemName = SanitizeItemName(proposedItemName);
                            }

                            // Rename file if different name now (taking into account whether extension is specified in TargetFileName or not)
                            if (!proposedItemName.Equals(
                                (string.IsNullOrEmpty(Path.GetExtension(proposedItemName)))
                                    ? Path.GetFileNameWithoutExtension(this.GeneratedItem.Name)
                                    : this.GeneratedItem.Name,
                                StringComparison.OrdinalIgnoreCase))
                            {
                                tracer.Info(
                                    Resources.GenerateProductCodeCommand_TraceRenameSolutionItem, this.GeneratedItem.Name, proposedItemName);

                                var uiService = (IVsUIShell)this.ServiceProvider.GetService(typeof(IVsUIShell));
                                var newItemName = this.GeneratedItem.Rename(proposedItemName, true, uiService);

                                tracer.Info(
                                    Resources.GenerateProductCodeCommand_TraceSolutionItemRenamed, this.GeneratedItem.Name, newItemName);
                            }
                        }
                    }
                }
            }
        }
        public override void Execute()
        {
            try
            {
                this.ValidateObject();

                tracer.Info(
                    Resources.SynchArtifactNameCommand_TraceInitial, this.CurrentElement.InstanceName, this.ReferenceTag);

                if (!string.IsNullOrEmpty(this.ReferenceTag) && this.ReferenceTag != FilteredReferenceTagValue)
                {
                    UpdateReferenceTagTo1113();
                }

                foreach (var reference in this.CurrentElement.References)
                {
                    if (reference.Kind == typeof(SolutionArtifactLinkReference).ToString())
                    {
                        var referenceTag = GetReference(reference.Tag);
                        if (referenceTag == null)
                            continue;

                        if (referenceTag.SyncNames || this.ReferenceTag == null)
                        {
                            var referenceUri = ReferenceKindProvider<SolutionArtifactLinkReference, Uri>.FromReference(reference);

                            var solutionItem = this.UriReferenceService.TryResolveUri<IItemContainer>(referenceUri);
                            if (solutionItem == null)
                            {
                                tracer.Warn(
                                    Resources.SynchArtifactNameCommand_TraceFailedToResolveReference, referenceUri, this.CurrentElement.InstanceName);
                                continue;
                            }

                            var solutionItemName = Path.GetFileNameWithoutExtension(solutionItem.Name);

                            if (!solutionItemName.Equals(this.CurrentElement.InstanceName, StringComparison.OrdinalIgnoreCase))
                            {
                                var proposedItemName = string.Empty;
                                if (string.IsNullOrEmpty(referenceTag.TargetFileName))
                                {
                                    // TODO: Determine if the 'InstanceName' property was the one changed, if not abort sync

                                    proposedItemName = this.CurrentElement.InstanceName;
                                }
                                else
                                {
                                    // TODO: Determine whether any of the properties referenced in TargetFileName syntax 
                                    // (i.e. {InstanceName} or {PropertyName}) was the property actually changed, and if not, dont sync!

                                    var resolver = new PathResolver(this.CurrentElement, this.UriReferenceService, @"\",
                                        string.IsNullOrEmpty(referenceTag.TargetFileName) ? this.CurrentElement.InstanceName : referenceTag.TargetFileName);
                                    resolver.Resolve();

                                    proposedItemName = Path.GetFileNameWithoutExtension(resolver.FileName);
                                }

                                tracer.Info(
                                    Resources.SynchArtifactNameCommand_TraceRenameSolutionItem, solutionItem.Name, proposedItemName);

                                var uiService = (IVsUIShell)this.ServiceProvider.GetService(typeof(IVsUIShell));
                                var newItemName = solutionItem.Rename(proposedItemName, true, uiService);

                                tracer.Info(
                                    Resources.SynchArtifactNameCommand_TraceSolutionItemRenamed, solutionItem.Name, newItemName);
                            }
                            else
                            {
                                tracer.Info(
                                    Resources.SynchArtifactNameCommand_TraceItemIgnoredSameName, solutionItem.Name);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                tracer.Error(
                    Resources.SynchArtifactNameCommand_TraceFailedSync, this.CurrentElement.InstanceName);
                throw;
            }
        }
Beispiel #56
0
 public PathResolverTests()
 {
     _config = new TestConfiguration();
     _pathResolver = new PathResolver(_config);
 }
 public PathResolverTests()
 {
     _pathResolver = new PathResolver();
 }
        /// <summary>
        /// Runs the configured template data against the element.
        /// </summary>
        public override void Execute()
        {
            this.ValidateObject();

            tracer.Info(
                Resources.GenerateModelingCodeCommand_TraceInitial, this.ModelFile, this.ModelElement.Id, this.TemplateUri.OriginalString, this.TargetPath, this.TargetFileName, this.SanitizeName);

            var template = this.Template.Value;

            var resolver = new PathResolver(this.ModelElement, this.UriService, this.TargetPath,
                        string.IsNullOrEmpty(this.TargetFileName) ? Path.ChangeExtension(((IProductElement)this.ModelElement).InstanceName, ".t4") : this.TargetFileName);
            if (!resolver.TryResolve())
            {
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture, Resources.GenerateModelingCodeCommand_ErrorTargetPathNameNotResolved, ((IProductElement)this.ModelElement).InstanceName, this.TargetPath));
            }

            var targetContainer = this.Solution.FindOrCreate(resolver.Path);
            var elementReference = SerializeReference();

            tracer.Info(
                Resources.GenerateModelingCodeCommand_TraceCreatedReference, elementReference);

            var elementType = this.ModelElement.GetType();

            CallContext.LogicalSetData(ModelElementDirectiveProcessor.KeyCallContextElementAssemblyPath, elementType.Assembly.ManifestModule.FullyQualifiedName);
            CallContext.LogicalSetData(ModelElementDirectiveProcessor.KeyCallContextElementNamespace, elementType.Namespace);

            // TODO: use template.Parameters
            CallContext.LogicalSetData(ModelElementTextTransformation.KeyModelBusReference, elementReference);
            CallContext.LogicalSetData(ModelElementTextTransformation.KeyTargetName, resolver.FileName);

            // Compatibility with PowerTools templates
            CallContext.LogicalSetData(ElementReferenceCallContextKey, elementReference);
            CallContext.LogicalSetData(ElementTargetNameContextKey, resolver.FileName);
            CallContext.LogicalSetData(ElementAssemblyPathCallContextKey, elementType.Assembly.ManifestModule.FullyQualifiedName);
            CallContext.LogicalSetData(ElementNamespaceContextKey, elementType.Namespace);

            var solutionItemName = resolver.FileName;

            if (SanitizeName)
            {
                solutionItemName = SanitizeItemName(solutionItemName);

                tracer.Verbose(
                    Resources.GenerateModelingCodeCommand_TraceSanitizedName, solutionItemName);
            }

            tracer.Info(
                Resources.GenerateModelingCodeCommand_TraceGeneratingItem, solutionItemName, targetContainer.GetLogicalPath());

            // If the template supports assigning parameters.
            if (template.Parameters != null)
                template.Parameters.Element = this.ModelElement;

            var output = template.Unfold(solutionItemName, targetContainer);
            if (output != null && output.Kind == ItemKind.Item)
            {
                var item = (IItem)output;

                // Set the model bus reference
                if (item.GetContainingProject() != null)
                    item.Data.SourceModelReference = elementReference;

                if (this.TargetBuildAction != DefaultTargetBuildAction)
                    item.Data.ItemType = this.TargetBuildAction;

                if (this.TargetCopyToOutput != DefaultTargetCopyToOutput)
                    item.Data.CopyToOutputDirectory = (int)this.TargetCopyToOutput;

                this.GeneratedItem = item;
            }
        }
            public void WhenPathReferencesTag_ThenResolvesToSpecificArtifactLink()
            {
                this.resolver = new PathResolver(this.element.Object, this.uriService.Object);
                this.resolver.Path = @"..\..\~[bar5]\Bar2";

                this.resolver.Resolve();

                Assert.Equal(@"Bar\Bar2", this.resolver.Path);
            }
Beispiel #60
0
 /// <summary>
 /// Performs a path lookup obeying to the passed flags.
 /// </summary>
 /// <param name="rootDirectory">The root directory.</param>
 /// <param name="path">The path to resolve.</param>
 /// <param name="flags">Controls aspects of the path lookup process.</param>
 /// <returns>The directory entry of the resolved path.</returns>
 /// <exception cref="System.Security.SecurityException">The caller does not have access to the path or a component. For example the caller does not have the right to traverse the path.</exception>
 /// <exception cref="System.IO.PathTooLongException">The path is too long to traverse. This can be the result of circular symbolic links in the path.</exception>
 /// <exception cref="System.IO.FileNotFoundException">The file or folder path was not found. This exception can be prevented by specifying PathResolutionFlags.DoNotThrowNotFoundException.</exception>
 /// <exception cref="System.IO.DirectoryNotFoundException">A path component was not found. This exception can be prevented by specifying PathResolutionFlags.DoNotThrowNotFoundException.</exception>
 /// <remarks>
 /// This call my result in other exceptions not specified in the above list. Other exceptions can be thrown by IVfsNode implementations, which are visited during the traversal
 /// process. For example a network file system node may throw an exception, if the server is unreachable.
 /// </remarks>
 public static DirectoryEntry Resolve(DirectoryEntry rootDirectory, ref string path, PathResolutionFlags flags)
 {
     // FIXME: Get the root from the thread execution block
     DirectoryEntry current = rootDirectory;
     PathResolver resolver = new PathResolver(rootDirectory, current);
     return resolver.Resolve(ref path, flags);
 }