示例#1
0
        internal static bool ExecCommandOnProjectSourceNode(HierarchyNode node, Guid cmdGroup, uint cmd, uint cmdexecopt, IntPtr pvaIn, IntPtr pvaOut, out int returnCode)
        {
            if (cmdGroup == VsMenus.guidStandardCommandSet2K)
            {
                switch ((VsCommands2K)cmd)
                {
                    case VsCommands2K.INCLUDEINPROJECT:
                        returnCode = ((IProjectSourceNode)node).IncludeInProject();
                        return true;

                    case VsCommands2K.EXCLUDEFROMPROJECT:
                        returnCode = ((IProjectSourceNode)node).ExcludeFromProject();
                        return true;

                    case OpenFolderInExplorerCmdId:
                        System.Diagnostics.Process.Start(node.Url);
                        returnCode = VSConstants.S_OK;
                        return true;
                }
            }

            // just an arbitrary value, it doesn't matter if method hasn't handled the request
            returnCode = VSConstants.S_FALSE;

            // not handled
            return false;
        }
示例#2
0
        public static HierarchyNode<ContentItem> CreateDirectoryNode(IFileSystem fs, ContentItem directory, HierarchyNode<ContentItem> parent, List<ContentItem> selectionTrail)
        {
            var node = new HierarchyNode<ContentItem>(directory);
            ExpandRecursive(fs, node, selectionTrail);

            return node;
        }
        public void OnMenuChangeAddServiceReference(object sender, EventArgs e)
        {
            try
            {
                Store store = this.CurrentDocView.CurrentDiagram.Store;
                Proxy proxy = DomainModelHelper.GetSelectedElement(this.ServiceProvider) as Proxy;

                if (proxy != null &&
                    !string.IsNullOrWhiteSpace(proxy.ClientApplication.ImplementationProject) &&
                    proxy.ClientApplication.ImplementationTechnology != null)
                {
                    IVsSolution solution = this.ServiceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
                    using (HierarchyNode projectNode = new HierarchyNode(solution, proxy.ClientApplication.ImplementationProject))
                    {
                        if (projectNode != null)
                        {
                            IVsAddWebReferenceResult result = VsShellDialogs.AddWebReferenceDialog(this.ServiceProvider, null, projectNode);
                            if (result != null)
                            {
                                result.Save();  // IVsWCFReferenceGroup refGropup = (IVsWCFReferenceGroup)result.Save()                              
                            }
                        }
                    }
                }
            }
            catch (Exception error)
            {
                Logger.Write(error);
            }
        }
        private void Fire(HierarchyNode node, Action<IVsExtensibility3, ProjectItem> fire) {
            // When we are in suspended mode. Do not fire anything
            if (this._suspended) {
                return;
            }

            // Project has to be opened
            if (!this._project.IsProjectOpened) {
                return;
            }

            // We don't want to fire events for references here. OAReferences should do the job
            if (node is ReferenceNode) {
                return;
            }

            IVsExtensibility3 vsExtensibility = this._project.GetService(typeof(IVsExtensibility)) as IVsExtensibility3;
            if (vsExtensibility != null) {
                object obj = node.GetAutomationObject();
                ProjectItem item = obj as ProjectItem;
                if (item != null) {
                    fire(vsExtensibility, item);
                }
            }
        }
示例#5
0
 public static void Replace(RustProjectNode root, HierarchyNode old, Func<HierarchyNode> newN)
 {
     if (root == null)
         throw new ArgumentNullException("root");
     if (old == null)
         throw new ArgumentNullException("old");
     if (newN == null)
         throw new ArgumentNullException("newN");
     __VSHIERARCHYITEMSTATE visualState = old.GetItemState(__VSHIERARCHYITEMSTATE.HIS_Selected | __VSHIERARCHYITEMSTATE.HIS_Expanded);
     HierarchyNode parent = old.Parent;
     HierarchyNode newNode;
     if(parent is UntrackedFolderNode)
     {
         using(((UntrackedFolderNode)parent).SuspendChildrenTracking())
         { 
             newNode = ReplaceCore(root, old, newN, parent);
             ((UntrackedFolderNode)parent).OnChildReplaced(old, newNode);
         }
     }
     else
     {
         newNode = ReplaceCore(root, old, newN, parent);
     }
     if ((visualState & __VSHIERARCHYITEMSTATE.HIS_Expanded) != 0)
         newNode.ExpandItem(EXPANDFLAGS.EXPF_ExpandFolder);
     if ((visualState & __VSHIERARCHYITEMSTATE.HIS_Selected) != 0)
         newNode.ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
 }
 public static void SelectItemInSolutionExplorer(this IVsUIShell uiShell, HierarchyNode node)
 {
     if (node != null)
     {
         uiShell.GetSolutionExplorer().ExpandItem((node.Hierarchy as IVsUIHierarchy), node.ItemId, EXPANDFLAGS.EXPF_SelectItem);
     }
 }
示例#7
0
        public override HierarchyNode<ContentItem> Build()
        {
            if (_initialItem == _lastAncestor && !_appendAdditionalLevel)
                return new HierarchyNode<ContentItem>(_initialItem);

            HierarchyNode<ContentItem> previousNode = null;
            foreach (ContentItem currentItem in Find.EnumerateParents(_initialItem, _lastAncestor, _appendAdditionalLevel))
            {
                HierarchyNode<ContentItem> currentNode = new HierarchyNode<ContentItem>(currentItem);
                if (previousNode != null)
                    previousNode.Parent = currentNode;

                foreach (ContentItem childItem in GetChildren(currentItem))
                {
                    if (previousNode != null && (previousNode.Current == childItem || previousNode.Current.TranslationOf == childItem))
                    {
                        currentNode.Children.Add(previousNode);
                    }
                    else
                    {
                        HierarchyNode<ContentItem> childNode = new HierarchyNode<ContentItem>(childItem);
                        currentNode.Children.Add(childNode);
                        childNode.Parent = currentNode;
                    }
                }
                previousNode = currentNode;
            }
            return previousNode;
        }
示例#8
0
		internal static void Write(HierarchyNode<ContentItem> hierarchy, ContentItem selectedItem, IContentAdapterProvider adapters, ItemFilter filter, string selectableTypes, string selectableExtensions, bool excludeRoot, string target, TextWriter writer)
		{
			N2.Web.Tree.Using(hierarchy)
				.OpenTo(selectedItem)
				.Filters(filter)
				.IdProvider(n => "u" + n.Current.ID, n => "l" + n.Current.ID)
				.LinkWriter((n, w) =>
				{
					BuildLink(adapters.ResolveAdapter<NodeAdapter>(n.Current), n.Current, n.Current.Path == selectedItem.Path, target, IsSelectable(n.Current, selectableTypes, selectableExtensions)).WriteTo(w);
					if (n.Children.Count == 0 && adapters.ResolveAdapter<NodeAdapter>(n.Current).HasChildren(n.Current, filter))
					{
						var ul = new TagBuilder("ul");
						ul.AddCssClass("ajax");
						w.Write(ul.ToString(TagRenderMode.StartTag));

						var li = new TagBuilder("li");
						li.InnerHtml = "{url:" + Url.ParseTokenized("{ManagementUrl}/Content/Navigation/LoadTree.ashx")
							.AppendQuery("target", target)
							.AppendQuery(SelectionUtility.SelectedQueryKey, HttpUtility.UrlEncode(n.Current.Path))
							.AppendQuery("selectableTypes", selectableTypes)
							.AppendQuery("selectableExtensions", selectableExtensions)
							+ "}";
						w.Write(li.ToString());

						w.Write(ul.ToString(TagRenderMode.EndTag));
					}
				})
				.ExcludeRoot(excludeRoot)
				.WriteTo(writer);
		}
示例#9
0
 /// <summary>
 /// Private helper to facilitate the previous CreateItem methods.
 /// </summary>
 private static IItemContainer CreateItem(IServiceProvider serviceProvider, HierarchyNode parent, uint selectedItemid)
 {
     using (HierarchyNode current = new HierarchyNode(parent, selectedItemid))
     {
         return ItemFactory.CreateItem(serviceProvider, current);
     }
 }
 private static void EnsureDetachedFromFormerParent(HierarchyNode hierarchyNode, ChangeSetBuilder pendingChanges)
 {
     if (hierarchyNode.Parent != null)
     {
         pendingChanges.Add(new DetachChildCommand(hierarchyNode.Parent.Id, hierarchyNode.Id));
     }
 }
示例#11
0
		/// <summary>
		/// Builds this instance.
		/// </summary>
		/// <returns></returns>
		public override HierarchyNode<ContentItem> Build()
		{
			if (initialItem == lastAncestor && !appendAdditionalLevel)
			{
				return new HierarchyNode<ContentItem>(initialItem);
			}

			HierarchyNode<ContentItem> previousNode = null;
			foreach (ContentItem currentItem in Find.EnumerateParents(initialItem, lastAncestor, appendAdditionalLevel, UseMasterVersion))
			{
				HierarchyNode<ContentItem> currentNode = new HierarchyNode<ContentItem>(currentItem);
				if (previousNode != null)
				{
					previousNode.Parent = currentNode;
				}

				foreach (ContentItem childItem in GetChildren(currentItem))
				{
					if (previousNode != null && childItem.Equals(previousNode.Current))
					{
						currentNode.Children.Add(previousNode);
					}
					else
					{
						HierarchyNode<ContentItem> childNode = new HierarchyNode<ContentItem>(childItem);
						currentNode.Children.Add(childNode);
						childNode.Parent = currentNode;
					}
				}
				previousNode = currentNode;
			}
			return previousNode;
		}
示例#12
0
        protected override void OnInit(EventArgs e)
        {
            var selected = Selection.SelectedItem;
            if (IsPostBack && !string.IsNullOrEmpty(inputFile.PostedFile.FileName))
            {
                string uploadFolder = Request["inputLocation"];
                if(!IsAvailable(uploadFolder))
                    throw new N2Exception("Cannot upload to " + Server.HtmlEncode(uploadFolder));

                string fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
                string filePath = VirtualPathUtility.Combine(uploadFolder, fileName);
                FS.WriteFile(filePath, inputFile.PostedFile.InputStream);

                ClientScript.RegisterStartupScript(typeof(Tree), "select", "updateOpenerWithUrlAndClose('" + ResolveUrl(filePath) + "');", true);
            }
            else if (Request["location"] == "files" || Request["location"] == "filesselection")
            {
                IHost host = Engine.Resolve<IHost>();
                HierarchyNode<ContentItem> root = new HierarchyNode<ContentItem>(Engine.Persister.Get(host.DefaultSite.RootItemID));

                var selectionTrail = new List<ContentItem>();
                if (selected is AbstractNode)
                {
                    selectionTrail = new List<ContentItem>(Find.EnumerateParents(selected, null, true));
                }
                else
                {
                    TrySelectingPrevious(ref selected, ref selectionTrail);
                }

                foreach (string uploadFolder in Engine.EditManager.UploadFolders)
                {
                    var dd = FS.GetDirectory(uploadFolder);

                    var node = CreateDirectoryNode(FS, new Directory(FS, dd, root.Current), root, selectionTrail);
                    root.Children.Add(node);
                }

                AddSiteFilesNodes(root, host.DefaultSite, selectionTrail);
                foreach (var site in host.Sites)
                {
                    AddSiteFilesNodes(root, site, selectionTrail);
                }

                siteTreeView.Nodes = root;
                siteTreeView.SelectedItem = selected;
            }
            else
            {
                var filter = Engine.EditManager.GetEditorFilter(Page.User);
                siteTreeView.Filter = filter;
                siteTreeView.RootNode = RootNode;
                siteTreeView.SelectedItem = selected;
            }

            siteTreeView.DataBind();

            base.OnInit(e);
        }
示例#13
0
 /// <summary>
 /// Create an IItemContainer wrapper object against pHier
 /// </summary>
 internal static IItemContainer CreateItem(IServiceProvider serviceProvider, IVsSolution solution, IVsHierarchy pHier)
 {
     Debug.Assert(serviceProvider != null && solution != null && pHier != null);
     using (HierarchyNode current = new HierarchyNode(solution, pHier))
     {
         return CreateItem(serviceProvider, current);
     }
 }
示例#14
0
 /// <summary>
 /// Create an IItemContainer wrapper object against IVsSolution
 /// </summary>
 internal static IItemContainer CreateItem(IServiceProvider serviceProvider, IVsSolution solution, uint selectedItemid)
 {
     Debug.Assert(serviceProvider != null && solution != null);
     using (HierarchyNode parent = new HierarchyNode(solution))
     {
         return CreateItem(serviceProvider, parent, selectedItemid);
     }
 }
		public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			IVsSolution vsSolution = (IVsSolution)ServiceHelper.GetService(provider, typeof(IVsSolution), this);
			using (HierarchyNode root = new HierarchyNode(vsSolution))
			{
				return EditValue(provider, root, value as HierarchyNode);
			}
		}
示例#16
0
 private void Print(HierarchyNode<IContainable> current)
 {
     System.Diagnostics.Debug.WriteLine(current.Current);
     System.Diagnostics.Debug.Indent();
     foreach (var child in current.Children)
         Print(child);
     System.Diagnostics.Debug.Unindent();
 }
 /// <summary>
 /// Adds a directory to the project hierarchy with the specified parent.
 /// </summary>
 protected void AddDirectory(HierarchyNode parent, bool isSearchPath, string subfolder) {
     var existing = parent.FindChild(Path.GetFileName(subfolder));
     if (existing == null) {
         FolderNode folderNode = CreateFolderNode(subfolder);
         parent.AddChild(folderNode);
         CreateHierarchy(folderNode, subfolder, isSearchPath);
     }
 }
示例#18
0
 private static string GetNodeNameForPackage(HierarchyNode node) {
     var project = node as ProjectNode;
     if (project != null) {
         return CommonUtils.GetFileOrDirectoryName(project.ProjectHome);
     } else {
         return node.Caption;
     }
 }
示例#19
0
 public HierarchyNode(ArtistViewModel artistViewModel, HierarchyNode parent, int level)
 {
     ArtistViewModel = artistViewModel;
     GraphNodeViewModel = null;
     Parent = parent;
     Children = new List<HierarchyNode>();
     Level = level;
 }
示例#20
0
 public override void RemoveChild(HierarchyNode node)
 {
     base.RemoveChild(node);
     if (!suspendTracking && (node is UntrackedFileNode || node is UntrackedFolderNode))
     {
         DecrementTrackedCount();
     }
 }
示例#21
0
文件: TagWrapper.cs 项目: Biswo/n2cms
        public static TagWrapper Begin(string tagName, HierarchyNode<ContentItem> node, Action<HierarchyNode<ContentItem>, TagBuilder> tagModifier, TextWriter writer)
        {
            var tag = new TagBuilder(tagName);
            if (tagModifier != null)
                tagModifier(node, tag);

            return new TagWrapper(tag, writer);
        }
示例#22
0
 protected virtual HierarchyNode<ContentItem> BuildTree(ContentItem currentItem, int remainingDepth)
 {
     HierarchyNode<ContentItem> node = new HierarchyNode<ContentItem>(currentItem);
     if (remainingDepth > 1)
         foreach (ContentItem childItem in GetChildren(currentItem))
             node.Children.Add(BuildTree(childItem, remainingDepth - 1));
     return node;
 }
		public void NamePropertySetCorrectly()
		{
			string name = "MyName";
			MockVSHierarchy hierarchy = new MockVSHierarchy(name, Guid.NewGuid());
			MockVsSolution solution = new MockVsSolution(hierarchy);
			HierarchyNode node = new HierarchyNode(solution);
			Assert.AreEqual<string>(name, node.Name);
		}
示例#24
0
 void buildChild(HierarchyNode<Function> item, List<Function> list)
 {
     foreach (var _item in item.ChildNodes)
     {
         _item.Entity.Level = _item.Depth;
         list.Add(_item.Entity);
         buildChild(_item, list);
     }
 }
 public NodeProperties(HierarchyNode node)
     : base(GetProjectManager(node))
 {
     if(node == null)
     {
         throw new ArgumentNullException("node");
     }
     this.node = node;
 }
示例#26
0
 public static void ExpandRecursive(IFileSystem fs, HierarchyNode<ContentItem> parent, List<ContentItem> selectionTrail)
 {
     int index = selectionTrail.FindIndex(ci => string.Equals(ci.Url, parent.Current.Url, StringComparison.InvariantCultureIgnoreCase));
     if (index < 0) return;
     foreach (var child in parent.Current.GetChildPagesUnfiltered())
     {
         parent.Children.Add(CreateDirectoryNode(fs, child, parent, selectionTrail));
     }
 }
        public override void AddChild(HierarchyNode node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            // make sure the node is in the map.
            Object nodeWithSameID = this.ProjectMgr.ItemIdMap[node.ID];

            if (!Object.ReferenceEquals(node, nodeWithSameID as HierarchyNode))
            {
                if (nodeWithSameID == null && node.ID <= this.ProjectMgr.ItemIdMap.Count)
                    // reuse our hierarchy id if possible.
                    this.ProjectMgr.ItemIdMap.SetAt(node.ID, this);
                else
                    throw new InvalidOperationException();
            }

            HierarchyNode previous = null;

            for (HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling)
            {
                if (this.ProjectMgr.CompareNodes(node, n) > 0)
                    break;

                previous = n;
            }

            // insert "node" after "previous".
            if (previous != null)
            {
                node.NextSibling = previous.NextSibling;
                previous.NextSibling = node;

                if (previous == this.LastChild)
                    this.LastChild = node;
            }
            else
            {
                if (this.LastChild == null)
                    this.LastChild = node;

                node.NextSibling = this.FirstChild;
                this.FirstChild = node;
            }

            node.Parent = this;
            this.OnItemAdded(this, node);

            NemerleProjectNode project = ProjectMgr as NemerleProjectNode;

            if (project != null && project.ProjectInfo.IsLoaded)
            {
                ReferenceNode referenceNode = (ReferenceNode)node;
                //TODO: Добавлять только если project.ProjectInfo.IsLoaded == екгу
                project.ProjectInfo.AddMacroAssembly(referenceNode);
            }
        }
 /// <summary>
 /// Adds a file to the project hierarchy with the specified parent.
 /// </summary>
 /// <param name="parent"></param>
 /// <param name="isSearchPath"></param>
 /// <param name="file"></param>
 protected void AddFile(HierarchyNode parent, bool isSearchPath, string file) {
     var existing = parent.FindChild(file);
     if (existing == null) {
         FileNode fileNode = CreateFileNode(file);
         //Files in search path are not considered memebers of the project itself
         fileNode.SetProperty((int)__VSHPROPID.VSHPROPID_IsNonMemberItem, isSearchPath);
         parent.AddChild(fileNode);
     }
 }
示例#29
0
        protected void ReloadHierarchy(HierarchyNode parent, IEnumerable<IPackage> modules) {
            //  We're going to reuse nodes for which matching modules exist in the new set.
            //  The reason for this is that we want to preserve the expansion state of the
            //  hierarchy. If we just bin everything off and recreate it all from scratch
            //  it'll all be in the collapsed state, which will be annoying for users who
            //  have drilled down into the hierarchy
            var recycle = new Dictionary<string, DependencyNode>();
            var remove = new List<HierarchyNode>();
            for (var current = parent.FirstChild; null != current; current = current.NextSibling) {
                var dep = current as DependencyNode;
                if (null == dep) {
                    if (!(current is GlobalModulesNode) && !(current is LocalModulesNode)) {
                        remove.Add(current);
                    }
                    continue;
                }

                if (modules != null && modules.Any(
                    module =>
                        module.Name == dep.Package.Name
                        && module.Version == dep.Package.Version
                        && module.IsBundledDependency == dep.Package.IsBundledDependency
                        && module.IsDevDependency == dep.Package.IsDevDependency
                        && module.IsListedInParentPackageJson == dep.Package.IsListedInParentPackageJson
                        && module.IsMissing == dep.Package.IsMissing
                        && module.IsOptionalDependency == dep.Package.IsOptionalDependency)) {
                    recycle[dep.Package.Name] = dep;
                } else {
                    remove.Add(current);
                }
            }

            foreach (var obsolete in remove) {
                parent.RemoveChild(obsolete);
                ProjectMgr.OnItemDeleted(obsolete);
            }

            if (modules != null) {
                foreach (var package in modules) {
                    DependencyNode child;

                    if (recycle.ContainsKey(package.Name)) {
                        child = recycle[package.Name];
                        child.Package = package;
                    }
                    else {
                        child = new DependencyNode(_projectNode, parent as DependencyNode, package);
                        parent.AddChild(child);
                    }

                    ReloadHierarchy(child, package.Modules);
                    if (ProjectMgr.ParentHierarchy != null) {
                        child.ExpandItem(EXPANDFLAGS.EXPF_CollapseFolder);
                    }
                }
            }
        }
示例#30
0
文件: Class1.cs 项目: nhatkycon/spav4
 void buildChild(HierarchyNode<DanhMuc> item, List<DanhMuc> list)
 {
     foreach (HierarchyNode<DanhMuc> _item in item.ChildNodes)
     {
         _item.Entity.Level = _item.Depth;
         list.Add(_item.Entity);
         buildChild(_item, list);
     }
 }
示例#31
0
 public void Add(HierarchyNode node)
 {
     selection.Add(new NodeProperties(node));
 }
示例#32
0
        /// <summary>
        /// Invokes the specified generator
        /// </summary>
        /// <param name="fileNode">The node on which to invoke the generator.</param>
        protected internal virtual void InvokeGenerator(FileNode fileNode)
        {
            if (fileNode == null)
            {
                throw new ArgumentNullException("fileNode");
            }

            SingleFileGeneratorNodeProperties nodeproperties = fileNode.NodeProperties as SingleFileGeneratorNodeProperties;

            if (nodeproperties == null)
            {
                throw new InvalidOperationException();
            }

            string customToolProgID = nodeproperties.CustomTool;

            if (String.IsNullOrEmpty(customToolProgID))
            {
                return;
            }

            string customToolNamespace = nodeproperties.CustomToolNamespace;

            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();

                if (!this.runningGenerator)
                {
                    //Get the buffer contents for the current node
                    string moniker = fileNode.GetMkDocument();

                    this.runningGenerator = true;

                    //Get the generator
                    IVsSingleFileGenerator generator;
                    int generateDesignTimeSource;
                    int generateSharedDesignTimeSource;
                    int generateTempPE;
                    SingleFileGeneratorFactory factory = new SingleFileGeneratorFactory(this.projectMgr.ProjectGuid, this.projectMgr.Site);
                    ErrorHandler.ThrowOnFailure(factory.CreateGeneratorInstance(customToolProgID, out generateDesignTimeSource, out generateSharedDesignTimeSource, out generateTempPE, out generator));

                    //Check to see if the generator supports siting
                    IObjectWithSite objWithSite = generator as IObjectWithSite;
                    if (objWithSite != null)
                    {
                        objWithSite.SetSite(fileNode.OleServiceProvider);
                    }

                    //Determine the namespace
                    if (String.IsNullOrEmpty(customToolNamespace))
                    {
                        customToolNamespace = this.ComputeNamespace(moniker);
                    }

                    //Run the generator
                    IntPtr[] output = new IntPtr[1];
                    output[0] = IntPtr.Zero;
                    uint   outPutSize = 0;
                    string extension  = String.Empty;
                    try
                    {
                        ErrorHandler.ThrowOnFailure(generator.DefaultExtension(out extension));
                    }
                    catch (Exception e)
                    {
                        if (System.Diagnostics.Debugger.IsAttached)
                        {
                            Debug.WriteLine("generator.DefaultExtension failed: " + e.Message);
                        }
                    }
                    //
                    IVsTextStream stream;
                    string        inputFileContents = this.GetBufferContents(moniker, out stream);
                    //
                    // HACK To support T4 Template
                    //
                    //bool utf8 = false;
                    if (String.Compare(Path.GetExtension(fileNode.FileName), ".tt", true) == 0)
                    {
                        // Per default, for a T4 template, convert to UTF8
                        // utf8 = true; ? to be done ??
                        // The Output Extension may be modified by the Template. Check it
                        Regex           t4ParsingRegex = new Regex("output.*\\sextension\\s*=\\s*\"(?<pvalue>.*?)(?<=[^\\\\](\\\\\\\\)*)\"", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.ExplicitCapture);
                        MatchCollection matchs         = t4ParsingRegex.Matches(inputFileContents);
                        if (matchs.Count > 0)
                        {
                            Match match = matchs[0];
                            Group group = match.Groups["pvalue"];
                            extension = group.Value;
                        }
                        // Any Encoding in the Template ?
                        t4ParsingRegex = new Regex("output.*\\sencoding\\s*=\\s*\"(?<pvalue>.*?)(?<=[^\\\\](\\\\\\\\)*)\"", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.ExplicitCapture);
                        matchs         = t4ParsingRegex.Matches(inputFileContents);
                        if (matchs.Count > 0)
                        {
                            Match match = matchs[0];
                            Group group = match.Groups["pvalue"];
                            //utf8 = false;
                        }
                    }

                    //Find if any dependent node exists
                    string        dependentNodeName = Path.GetFileNameWithoutExtension(fileNode.FileName) + extension;
                    HierarchyNode dependentNode     = fileNode.FirstChild;
                    while (dependentNode != null)
                    {
                        if (String.Compare(dependentNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon), fileNode.FileName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            dependentNodeName = ((FileNode)dependentNode).FileName;
                            break;
                        }

                        dependentNode = dependentNode.NextSibling;
                    }

                    //If you found a dependent node.
                    if (dependentNode != null)
                    {
                        //Then check out the node and dependent node from SCC
                        if (!this.CanEditFile(dependentNode.GetMkDocument()))
                        {
                            throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                        }
                    }
                    else //It is a new node to be added to the project
                    {
                        // Check out the project file if necessary.
                        if (!this.projectMgr.QueryEditProjectFile(false))
                        {
                            throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                        }
                    }


                    try
                    {
                        ErrorHandler.ThrowOnFailure(generator.Generate(moniker, inputFileContents, customToolNamespace, output, out outPutSize, this));
                    }
                    catch (Exception e)
                    {
                        if (System.Diagnostics.Debugger.IsAttached)
                        {
                            Debug.WriteLine("generator.Generate failed: " + e.Message);
                        }
                    }
                    if (outPutSize > 0)
                    {
                        byte[] data = new byte[outPutSize];

                        if (output[0] != IntPtr.Zero)
                        {
                            Marshal.Copy(output[0], data, 0, (int)outPutSize);
                            Marshal.FreeCoTaskMem(output[0]);
                        }
                        // HACK T4 Support

                        /*
                         * utf8 = false;
                         * if (utf8)
                         * {
                         *  System.Text.StringBuilder sb = new System.Text.StringBuilder();
                         *  sb.Append(System.Text.Encoding.ASCII.GetString(data, 0, (int)outPutSize));
                         *  //
                         *  System.Text.Encoding enc = new System.Text.UTF8Encoding(true);
                         *  byte[] preamble = enc.GetPreamble();
                         *  byte[] encData = enc.GetBytes(sb.ToString());
                         *  //
                         *  outPutSize = (uint)encData.Length + (uint)preamble.Length;
                         *  data = new byte[outPutSize];
                         *  Array.Copy(preamble, data, preamble.Length);
                         *  Array.Copy(encData, 0, data, preamble.Length, encData.Length);
                         * }
                         */
                        //Todo - Create a file and add it to the Project
                        string fileToAdd = this.UpdateGeneratedCodeFile(fileNode, data, (int)outPutSize, dependentNodeName);
                    }
                }
            }
            finally
            {
                this.runningGenerator = false;
            }
        }
示例#33
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="project">The associated project.</param>
 /// <param name="nodeWithItems">The node that defines the items.</param>
 public OANavigableProjectItems(OAProject project, HierarchyNode nodeWithItems)
 {
     this.project       = project;
     this.nodeWithItems = nodeWithItems;
     this.items         = this.GetListOfProjectItems();
 }
示例#34
0
 public FileNodeProperties(HierarchyNode node)
     : base(node)
 {
 }
示例#35
0
        protected override void OnInit(EventArgs e)
        {
            FS     = Engine.Resolve <IFileSystem>();
            Config = Engine.Resolve <ConfigurationManagerWrapper>().Sections.Management;
            Register.JQueryUi(Page);
            var selected = Selection.SelectedItem;

            if (IsPostBack && !string.IsNullOrEmpty(inputFile.PostedFile.FileName))
            {
                string uploadFolder = Request[inputLocation.UniqueID];
                if (!IsAvailable(uploadFolder))
                {
                    throw new N2Exception("Cannot upload to " + Server.HtmlEncode(uploadFolder));
                }

                string fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
                string filePath = Url.Combine(uploadFolder, fileName);
                FS.WriteFile(filePath, inputFile.PostedFile.InputStream);

                ClientScript.RegisterStartupScript(typeof(Tree), "select", "updateOpenerWithUrlAndClose('" + ResolveUrl(filePath) + "');", true);
            }
            else if (Request["location"] == "files" || Request["location"] == "filesselection")
            {
                IHost host = Engine.Resolve <IHost>();
                HierarchyNode <ContentItem> root = new HierarchyNode <ContentItem>(Engine.Persister.Get(host.DefaultSite.RootItemID));

                var selectionTrail = new List <ContentItem>();
                if (selected is AbstractNode)
                {
                    selectionTrail = new List <ContentItem>(Find.EnumerateParents(selected, null, true));
                }
                else
                {
                    TrySelectingPrevious(ref selected, ref selectionTrail);
                }

                foreach (var upload in Engine.Resolve <UploadFolderSource>().GetUploadFoldersForAllSites())
                {
                    var dir = N2.Management.Files.FolderNodeProvider.CreateDirectory(upload, FS, Engine.Persister, Engine.Resolve <IDependencyInjector>());

                    if (!Engine.SecurityManager.IsAuthorized(dir, User))
                    {
                        continue;
                    }

                    var node = CreateDirectoryNode(FS, dir, root, selectionTrail);
                    root.Children.Add(node);
                }

                siteTreeView.Nodes        = root;
                siteTreeView.SelectedItem = selected;
            }
            else
            {
                var filter = Engine.EditManager.GetEditorFilter(Page.User);
                siteTreeView.Filter       = filter;
                siteTreeView.RootNode     = Engine.Resolve <Navigator>().Navigate(Request["root"] ?? "/");
                siteTreeView.SelectedItem = selected;
            }

            siteTreeView.SelectableTypes      = Request["selectableTypes"];
            siteTreeView.SelectableExtensions = Request["selectableExtensions"];
            siteTreeView.DataBind();

            inputLocation.Value = siteTreeView.SelectedItem.Url;

            base.OnInit(e);
        }
示例#36
0
        private static HierarchyNode <ContentItem> CreateDirectoryNode(IFileSystem fs, ContentItem directory, HierarchyNode <ContentItem> parent, List <ContentItem> selectionTrail)
        {
            var node = new HierarchyNode <ContentItem>(directory);

            ExpandRecursive(fs, node, selectionTrail);

            return(node);
        }
示例#37
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="project">The associated project.</param>
 /// <param name="nodeWithItems">The node that defines the items.</param>
 internal OANavigableProjectItems(OAProject project, HierarchyNode nodeWithItems)
 {
     this.project       = project;
     this.nodeWithItems = nodeWithItems;
 }
示例#38
0
 public FolderNodeProperties(HierarchyNode node)
     : base(node)
 {
 }
 internal InterpretersNodeProperties(HierarchyNode node)
     : base(node)
 {
 }
            private async Task ChildCreatedAsync(HierarchyNode child)
            {
                if (this.project.IsFileHidden(this.path))
                {
                    // don't add hidden files/folders
                    return;
                }

                // creating a new item, need to create the on all files node
                var parent = this.project.GetParentFolderForPath(this.path);

                if (parent == null)
                {
                    // we've hit an error while adding too many files, the file system watcher
                    // couldn't keep up.  That's alright, we'll merge the files in correctly
                    // in a little while...
                    return;
                }

                var wasExpanded = parent.GetIsExpanded();

                if (Directory.Exists(this.path))
                {
                    if (IsFileSymLink(this.path))
                    {
                        var parentDir = CommonUtils.GetParent(this.path);
                        if (IsRecursiveSymLink(parentDir, this.path))
                        {
                            // don't add recusrive sym link directory
                            return;
                        }

                        // otherwise we're going to need a new file system watcher
                        this.project.CreateSymLinkWatcher(this.path);
                    }

                    var folderNode            = this.project.AddAllFilesFolder(parent, this.path);
                    var folderNodeWasExpanded = folderNode.GetIsExpanded();

                    // then add the folder nodes
                    await this.project.MergeDiskNodesAsync(folderNode, this.path).ConfigureAwait(true);

                    // Assert we're back on the UI thread
                    this.project.Site.GetUIThread().MustBeCalledFromUIThread();

                    this.project.OnInvalidateItems(folderNode);

                    folderNode.ExpandItem(folderNodeWasExpanded ? EXPANDFLAGS.EXPF_ExpandFolder : EXPANDFLAGS.EXPF_CollapseFolder);
                }
                else if (File.Exists(this.path))
                {
                    // rapid changes can arrive out of order, make sure the file still exists
                    this.project.AddAllFilesFile(parent, this.path);
                    if (StringComparer.OrdinalIgnoreCase.Equals(this.project.GetStartupFile(), this.path))
                    {
                        this.project.BoldStartupItem();
                    }
                }

                parent.ExpandItem(wasExpanded ? EXPANDFLAGS.EXPF_ExpandFolder : EXPANDFLAGS.EXPF_CollapseFolder);
            }
示例#41
0
 public NodeProperties(HierarchyNode node)
 {
     this.node = node;
 }
 public void CustomizeModel(PfeDataModel model, IWebEasRepositoryBase repository, HierarchyNode node, string filter, HierarchyNode masterNode, string kodPolozkyModulu)
 {
     /*
      * if (model.Fields != null)
      * {
      *  var icoField = model.Fields.FirstOrDefault(p => p.Name == nameof(ICO));
      *  if (icoField != null)
      *  {
      *      icoField.SearchFieldDefinition = new List<PfeSearchFieldDefinition>
      *      {
      *          new PfeSearchFieldDefinition
      *          {
      *              Code = "osa-oso-po",
      *              NameField = nameof(PO_OsobaView.D_PO_Osoba_Id),
      *              DisplayField = nameof(PO_OsobaView.ICO),
      *              InputSearchField = nameof(PO_OsobaView.InputSearchField)
      *          }
      *      };
      *  }
      * }
      */
 }
        public void CustomizeModel(PfeDataModel model, IWebEasRepositoryBase repository, HierarchyNode node, string filter, HierarchyNode masterNode, string kodPolozkyModulu)
        {
            int isoZdroj      = (int)repository.GetNastavenieI("cfe", "ISOZdroj");
            var isoZdrojNazov = repository.GetNastavenieS("cfe", "ISOZdrojNazov");

            if (model.Fields != null)
            {
                var poradieField = model.Fields.FirstOrDefault(p => p.Name == nameof(Poradie));

                if (poradieField != null)
                {
                    poradieField.Validator = new PfeValidator
                    {
                        Rules = new List <PfeRule>
                        {
                            new PfeRule
                            {
                                ValidatorType = PfeValidatorType.SetMin,
                                Min           = "1"
                            }
                        }
                    };
                }

                if (repository.GetNastavenieI("cfe", "eSAMRezim") != 1 && repository.Session.AdminLevel != AdminLevel.SysAdmin)
                {
                    model.Fields.FirstOrDefault(p => p.Name == nameof(DCOM)).Text = "_DCOM";
                }

                if (isoZdroj == 0 && repository.Session.AdminLevel != AdminLevel.SysAdmin)
                {
                    model.Fields.FirstOrDefault(p => p.Name == nameof(ISO)).Text = "_ISO";
                }
            }

            if (isoZdroj > 0 && repository.Session.Roles.Where(w => w.Contains("REG_MIGRATOR")).Any() && model.Type != PfeModelType.Form)
            {
                if (node.Actions.Any(x => x.ActionType == NodeActionType.MenuButtonsAll))
                {
                    var polozkaMenuAll = node.Actions.Where(x => x.ActionType == NodeActionType.MenuButtonsAll && x.Caption == "ISO").FirstOrDefault();
                    if (polozkaMenuAll != null)
                    {
                        polozkaMenuAll.Caption = isoZdrojNazov;
                    }
                }
            }
            else
            {
                node.Actions.RemoveAll(x => x.ActionType == NodeActionType.MenuButtonsAll && x.Caption == "ISO");
            }
        }
示例#44
0
        public override object GetRowDefaultValues(string code, string masterCode, string masterRowId, string copyId)
        {
            //Odkomentovať keď to chcem použiť
            var           root       = RenderModuleRootNode;
            var           node       = root.TryFindNode(code);
            HierarchyNode masternode = null;

            if (!masterCode.IsNullOrEmpty())
            {
                masternode = root.TryFindNode(masterCode);
            }

            #region D_PRI_0, D_VYD_0

            if (node != null && (node.ModelType == typeof(V_PRI_0View) || node.ModelType == typeof(V_VYD_0View)))
            {
                var FirstOrj = GetList <tblK_ORJ_0>().OrderBy(x => x.Serial_No).FirstOrDefault();
                var FirstSkl = GetList <tblK_SKL_0>().OrderBy(x => x.Serial_No).FirstOrDefault();

                return(new Pri0Vyd0Defaults()
                {
                    DAT_DKL = DateTime.Now.Date,
                    K_ORJ_0 = (int)(FirstOrj?.K_ORJ_0 ?? null),
                    K_SKL_0 = (int)(FirstSkl?.K_SKL_0 ?? null)
                });
            }

            #endregion

            #region D_SIM_0

            if (node != null && node.ModelType == typeof(V_SIM_0View))
            {
                short r = 1;
                byte  t = 1;

                if (masternode == null || string.IsNullOrEmpty(masterRowId))
                {
                    //nic
                }
                else if (masternode.ModelType == typeof(V_PRI_0View))
                {
                    var poslednaPolozka = GetList <tblD_SIM_0>(x => x.D_PRI_0 == Convert.ToInt16(masterRowId)).OrderByDescending(x => x.RANK).FirstOrDefault();
                    r = (short)((poslednaPolozka?.RANK ?? 0) + 1);
                    t = 1; //"+" - PV3DCombo.GetText
                }
                else if (masternode.ModelType == typeof(V_VYD_0View))
                {
                    var poslednaPolozka = GetList <tblD_SIM_0>(x => x.D_VYD_0 == Convert.ToInt16(masterRowId)).OrderByDescending(x => x.RANK).FirstOrDefault();
                    r = (short)((poslednaPolozka?.RANK ?? 0) + 1);
                    t = 2; //"-" - PV3DCombo.GetText
                }
                return(new SimDefaults()
                {
                    RANK = r,
                    PV = t
                });
            }

            #endregion

            #region D_PRI_1, D_VYD_1

            if (node != null && masternode != null && !string.IsNullOrEmpty(masterRowId) && (node.ModelType == typeof(V_PRI_1View) || node.ModelType == typeof(V_VYD_1View)))
            {
                Pri1Vyd1Defaults def = new Pri1Vyd1Defaults()
                {
                    RANK = 1
                };

                if (masternode.ModelType == typeof(V_PRI_0View))
                {
                    var poslednaPolozka = GetList <tblD_PRI_1>(x => x.D_PRI_0 == Convert.ToInt16(masterRowId)).OrderByDescending(x => x.RANK).FirstOrDefault();
                    if (poslednaPolozka != null)
                    {
                        def.RANK = (short)((poslednaPolozka?.RANK ?? 0) + 1);
                    }

                    var masterRow = GetById <V_PRI_0View>(masterRowId);
                    if (masterRow != null)
                    {
                        def.K_SKL_0 = masterRow.K_SKL_0;
                    }
                }
                else if (masternode.ModelType == typeof(V_VYD_0View))
                {
                    var poslednaPolozka = GetList <tblD_VYD_1>(x => x.D_VYD_0 == Convert.ToInt16(masterRowId)).OrderByDescending(x => x.RANK).FirstOrDefault();
                    if (poslednaPolozka != null)
                    {
                        def.RANK = (short)((poslednaPolozka?.RANK ?? 0) + 1);
                    }

                    var masterRow = GetById <V_VYD_0View>(masterRowId);
                    if (masterRow != null)
                    {
                        def.K_SKL_0 = masterRow.K_SKL_0;
                    }
                }
                return(def);
            }

            #endregion



            return(new object());
        }
        public void ComboCustomize(IWebEasRepositoryBase repository, string column, string kodPolozky, Dictionary <string, string> requiredFields, ref PfeComboAttribute comboAttribute, HierarchyNode node)
        {
            //if (kodPolozky.Equals("fin-bnk-ban") || kodPolozky.Equals("fin-bnk-ppp"))
            if (kodPolozky.Equals("fin-bnk-ban")) //Prevodné príkazy majú zobraziť všetky bank. účty
            {
                comboAttribute.FilterByOrsPravo = true;
            }

            if (kodPolozky.Equals("fin-bnk-ppp"))
            {
                comboAttribute.AdditionalWhereSql += $" AND C_Mena_Id = {(int)MenaEnum.EUR}";
            }
        }
示例#46
0
 internal OAProjectItems(OAProject project, HierarchyNode nodeWithItems)
     : base(project, nodeWithItems)
 {
 }
示例#47
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="project">The associated project.</param>
 /// <param name="items">A list of items that will make up the items defined by this object.</param>
 /// <param name="nodeWithItems">The node that defines the items.</param>
 public OANavigableProjectItems(OAProject project, IList <EnvDTE.ProjectItem> items, HierarchyNode nodeWithItems)
 {
     this.items         = items;
     this.project       = project;
     this.nodeWithItems = nodeWithItems;
 }
示例#48
0
 public SelectionContainer(HierarchyNode node)
 {
     selection = new ArrayList();
     selection.Add(new NodeProperties(node));
 }
 public HierarchyNodeEventArgs(HierarchyNode child)
 {
     this.child = child;
 }
示例#50
0
        protected internal virtual void InvokeGeneratorEx(FileNode fileNode, String document, bool runEvenIfNotDirty)
        {
            base.InvokeGenerator(fileNode);
            Utilities.ArgumentNotNull("fileNode", fileNode);

            SingleFileGeneratorNodeProperties nodeproperties = fileNode.NodeProperties as SingleFileGeneratorNodeProperties;

            if (nodeproperties == null)
            {
                throw new InvalidOperationException();
            }

            string customToolProgID = nodeproperties.CustomTool;

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

            // not sure what to do if BuildAction is set to "MSBuild:Compile".  IronPython doesn't handle this correctly either.
            // This build action is set for .xaml files but doing nothing doesn't seem to cause problems, so for now we ignore this
            // generator type and do nothing too.  If we don't do this, we get lots of message boxes when the clsid of this non-existent
            // single file generator isn't found.

            // We should try to find out what the proper action is here.  There is no "MSBuild:Compile" entry in the registry
            // for the C# or VB project system single file generators, so there must be some special handling for this build type
            // otherwise it would just be blank.  Naturally, the IronPython sample isn't any help here.

            if (customToolProgID.StartsWith("MSBuild:Compile", StringComparison.OrdinalIgnoreCase))
            {
                var project = fileNode.ProjectMgr as XSharpProjectNode;
                if (project.IsXamlFile(document))
                {
                    // need to generate the .g.prg file.
                    project.Build(project.CurrentConfig.ConfigCanonicalName, "BuildGenerateSources"); //  BuildGenerateSources
                }
                // The C# project system then calls a InvokeMsBuild method with the following contents

                /*
                 * HRESULT CVsProjBaseFileNode::InvokeMSBuildTarget(_In_z_ LPCWSTR wszMSBuildTarget)
                 * {
                 *  HRESULT hr = NOERROR;
                 *
                 *  if (wszMSBuildTarget != NULL)
                 *  {
                 *      CLangBuildMgr *pBuildMgr = GetProject()->GetBuildMgr();
                 *      CComPtr<MSBuildEngine::IProject> srpMSBuildProject = pBuildMgr->GetMSBuildProject();
                 *
                 *      if (CXMakeHelper::DoesTargetExist(srpMSBuildProject, wszMSBuildTarget) && pBuildMgr->HasPassedSecurityChecks())
                 *      {
                 *          // Initialize the build engine for this project and configuration.
                 *          CSmartMSBuildInitializer smsbi;
                 *          CLangProjectConfig *pProjConfig = pBuildMgr->GetConfigs()->GetActiveConfig();
                 *          hr = smsbi.Initialize(pBuildMgr, pProjConfig);
                 *
                 *          if (SUCCEEDED(hr))
                 *          {
                 *              // Build the specified target in the MSBuild project.
                 *              hr = pBuildMgr->BuildTarget(wszMSBuildTarget);
                 *          }
                 *
                 *          // Don't bother keeping the return value here--we want to
                 *          // return failure from Initialize or BuildTarget instead.
                 *          smsbi.Restore(pBuildMgr);
                 *      }
                 *  }
                 *
                 *  return hr;
                 * }
                 */
                return;
            }

            string customToolNamespace = nodeproperties.CustomToolNamespace;

            try
            {
                if (!this.runningGenerator)
                {
                    //Find if any dependent node exists
                    string        dependentNodeName = null;
                    HierarchyNode dependentNode     = fileNode.FirstChild;

                    while (dependentNode != null)
                    {
                        string dependentUpon = dependentNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);

                        if (!String.IsNullOrEmpty(dependentUpon))
                        {
                            if (!Path.IsPathRooted(dependentUpon))
                            {
                                dependentUpon = Path.Combine(Path.GetDirectoryName(fileNode.Url), dependentUpon);
                            }

                            if (string.Compare(dependentUpon, fileNode.Url, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                dependentNodeName = ((FileNode)dependentNode).FileName;
                                break;
                            }
                        }

                        dependentNode = dependentNode.NextSibling;
                    }

                    bool outputOutOfDate = dependentNodeName == null;

                    if ((!runEvenIfNotDirty) && !outputOutOfDate)
                    {
                        string generatedFile = Path.Combine(Path.GetDirectoryName(fileNode.GetMkDocument()), dependentNodeName);

                        outputOutOfDate = !File.Exists(generatedFile);

                        if (!outputOutOfDate)
                        {
                            outputOutOfDate = File.GetLastWriteTime(fileNode.GetMkDocument()) > File.GetLastWriteTime(generatedFile);

                            if (!outputOutOfDate)
                            {
                                IVsHierarchy      rdtHier;
                                IVsPersistDocData perDocData;
                                uint cookie;
                                outputOutOfDate = this.VerifyFileDirtyInRdt(document, out rdtHier, out perDocData, out cookie);
                            }
                        }
                    }

                    //if (runEvenIfNotDirty || outputOutOfDate)
                    {
                        //Get the buffer contents for the current node
                        string moniker = fileNode.GetMkDocument();

                        this.runningGenerator = true;
                        anyGeneratorsRunning++;

                        //Get the generator
                        IVsSingleFileGenerator generator;
                        int generateDesignTimeSource;
                        int generateSharedDesignTimeSource;
                        int generateTempPE;
                        SingleFileGeneratorFactory factory = new SingleFileGeneratorFactory(this.ProjectMgr.ProjectGuid, this.ProjectMgr.Site);
                        ErrorHandler.ThrowOnFailure(factory.CreateGeneratorInstance(customToolProgID, out generateDesignTimeSource, out generateSharedDesignTimeSource, out generateTempPE, out generator));

                        //Check to see if the generator supports siting
                        IObjectWithSite objWithSite = generator as IObjectWithSite;
                        if (objWithSite != null)
                        {
                            objWithSite.SetSite(fileNode.OleServiceProvider);
                        }

                        //Determine the namespace
                        if (string.IsNullOrEmpty(customToolNamespace))
                        {
                            customToolNamespace = this.ComputeNamespace(moniker);
                        }

                        //Run the generator
                        IntPtr[] output = new IntPtr[1];
                        output[0] = IntPtr.Zero;
                        uint outPutSize;

                        if (dependentNodeName == null)
                        {
                            string extension = null;
                            try
                            {
                                generator.DefaultExtension(out extension);
                            }
                            catch (Exception e)
                            {
                                if (System.Diagnostics.Debugger.IsAttached)
                                {
                                    Debug.WriteLine(e);
                                }
                            }
                            if (!String.IsNullOrEmpty(extension))
                            {
                                dependentNodeName = Path.GetFileNameWithoutExtension(fileNode.FileName) + extension;
                            }
                            else
                            {
                                dependentNodeName = fileNode.FileName;
                            }
                        }


                        //If you found a dependent node.
                        if (dependentNode != null)
                        {
                            //Then check out the node and dependent node from SCC
                            if (!this.CanEditFile(dependentNode.GetMkDocument()))
                            {
                                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                            }
                        }
                        else //It is a new node to be added to the project
                        {
                            // Check out the project file if necessary.
                            if (!this.ProjectMgr.QueryEditProjectFile(false))
                            {
                                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                            }
                        }
                        IVsTextStream stream;
                        string        inputFileContents = this.GetBufferContents(moniker, out stream);

                        var    res  = generator.Generate(moniker, inputFileContents, customToolNamespace, output, out outPutSize, this);
                        byte[] data = new byte[outPutSize];

                        if (output[0] != IntPtr.Zero)
                        {
                            Marshal.Copy(output[0], data, 0, (int)outPutSize);
                            Marshal.FreeCoTaskMem(output[0]);
                        }

                        //Todo - Create a file and add it to the Project
                        string fileToAdd = this.UpdateGeneratedCodeFile(fileNode, data, (int)outPutSize, dependentNodeName, dependentNode);
                    }
                }
            }
            finally
            {
                this.runningGenerator = false;
                anyGeneratorsRunning--;
            }
        }
示例#51
0
        private IEnumerable <HierarchyNode <IContainable> > AddContainersToRootContainer(HierarchyNode <IContainable> rootContainer, IEnumerable <IContainable> containersToProcess)
        {
            var addedContainers = new List <HierarchyNode <IContainable> >(new HierarchyNode <IContainable>[] { rootContainer });
            var queue           = new Queue <IContainable>(containersToProcess);

            while (queue.Count > 0)
            {
                var current = queue.Dequeue();
                if (current.ContainerName == current.Name)
                {
                    throw new N2Exception("The container '{0}' cannot reference itself as containing container. Change the ContainerName property.", current.Name);
                }

                string containerName = current.ContainerName;
                var    container     = addedContainers.FirstOrDefault(c => c.Current.Name == containerName);
                if (container != null)
                {
                    // the container was previously in the loop
                    var node = new HierarchyNode <IContainable>(current);
                    container.Add(node);
                    addedContainers.Add(node);
                }
                else if (!queue.Any(c => c.Name == containerName))
                {
                    // no container - add to root
                    var node = new HierarchyNode <IContainable>(current);
                    rootContainer.Add(node);
                    addedContainers.Add(node);
                }
                else
                {
                    // the container is in the queue - add this to end
                    queue.Enqueue(current);
                }
            }
            return(addedContainers);
        }
示例#52
0
        /// <summary>
        /// Invokes the specified generator
        /// </summary>
        /// <param name="fileNode">The node on which to invoke the generator.</param>
        protected internal virtual void InvokeGenerator(FileNode fileNode)
        {
            if (fileNode == null)
            {
                throw new ArgumentNullException("node");
            }

            SingleFileGeneratorNodeProperties nodeproperties = fileNode.NodeProperties as SingleFileGeneratorNodeProperties;

            if (nodeproperties == null)
            {
                throw new InvalidOperationException();
            }

            string customToolProgID = nodeproperties.CustomTool;

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

            string customToolNamespace = nodeproperties.CustomToolNamespace;

            try
            {
                if (!this.runningGenerator)
                {
                    //Get the buffer contents for the current node
                    string moniker = fileNode.GetMkDocument();

                    this.runningGenerator = true;

                    //Get the generator
                    IVsSingleFileGenerator generator;
                    int generateDesignTimeSource;
                    int generateSharedDesignTimeSource;
                    int generateTempPE;
                    SingleFileGeneratorFactory factory = new SingleFileGeneratorFactory(this.projectMgr.ProjectGuid, this.projectMgr.Site);
                    ErrorHandler.ThrowOnFailure(factory.CreateGeneratorInstance(customToolProgID, out generateDesignTimeSource, out generateSharedDesignTimeSource, out generateTempPE, out generator));

                    //Check to see if the generator supports siting
                    IObjectWithSite objWithSite = generator as IObjectWithSite;
                    if (objWithSite != null)
                    {
                        objWithSite.SetSite(fileNode.OleServiceProvider);
                    }

                    //Determine the namespace
                    if (string.IsNullOrEmpty(customToolNamespace))
                    {
                        customToolNamespace = this.ComputeNamespace(moniker);
                    }

                    //Run the generator
                    IntPtr[] output = new IntPtr[1];
                    output[0] = IntPtr.Zero;
                    uint   outPutSize;
                    string extension;
                    ErrorHandler.ThrowOnFailure(generator.DefaultExtension(out extension));

                    //Find if any dependent node exists
                    string        dependentNodeName = Path.GetFileNameWithoutExtension(fileNode.FileName) + extension;
                    HierarchyNode dependentNode     = fileNode.FirstChild;
                    while (dependentNode != null)
                    {
                        if (string.Compare(dependentNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon), fileNode.FileName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            dependentNodeName = ((FileNode)dependentNode).FileName;
                            break;
                        }

                        dependentNode = dependentNode.NextSibling;
                    }

                    //If you found a dependent node.
                    if (dependentNode != null)
                    {
                        //Then check out the node and dependent node from SCC
                        if (!this.CanEditFile(dependentNode.GetMkDocument()))
                        {
                            throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                        }
                    }
                    else                     //It is a new node to be added to the project
                    {
                        // Check out the project file if necessary.
                        if (!this.projectMgr.QueryEditProjectFile(false))
                        {
                            throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                        }
                    }
                    IVsTextStream stream;
                    string        inputFileContents = this.GetBufferContents(moniker, out stream);

                    ErrorHandler.ThrowOnFailure(generator.Generate(moniker, inputFileContents, customToolNamespace, output, out outPutSize, this));
                    byte[] data = new byte[outPutSize];

                    if (output[0] != IntPtr.Zero)
                    {
                        Marshal.Copy(output[0], data, 0, (int)outPutSize);
                        Marshal.FreeCoTaskMem(output[0]);
                    }

                    //Todo - Create a file and add it to the Project
                    string fileToAdd = this.UpdateGeneratedCodeFile(fileNode, data, (int)outPutSize, dependentNodeName);
                }
            }
            finally
            {
                this.runningGenerator = false;
            }
        }
示例#53
0
 public void Set(HierarchyNode node)
 {
     selection.Clear();
     selection.Add(new NodeProperties(node));
 }
示例#54
0
 public SingleFileGeneratorNodeProperties(HierarchyNode node)
     : base(node)
 {
 }
 public NemerleProjectReferencesProperties(HierarchyNode node, string className)
     : base(node)
 {
     _className = className + "!";
 }
示例#56
0
 public OAProjectItems(OAProject project, HierarchyNode nodeWithItems)
     : base(project, nodeWithItems)
 {
 }
示例#57
0
 protected virtual Node <TreeNode> GetStructure(HierarchyNode <ContentItem> structure, ItemFilter filter)
 {
     return(structure.CreateNode(engine.Resolve <IContentAdapterProvider>(), filter));
 }
示例#58
0
 public ReferenceNodeProperties(HierarchyNode node)
     : base(node)
 {
 }
示例#59
0
        /// <summary>
        /// Handles command status on source a node. Should be overridden by descendant nodes.
        /// </summary>
        /// <param name="node">A HierarchyNode that implements the IProjectSourceNode interface.</param>
        /// <param name="guidCmdGroup">A unique identifier of the command group. The pguidCmdGroup parameter can be NULL to specify the standard group.</param>
        /// <param name="cmd">The command to query status for.</param>
        /// <param name="result">An out parameter specifying the QueryStatusResult of the command.</param>
        /// <param name="returnCode">If the method succeeds, it returns S_OK. If it fails, it returns an error code.</param>
        /// <returns>Returns true if the status request is handled, false otherwise.</returns>
        internal static bool QueryStatusOnProjectSourceNode(HierarchyNode node, Guid guidCmdGroup, uint cmd, ref QueryStatusResult result, out int returnCode)
        {
            if (guidCmdGroup == VsMenus.guidStandardCommandSet2K)
            {
                IProjectSourceNode sourceNode = node as IProjectSourceNode;
                switch ((VsCommands2K)cmd)
                {
                case VsCommands2K.SHOWALLFILES:
                {
                    WixProjectNode projectNode = node.ProjectMgr as WixProjectNode;
                    result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
                    if (projectNode != null && projectNode.ShowAllFilesEnabled)
                    {
                        result |= QueryStatusResult.LATCHED;         // it should be displayed as pressed
                    }

                    returnCode = VSConstants.S_OK;
                    return(true);        // handled.
                }

                case VsCommands2K.INCLUDEINPROJECT:
                    // if it is a non member item node, the we support "Include In Project" command
                    if (sourceNode != null && sourceNode.IsNonMemberItem)
                    {
                        result    |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
                        returnCode = VSConstants.S_OK;
                        return(true);    // handled.
                    }

                    break;

                case VsCommands2K.EXCLUDEFROMPROJECT:
                    // if it is a non member item node, then we don't support "Exclude From Project" command
                    if (sourceNode != null && sourceNode.IsNonMemberItem)
                    {
                        returnCode = (int)OleConstants.MSOCMDERR_E_NOTSUPPORTED;
                        return(true);    // handled.
                    }

                    break;
                }
            }

            if (VsMenus.guidStandardCommandSet97 == guidCmdGroup)
            {
                switch ((VsCommands)cmd)
                {
                case VsCommands.AddNewItem:
                case VsCommands.AddExistingItem:
                    result     = QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
                    returnCode = VSConstants.S_OK;
                    return(true);

                case VsCommands.SetStartupProject:
                    result     = QueryStatusResult.SUPPORTED | QueryStatusResult.INVISIBLE;
                    returnCode = VSConstants.S_OK;
                    return(true);
                }
            }

            // just an arbitrary value, it doesn't matter if method hasn't handled the request
            returnCode = VSConstants.S_FALSE;

            // not handled
            return(false);
        }
示例#60
0
        protected virtual string UpdateGeneratedCodeFile(FileNode fileNode, byte[] data, int size, string fileName, HierarchyNode dependentNode)
        {
            string filePath             = Path.Combine(Path.GetDirectoryName(fileNode.GetMkDocument()), fileName);
            IVsRunningDocumentTable rdt = this.ProjectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;

            // (kberes) Shouldn't this be an InvalidOperationException instead with some not to annoying errormessage to the user?
            if (rdt == null)
            {
                ErrorHandler.ThrowOnFailure(VSConstants.E_FAIL);
            }

            IVsHierarchy hier;
            uint         cookie;
            uint         itemid;
            IntPtr       docData = IntPtr.Zero;

            ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)(_VSRDTFLAGS.RDT_NoLock), filePath, out hier, out itemid, out docData, out cookie));
            if (docData != IntPtr.Zero)
            {
                Marshal.Release(docData);
                IVsTextStream srpStream;
                string        inputFileContents = this.GetBufferContents(filePath, out srpStream);
                if (srpStream != null)
                {
                    int oldLen = 0;
                    int hr     = srpStream.GetSize(out oldLen);
                    if (ErrorHandler.Succeeded(hr))
                    {
                        IntPtr dest = IntPtr.Zero;
                        try
                        {
                            if (data.Length > 2 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF)
                            {
                                // the data is in UTF-8 format and must be converted to Unicode, since the IVsTextStream
                                // buffer is always Unicode
                                //
                                // The ResXCodeGenerator generates UTF-8 code, other SingleFileGenerators might do the same thing, who knows?

                                string txt = new System.Text.UTF8Encoding().GetString(data, 3, data.Length - 3);  // skip over encoding preamble

                                UnicodeEncoding enc         = new UnicodeEncoding();
                                int             len         = enc.GetByteCount(txt);
                                Byte[]          unicodeData = new Byte[len];
                                enc.GetBytes(txt, 0, txt.Length, unicodeData, 0);

                                dest = Marshal.AllocCoTaskMem(len);
                                Marshal.Copy(unicodeData, 0, dest, unicodeData.Length);
                                ErrorHandler.ThrowOnFailure(srpStream.ReplaceStream(0, oldLen, dest, len / 2)); // Note: 4th param is # of chars, not bytes!
                            }
                            // end of changes
                            else
                            {
                                dest = Marshal.AllocCoTaskMem(data.Length);
                                Marshal.Copy(data, 0, dest, data.Length);
                                ErrorHandler.ThrowOnFailure(srpStream.ReplaceStream(0, oldLen, dest, size / 2));
                            }

                            // for now, always save the generated file.  Otherwise we have issues when the source file is dirty and the user
                            // builds the project.  The generator runs (because of the overridden SaveItem() in the project node) but the generated
                            // file ends up dirty and when the project is built, everything should be saved.
                            // We could probably force a save on that node, but it seems cleaner to always save the generated file.

                            int canceled;
                            ErrorHandler.ThrowOnFailure(this.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, filePath, dependentNode.ID, docData, out canceled));
                        }
                        finally
                        {
                            if (dest != IntPtr.Zero)
                            {
                                Marshal.Release(dest);
                            }
                        }
                    }
                }
            }
            else
            {
                using (FileStream generatedFileStream = File.Open(filePath, FileMode.OpenOrCreate))
                {
                    generatedFileStream.Write(data, 0, size);
                    // adjust length, in case the file shrinks in size..
                    generatedFileStream.SetLength(size);
                }

                EnvDTE.ProjectItem projectItem = fileNode.GetAutomationObject() as EnvDTE.ProjectItem;
                if (projectItem != null && (this.ProjectMgr.FindChild(fileNode.FileName) == null))
                {
                    projectItem.ProjectItems.AddFromFile(filePath);
                }
            }
            return(filePath);
        }