Exemplo n.º 1
0
 protected override void VisitEnum(CodeEnum codeEnum)
 {
     if (codeEnum.FullName == _classFullName)
     {
         _result = codeEnum.ProjectItem;
     }
 }
        public ProcessResult Execute(ProcessInfo processInfo, ProjectItem item, TaskExecutionContext context)
        {
            var outputFile = context.GeneratePathInWorkingDirectory(item.NameOrType + ".log");
            if ((this.Item == null) || (this.Context == null))
            {
                return this.Execute(processInfo,
                                    item.Project.Name,
                                    item.NameOrType,
                                    outputFile);
            }

            Assert.AreEqual(this.FileName, processInfo.FileName);
            var actual = processInfo.Arguments == null ? null : processInfo.Arguments.ToString();
            Assert.AreEqual(this.Arguments, actual);
            Assert.AreEqual(this.WorkingDirectory, processInfo.WorkingDirectory);
            Assert.AreSame(this.Item, item);
            Assert.AreEqual(this.Context, context);

            var fileSystemMock = new Mock<IFileSystem>();
            fileSystemMock.Setup(fs => fs.OpenFileForRead(outputFile)).Returns(new MemoryStream());
            var result = new ProcessResult(
                fileSystemMock.Object,
                outputFile,
                this.ExitCode,
                this.TimedOut,
                this.Failed);
            return result;
        }
Exemplo n.º 3
0
 private static void SetDependentUpon(ProjectItem item, string value)
 {
     if (Helpers.ProjectItemContainsProperty(item, "DependentUpon"))
       {
     item.Properties.Item("DependentUpon").Value = value;
       }
 }
Exemplo n.º 4
0
        public static void CreateNewProcessOverview(string ProcessName, ProjectItem processFile, ProjectItem diagramFile)
        {
            var store = new Store(typeof(CloudCoreArchitectProcessOverviewDomainModel));
            var partition = new Partition(store);
            var result = new SerializationResult();

            using (Transaction t = store.TransactionManager.BeginTransaction("create new process overview model"))
            {
                try
                {
                    var processOverviewSerializationHelper = CloudCoreArchitectProcessOverviewSerializationHelper.Instance;
                    Architect.ProcessOverview.Process process = processOverviewSerializationHelper.CreateModelHelper(partition);

                    SetProcessOverviewProperties(ProcessName, process);

                    var diagram = processOverviewSerializationHelper.CreateDiagramHelper(partition, process);

                    processOverviewSerializationHelper.SaveModelAndDiagram(result, process, processFile.FileNames[0], diagram, diagramFile.FileNames[0]);

                    AddAssemblyReference(ProcessName, process);

                    t.Commit();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }
Exemplo n.º 5
0
 protected override void VisitClass(CodeClass codeClass)
 {
     if (codeClass.FullName == _classFullName)
     {
         _result = codeClass.ProjectItem;
     }
 }
		public static bool VerifyConfiguration(ProjectItem projectItem)
		{
			var configProjectItem = SearchService.FindConfigFromModule(projectItem);
			if (configProjectItem == null)
			{
				throw new Exception($"Configuration file not found for module {projectItem.Name}");
			}
			string configText = configProjectItem.ReadAllText();

			var moduleText = projectItem.ReadAllText();
			var serviceNames =
				moduleText.Matches(@".GetObject\<(?<element>[^\>]+)\>")
					.Union(moduleText.Matches(@".GetRuntimeObject\<(?<element>[^\>]+)\>"))
					.Union(moduleText.Matches(@".RegisterInstance\<(?<element>[^\>]+)\>"));

			foreach (var serviceName in serviceNames)
			{
				var fullName = FindServiceFullName(serviceName);

				if (!configText.Contains(fullName))
				{
					throw new Exception($"{fullName} not found in the configuration file. Model: {projectItem.Name}");
				}
			}

			return false;
		}
        public static void RemoveSubItemsAndAssociatedFiles(ProjectItem parentItem)
        {
            if (parentItem == null) return;

            var projectItems = parentItem.ProjectItems.Cast<ProjectItem>();
            RemoveSubItemsAndAssociatedFiles(projectItems);
        }
        /// <summary>
        /// Creates a new instance of <see cref="GenerateAssemblersParams"/>.
        /// </summary>
        /// <param name="targetProject">Project where the Assemblers are going to be generated.</param>
        /// <param name="targetProjectFolder">Project folder where Assemblers are going to be generated. 
        /// Null value indicates to generate at project level.</param>
        /// <param name="sourceFileHeaderComment">Source File Header Comment (optional).</param>
        /// <param name="useProjectDefaultNamespace">Indicates if Target Project default namespace is going to be used.</param>
        /// <param name="sourceNamespace">Namespace used for the Assemblers.</param>
        /// <param name="classIdentifierUse">Indicates use of identifier in class names.</param>
        /// <param name="classIdentifierWord">Identifier to use in class names.</param>
        /// <param name="sourceFileGenerationType">Specifies the Source File Generation Type desired.</param>
        /// <param name="sourceFileName">Source File Name to use if the Source File Generation Type is OneSourceFile.</param>
        /// <param name="isServiceReady">Specifies if the DTOs are Service-Ready (this means if they can be serialized or not).</param>
        /// <param name="dtosNamespace">DTO's namespace.</param>
        /// <param name="dtosTargetProject">DTO's target Project.</param>
        /// <param name="edmxProjectItem">EDMX ProjectItem.</param>
        public GenerateAssemblersParams(Project targetProject, ProjectItem targetProjectFolder, 
            string sourceFileHeaderComment, bool useProjectDefaultNamespace, string sourceNamespace, 
            ClassIdentifierUse classIdentifierUse, string classIdentifierWord,
            SourceFileGenerationType sourceFileGenerationType, string sourceFileName, bool isServiceReady, 
            string dtosNamespace, Project dtosTargetProject, ProjectItem edmxProjectItem)
        {
            this.TargetProject = targetProject;
            this.TargetProjectFolder = targetProjectFolder;

            // Indicate target type
            this.TargetType = (this.TargetProjectFolder == null ? TargetType.Project : TargetType.ProjectFolder);

            this.SourceFileHeaderComment = sourceFileHeaderComment;
            this.UseProjectDefaultNamespace = useProjectDefaultNamespace;
            this.SourceNamespace = sourceNamespace;

            this.ClassIdentifierUse = classIdentifierUse;
            this.ClassIdentifierWord = classIdentifierWord;

            if (this.ClassIdentifierUse == ClassIdentifierUse.None)
            {
                this.ClassIdentifierWord = string.Empty;
            }

            this.SourceFileGenerationType = sourceFileGenerationType;
            this.SourceFileName = sourceFileName;
            this.IsServiceReady = isServiceReady;
            this.DTOsNamespace = dtosNamespace;
            this.DTOsTargetProject = dtosTargetProject;
            this.EDMXProject = edmxProjectItem.ContainingProject;

            this.EntitiesNamespace = EdmxHelper.GetEntitiesNamespace(edmxProjectItem);
        }
 public static FileCodeModel CreateFileCodeModel(DTE dte, ProjectItem item, CodeDomProvider provider, string fileName)
 {
     if (null == item) {
         throw new ArgumentNullException("item");
     }
     return new CodeDomFileCodeModel(dte, item, provider, fileName);
 }
        public override NameValueItem[] GetNameValueItems(XmlNode node, XmlDocument resdoc, ProjectItem item)
        {
            try
            {
                List<NameValueItem> nvitems = new List<NameValueItem>();
                foreach (XmlNode lobInstance in GetChildsOfType(GetFirstChildOfType(node.ParentNode.ParentNode, "LobSystemInstances"), "LobSystemInstance"))
                {
                    //we have the Entity in our hand
                    string entityName = node.Attributes["Name"].Value;
                    string entityValue = node.Attributes["Name"].Value;
                    string entityGroup = lobInstance.Attributes["Name"].Value; //LobSystemInstance
                    string entityDescription = node.Attributes["Namespace"].Value; //LobSystemInstance

                    NameValueItem nvitem = new NameValueItem();
                    nvitem.ItemType = "BCSEntity";
                    nvitem.Name = entityName;
                    nvitem.Value = entityValue;
                    nvitem.Group = entityGroup;
                    nvitem.Description = entityDescription;

                    nvitems.Add(nvitem);
                }

                return nvitems.ToArray();
            }
            catch
            {

            }
            return new NameValueItem[0];
        }
 private bool ContainsDeployableItem(ProjectItem pitem)
 {
     if (pitem != null && pitem.ProjectItems != null)
     {
         foreach (ProjectItem childItem in pitem.ProjectItems)
         {
             if (childItem.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFile)
             {
                 //ok, is file
                 if (ItemIsDeployable(childItem))
                 {
                     return true;
                 }
             }
             else
             {
                 if (ContainsDeployableItem(childItem))
                 {
                     return true;
                 }
             }
         }
     }
     return false;
 }
Exemplo n.º 12
0
 public IEnumerable<IStepDefinitionBinding> GetBindingsFromProjectItem(ProjectItem projectItem, out List<ProjectItem> relatedProjectItems)
 {
     var bindingProcessor = new IdeBindingSourceProcessor(tracer);
     relatedProjectItems = new List<ProjectItem>();
     ProcessBindingsFromProjectItem(projectItem, bindingProcessor, relatedProjectItems);
     return bindingProcessor.ReadStepDefinitionBindings();
 }
Exemplo n.º 13
0
        public bool RunFeatures(ProjectItem projectItem, bool debug)
        {
            if (IsAllowDebugGeneratedFilesSet(projectItem))
                return runnerGateway_CodeBehind.RunFeatures(projectItem, debug);

            return runnerGateway_TestWindowInvoke.RunFeatures(projectItem, debug);
        }
		bool IgnoreChildProjectItem (ProjectItem item)
		{
			if (item != null) {
				return SeenChildProjectItemBefore (item);
			}
			return true;
		}
		public ProjectItemRelationship (ProjectItem parentProjectItem, MD.ProjectItem msbuildProjectItem)
		{
			this.ParentProjectItem = parentProjectItem;
			this.MSBuildProjectItem = msbuildProjectItem;
			this.Project = (Project)parentProjectItem.ContainingProject;
			GetRelationship ();
		}
		public override void FixtureSetUp()
		{
			base.FixtureSetUp();
			project = WebReferenceTestHelper.CreateTestProject("C#");
			WebReferencesProjectItem item = new WebReferencesProjectItem(project);
			item.Include = "Web References\\";
			ProjectService.AddProjectItem(project, item);

			protocol = new DiscoveryClientProtocol();
			DiscoveryDocumentReference discoveryRef = new DiscoveryDocumentReference();
			discoveryRef.Url = updateFromUrl;
			protocol.References.Add(discoveryRef);

			ContractReference contractRef = new ContractReference();
			contractRef.Url = "http://localhost/test.asmx?wsdl";
			contractRef.ClientProtocol = new DiscoveryClientProtocol();
			ServiceDescription desc = new ServiceDescription();
			contractRef.ClientProtocol.Documents.Add(contractRef.Url, desc);
			protocol.References.Add(contractRef);

			WebReferenceTestHelper.InitializeProjectBindings();

			webReference = new Gui.WebReference(project, updateFromUrl, name, proxyNamespace, protocol);
			webReferencesProjectItem = WebReferenceTestHelper.GetProjectItem(webReference.Items, "Web References\\", ItemType.WebReferences);
		}
        /// <summary>
        /// Loads XML from the .config file, manipulates it to possibly add an "defaultConnectionFactory" entry
        /// and then attempts to save the file.
        /// </summary>
        /// <remarks>
        /// If the file cannot be saved then it is not saved and an exception is thrown. Under normal use this should not happen
        /// because NuGet will have ensured that the file is writable. It would be possible to try to do things like try check out
        /// the file from source control, but it doesn't seem like this is valuable enough to implement given it will not normally be used.
        /// </remarks>
        public virtual void ProcessConfigFile(ProjectItem configItem, IEnumerable<Func<XDocument, bool>> manipulators)
        {
            Contract.Requires(configItem != null);

            var fileName = configItem.FileNames[0];
            var config = XDocument.Load(fileName);

            var fileModified = false;
            foreach (var manipulator in manipulators)
            {
                fileModified = manipulator(config) || fileModified;
            }

            if (fileModified)
            {
                try
                {
                    config.Save(fileName);
                }
                catch (Exception ex)
                {
                    throw new IOException(Strings.SaveConnectionFactoryInConfigFailed(fileName), ex);
                }
            }
        }
Exemplo n.º 18
0
        public void Fill(SolutionBrowserForm parent, string projectType, string objectName,
            ProjectItem defaultPath = null)
        {
            ObjectName.Text = objectName;
            _parent = parent;
            _defaultPath = defaultPath;

            var enumerator = new ProjectEnumerator();
            foreach (var project in enumerator.Get(projectType))
            {
                var newNode = new TreeViewItem();
                newNode.Header = project.Name;
                newNode.Tag = project;

                for (var i = 1; i <= project.ProjectItems.Count; i++)
                {
                    var expandParent = false;
                    var node = AddChildren(project.ProjectItems.Item(i), out expandParent);

                    if (node != null)
                    {
                        newNode.Items.Add(node);
                        if (expandParent)
                        {
                            newNode.IsExpanded = true;
                            node.IsExpanded = true;
                        }
                    }
                }

                Tree.Items.Add(newNode);
            }
        }
Exemplo n.º 19
0
 public static Microsoft.AnalysisServices.BackEnd.DataModelingSandbox GetTabularSandboxFromProjectItem(ProjectItem projectItem, bool openIfNotOpen)
 {
     Microsoft.VisualStudio.Project.Automation.OAFileItem project = projectItem as Microsoft.VisualStudio.Project.Automation.OAFileItem;
     Microsoft.AnalysisServices.VSHost.VSHostManager host = GetVSHostManager(project, openIfNotOpen);
     if (host == null) return null;
     return host.Sandbox;
 }
Exemplo n.º 20
0
        public DocumentEventArgs(string documentFullPath, ProjectItem projectItem)
        {
            this.DocumentFullPath = documentFullPath;
            this.DocumentFileName = Path.GetFileName(documentFullPath);

            this.ProjectItem = projectItem;
        }
 public bool RunScenario(ProjectItem projectItem, IScenarioBlock currentScenario, ScenarioOutlineExamplesRow examplesRow, IGherkinFileScope fileScope, bool debug)
 {
     var line = currentScenario.KeywordLine;
     if (examplesRow != null && examplesRow.BlockRelativeLine >= 0)
         line += examplesRow.BlockRelativeLine;
     return RunInCurrentContext(VsxHelper.GetFileName(projectItem), debug, line);
 }
Exemplo n.º 22
0
        public SProjectItem(ProjectItem item)
        {
            this.Name = item.Name;

            foreach(var c in item.Children)
                this.Children.Add(SProjectItem.Build(c));
        }
Exemplo n.º 23
0
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = db.UserModels
                         .Include("UserProjectRoles")
                         .Include("UserProjectRoles.Role")
                         .Where(m => m.Id == id).ToList().First();

            var userProjectsList = user.UserProjectRoles.ToList();
            var projectList = db.Projects.ToList();

            var viewmodel = new UserViewModel();
            viewmodel.Id = user.Id;
            viewmodel.Email = user.Email;
            viewmodel.FirstName = user.FirstName;
            viewmodel.LastName = user.LastName;
            viewmodel.IsAdmin = user.Admin;

            foreach (var item in projectList)
            {
                var toAdd = new ProjectItem();
                toAdd.ProjectId = item.Id;
                toAdd.ProjectName = item.Name;
                toAdd.IsManager = userProjectsList.Where(m => m.ProjectId == item.Id && m.Role.Role1 == "Manager").ToList().Count > 0;
                toAdd.IsDeveloper = userProjectsList.Where(m => m.ProjectId == item.Id && m.Role.Role1 == "Developer").ToList().Count > 0;
                toAdd.IsSubmitter = userProjectsList.Where(m => m.ProjectId == item.Id && m.Role.Role1 == "Submitter").ToList().Count > 0;
                viewmodel.ProjectItems.Add(toAdd);
            }

            return View(viewmodel);
        }
        internal static IEnumerable<IntellisenseObject> ProcessFile(ProjectItem item, HashSet<CodeClass> underProcess = null)
        {
            if (item.FileCodeModel == null)
                return null;

            List<IntellisenseObject> list = new List<IntellisenseObject>();

            if (underProcess == null)
                underProcess = new HashSet<CodeClass>();

            foreach (CodeElement element in item.FileCodeModel.CodeElements)
            {
                if (element.Kind == vsCMElement.vsCMElementNamespace)
                {
                    CodeNamespace cn = (CodeNamespace)element;

                    foreach (CodeElement member in cn.Members)
                    {
                        if (ShouldProcess(member))
                            ProcessElement(member, list, underProcess);
                    }
                }
                else if (ShouldProcess(element))
                    ProcessElement(element, list, underProcess);
            }

            return new HashSet<IntellisenseObject>(list);
        }
Exemplo n.º 25
0
        internal VSProjectItemManager(DTE2 dte, ProjectItem projectItem, string fileNamePrefix)
        {
            this.dte = dte;
            this.projectItem = projectItem;

            this.filesAdded = new Dictionary<string, object>();
            this.filesCreated = new List<string>();

            if (this.projectItem != null)
            {
                if (string.IsNullOrEmpty(fileNamePrefix))
                {
                    fileNamePrefix = this.GetFileNamePrefix(projectItem.Name);
                }

                if (projectItem.FileCount > 0)
                {
                    try
                    {
                        this.fullFileNamePrefix = Path.GetDirectoryName(projectItem.get_FileNames(0)) + @"\" + fileNamePrefix;
                    }
                    catch (System.ArgumentException)
                    {
                        //vs.Php raise exception
                    }

                }
            }
        }
        private void AddCustomToolItemBeforeQueryStatus(object sender, EventArgs e)
        {
            OleMenuCommand button = (OleMenuCommand) sender;
            button.Visible = false;

            UIHierarchyItem uiItem = GetSelectedItem();

            if (uiItem == null)
                return;

            _item = uiItem.Object as ProjectItem;
            if (_item == null)
                return;

            if (_item.ContainingProject.Kind != PrjKind.prjKindCSharpProject && _item.ContainingProject.Kind != PrjKind.prjKindVBProject)
                return;

            string fullPath = _item.Properties.Item("FullPath").Value.ToString();
            string ext = Path.GetExtension(fullPath);

            if (!ext.Equals(".vsct", StringComparison.OrdinalIgnoreCase))
                return;

            button.Checked = _item.Properties.Item("CustomTool").Value.ToString() == CUSTOM_TOOL_NAME;
            button.Visible = true;
        }
		public static void InternalExecute(ProjectItem projectItem)
		{
			var ctors = new List<CodeFunction>();

			foreach (CodeFunction constructor in projectItem.FindContructors().Where(m => m.Parameters.Count > 0))
			{
				var codeElement = constructor.As<CodeElement>();
				string ctorText = codeElement.InnerText();
				var editPoint = codeElement.AtTheFirstLineAfterTheOpeningBrakect();

				bool lineAdded = false;
				foreach (var param in constructor.Parameters().Reverse())
				{
					if (param.Type.CodeType.Kind != vsCMElement.vsCMElementStruct && !ctorText.Contains($"ArgumentNullException(\"{param.Name}\")"))
					{
						lineAdded = true;
						projectItem.AddLine(editPoint, param.Name.ToCtorNullCheck());
					}
				}

				if (lineAdded)
				{
					ctors.Add(constructor);
				}
			}

			if (ctors.Any())
			{
				if (!projectItem.Contains("using System;"))
				{
					projectItem.AddLine(projectItem.FindNameSpace().As<CodeElement>().AtTheFirstLineAfterTheOpeningBrakect(), "using System;");
				}
			}

			foreach (CodeFunction constructor in projectItem.FindContructors().Where(m => m.Parameters.Count > 0))
			{
				if (string.IsNullOrWhiteSpace(constructor.DocComment))
				{
					AddCommentsToCodeElements.AddDocCommentToCtor(constructor);
				}

				var docComment = constructor.DocComment;
				var codeElement = constructor.As<CodeElement>();
				if ((codeElement.Contains("throw new ArgumentNullException") || codeElement.Contains("throw new System.ArgumentNullException"))
					&& (!docComment.Contains(exceptionMessage1) && !docComment.Contains(exceptionMessage2)))
				{
					codeElement.AppendToDocComment(exceptionMessage1);
				}
			}

			if (ctors.Any())
			{
				var dte = (DTE)Package.GetGlobalService(typeof(SDTE));
				try
				{
					dte.ExecuteCommand("Edit.FormatDocument");
				}
				catch { }
			}
		}
Exemplo n.º 28
0
        private CodeDomCodeNamespace vsTopNamespace; // top-level CodeModel namespace

        #endregion Fields

        #region Constructors

        public CodeDomFileCodeModel(DTE dte, ProjectItem parent, CodeDomProvider provider, string filename)
            : base(dte, filename)
        {
            this.parent = parent;
            this.provider = provider as IMergableProvider;
            if (provider == null) throw new ArgumentException("provider must implement IMergeableProvider interface");
        }
Exemplo n.º 29
0
        public static IEnumerable<ProjectItem> GetSelfAndChildProjectItems(ProjectItem projectItem)
        {
            yield return projectItem;
            for (int i = 1; i <= projectItem.ProjectItems.Count; i++)
            {
                ProjectItem item = null;
                try
                {
                    item = projectItem.ProjectItems.Item(i);
                }
                catch (Exception ex)
                {
                    // sometimes we get System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) 
                    // when we open some file in the text editor
                    LogService.LogError(new Exception("Cannot evaluate items in the project!", ex));
                }

                if (item != null)
                {
                    foreach (var childItem in GetSelfAndChildProjectItems(item))
                    {
                        yield return childItem;
                    }
                }
            }
        }
Exemplo n.º 30
0
        private static IEnumerable<string> GetUnsavedModifiedProjectItems(ProjectItem projectItem)
        {
            if ((projectItem.ProjectItems != null && projectItem.ProjectItems.Count == 0) && projectItem.SubProject == null)
            {
                if (!projectItem.Saved)
                    yield return projectItem.Name;
            }

            var projectItems = projectItem.ProjectItems == null ? new List<ProjectItem>() : projectItem.ProjectItems.OfType<ProjectItem>().ToList();

            if (projectItem.SubProject != null)
            {
                if (!projectItem.SubProject.Saved)
                    yield return projectItem.SubProject.Name;

                foreach (var subProjectProjectItem in projectItem.SubProject.ProjectItems.OfType<ProjectItem>().SelectMany(GetUnsavedModifiedProjectItems))
                {
                    yield return subProjectProjectItem;
                }
            }

            foreach (var pi in projectItems.Where(pi => !pi.Saved))
            {
                yield return pi.Name;
            }
        }
Exemplo n.º 31
0
        private void SetIconIndexes(ProjectItem item, TreeNode node)
        {
            switch (item.Kind)
            {
            case Constants.vsProjectItemKindPhysicalFolder:
                // UNDONE: icon resources could be pulled from VS.
                if (item.Name == "Configuration" || item.Name == "Properties")
                {
                    node.ImageIndex         = 34;
                    node.SelectedImageIndex = 2;
                }
                else if (item.Name == "Web References")
                {
                    node.ImageIndex         = 37;
                    node.SelectedImageIndex = 2;
                }
                else if (HasProperty(item.Properties, "WebReference"))
                {
                    node.ImageIndex         = 36;
                    node.SelectedImageIndex = 36;
                }
                else
                {
                    node.ImageIndex         = 3;
                    node.SelectedImageIndex = 4;
                }
                break;

            case Constants.vsProjectItemKindPhysicalFile:
                try
                {
                    // Try to get the dependent property.
                    if (item.Properties.Item("IsDependentFile").Value.ToString() == Boolean.TrueString)
                    {
                        node.ImageIndex         = 35;
                        node.SelectedImageIndex = 35;
                        break;
                    }
                }
                catch { }
                switch (Path.GetExtension(item.get_FileNames(1)))
                {
                case ".ascx":
                    node.ImageIndex         = 5;
                    node.SelectedImageIndex = 5;
                    break;

                case ".asmx":
                    node.ImageIndex         = 6;
                    node.SelectedImageIndex = 6;
                    break;

                case ".aspx":
                    node.ImageIndex         = 7;
                    node.SelectedImageIndex = 7;
                    break;

                case ".bmp":
                case ".png":
                case ".gif":
                case ".jpg":
                    node.ImageIndex         = 8;
                    node.SelectedImageIndex = 8;
                    break;

                case ".config":
                    node.ImageIndex         = 9;
                    node.SelectedImageIndex = 9;
                    break;

                case ".cs":
                    node.ImageIndex         = 11;
                    node.SelectedImageIndex = 11;
                    break;

                case ".disco":
                    node.ImageIndex         = 14;
                    node.SelectedImageIndex = 14;
                    break;

                case ".html":
                case ".htm":
                    node.ImageIndex         = 15;
                    node.SelectedImageIndex = 15;
                    break;

                case ".ico":
                    node.ImageIndex         = 16;
                    node.SelectedImageIndex = 16;
                    break;

                case ".js":
                    node.ImageIndex         = 18;
                    node.SelectedImageIndex = 18;
                    break;

                case ".resx":
                    node.ImageIndex         = 21;
                    node.SelectedImageIndex = 21;
                    break;

                case ".wsdl":
                    node.ImageIndex         = 23;
                    node.SelectedImageIndex = 23;
                    break;

                case ".settings":
                    node.ImageIndex         = 24;
                    node.SelectedImageIndex = 24;
                    break;

                case ".css":
                    node.ImageIndex         = 25;
                    node.SelectedImageIndex = 25;
                    break;

                case ".txt":
                    node.ImageIndex         = 26;
                    node.SelectedImageIndex = 26;
                    break;

                case ".vbs":
                    node.ImageIndex         = 28;
                    node.SelectedImageIndex = 28;
                    break;

                case ".wsf":
                    node.ImageIndex         = 30;
                    node.SelectedImageIndex = 30;
                    break;

                case ".xml":
                    node.ImageIndex         = 31;
                    node.SelectedImageIndex = 31;
                    break;

                case ".xsd":
                    node.ImageIndex         = 32;
                    node.SelectedImageIndex = 32;
                    break;

                case ".xsl":
                    node.ImageIndex         = 33;
                    node.SelectedImageIndex = 33;
                    break;

                default:
                    node.ImageIndex         = 17;
                    node.SelectedImageIndex = 17;
                    break;
                }
                break;

            default:
                node.ImageIndex         = 11;
                node.SelectedImageIndex = 11;
                break;
            }
        }
Exemplo n.º 32
0
        internal static bool TryGetBufferViaExtensions(
            IServiceProvider serviceProvider, ProjectItem projectItem, string fileContents,
            Lazy <IModelConversionExtension, IEntityDesignerConversionData>[] converters,
            Lazy <IModelTransformExtension>[] serializers, out string documentViaExtensions,
            out List <ExtensionError> errors)
        {
            Debug.Assert(serviceProvider != null, "serviceProvider != null");
            Debug.Assert(projectItem != null, "projectItem != null");
            Debug.Assert(VsUtils.EntityFrameworkSupportedInProject(projectItem.ContainingProject, serviceProvider, false));
            Debug.Assert(serializers != null && converters != null, "extensions must not be null");
            Debug.Assert(serializers.Any() || converters.Any(), "at least one extension expected");

            errors = new List <ExtensionError>();
            documentViaExtensions = "";

            ModelConversionContextImpl conversionContext = null;
            ModelTransformContextImpl  transformContext  = null;

            try
            {
                var targetSchemaVersion =
                    EdmUtils.GetEntityFrameworkVersion(projectItem.ContainingProject, serviceProvider);

                Debug.Assert(targetSchemaVersion != null, "should not get here for a Misc project");

                // get the extension of the file being loaded (might not be EDMX); this API will include the preceding "."
                var       filePath         = projectItem.get_FileNames(1);
                var       fileExtension    = Path.GetExtension(filePath);
                XDocument originalDocument = null;

                // see if we are loading an EDMX file or not, and if we have any converters
                if (!string.Equals(
                        fileExtension, EntityDesignArtifact.ExtensionEdmx,
                        StringComparison.OrdinalIgnoreCase))
                {
                    conversionContext = new ModelConversionContextImpl(
                        projectItem.ContainingProject, projectItem, new FileInfo(filePath),
                        targetSchemaVersion, fileContents);

                    // we aren't loading an EDMX file, so call the extensions who can process this file extension
                    // when this finishes, then output should be a valid EDMX document
                    VSArtifact.DispatchToConversionExtensions(converters, fileExtension, conversionContext, true);

                    // we are done with the non-EDMX extensions so CurrentDocument will be a valid EDMX document
                    // create the serialization context for further extensions to act on
                    transformContext = new ModelTransformContextImpl(
                        projectItem, targetSchemaVersion, conversionContext.CurrentDocument);
                }
                else
                {
                    // we are loading an EDMX file, we can parse file contents into an XDocument
                    try
                    {
                        originalDocument = XDocument.Parse(fileContents, LoadOptions.PreserveWhitespace);
                        transformContext = new ModelTransformContextImpl(
                            projectItem, targetSchemaVersion, originalDocument);
                    }
                    catch (XmlException)
                    {
                        // If there's an error here, don't do anything. We will want to gracefully step out of the extension loading
                        // since the designer itself won't load.
                    }
                }

                if (transformContext != null &&
                    originalDocument != null)
                {
                    // now dispatch to those that want to work on EDMX files
                    VSArtifact.DispatchToSerializationExtensions(serializers, transformContext, true);

                    // TODO: this does not seem to be correct if severity is Message or Warning
                    if (transformContext.Errors.Count == 0)
                    {
                        // see if any extension changed things. Note that we need to compare the serialization of
                        // the XDocuments together since the original buffer may have different whitespace after creating the XDocument.
                        // TODO: Why not use XNode.DeepEquals()?
                        string newBufferContents;
                        using (var currentDocWriter = new Utf8StringWriter())
                        {
                            transformContext.CurrentDocument.Save(currentDocWriter, SaveOptions.None);
                            newBufferContents = currentDocWriter.ToString();
                        }

                        string originalBufferContents;
                        using (var originalDocWriter = new Utf8StringWriter())
                        {
                            originalDocument.Save(originalDocWriter, SaveOptions.None);
                            originalBufferContents = originalDocWriter.ToString();
                        }

                        if (!string.Equals(originalBufferContents, newBufferContents, StringComparison.Ordinal))
                        {
                            documentViaExtensions = newBufferContents;
                            return(true);
                        }
                    }
                    else
                    {
                        errors.AddRange(transformContext.Errors);
                        return(false);
                    }
                }
            }
            finally
            {
                var errorList = ErrorListHelper.GetExtensionErrorList(serviceProvider);
                errorList.Clear();

                // log any errors
                if (conversionContext != null &&
                    conversionContext.Errors.Count > 0)
                {
                    ErrorListHelper.LogExtensionErrors(conversionContext.Errors, projectItem);
                }

                if (transformContext != null &&
                    transformContext.Errors.Count > 0)
                {
                    ErrorListHelper.LogExtensionErrors(transformContext.Errors, projectItem);
                }
            }

            return(false);
        }
Exemplo n.º 33
0
        /// <summary>
        /// Adds the plugins.
        /// </summary>
        /// <param name="visualStudioService">The visual studio service.</param>
        /// <param name="plugins">The plugins.</param>
        /// <param name="viewModelName">Name of the view model.</param>
        /// <param name="codeSnippetsPath">The code snippets path.</param>
        public void AddPlugins(
            IVisualStudioService visualStudioService,
            List <Plugin> plugins,
            string viewModelName,
            string codeSnippetsPath)
        {
            Project coreProject = visualStudioService.CoreProject;

            this.AddProjectPlugins(coreProject, plugins, "Core", "Core");
            this.AddProjectPlugins(visualStudioService.DroidProject, plugins, "Droid", "Droid");
            this.AddProjectPlugins(visualStudioService.iOSProject, plugins, "iOS", "Touch");
            this.AddProjectPlugins(visualStudioService.WindowsPhoneProject, plugins, "WindowsPhone", "WindowsPhone");
            this.AddProjectPlugins(visualStudioService.WindowsStoreProject, plugins, "WindowsStore", "WindowsStore");
            this.AddProjectPlugins(visualStudioService.WpfProject, plugins, "Wpf", "Wpf");

            if (string.IsNullOrEmpty(viewModelName) == false)
            {
                ProjectItem projectItem = coreProject.GetProjectItem(viewModelName);

                if (projectItem != null)
                {
                    foreach (Plugin plugin in plugins)
                    {
                        string snippetPath = string.Format(@"{0}\Plugins.{1}.txt", codeSnippetsPath, plugin.FriendlyName);

                        if (File.Exists(snippetPath))
                        {
                            FileInfo fileInfo = new FileInfo(snippetPath);

                            //// only do if the snippet contains some text :-)
                            if (fileInfo.Length > 0)
                            {
                                string assemblyName = Path.GetFileNameWithoutExtension(plugin.FileName);

                                projectItem.AddUsingStatement("Cirrious.CrossCore");

                                projectItem.AddUsingStatement(assemblyName);

                                projectItem.InsertMethod(snippetPath);

                                //// tidy up the using statements.
                                projectItem.Save();
                                projectItem.MoveUsingStatements();
                                projectItem.Save();
                                projectItem.SortAndRemoveUsingStatements();
                                projectItem.Save();

                                if (projectItem.Document != null)
                                {
                                    projectItem.Document.ActiveWindow.Close();
                                }
                            }
                        }
                    }
                }
            }

            DTE2 dte2 = coreProject.DTE as DTE2;

            dte2.SaveAll();
        }
 // This method is only called for item templates,
 // not for project templates.
 public void ProjectItemFinishedGenerating(ProjectItem projectItem)
 {
 }
 // This method is called before opening any item that
 // has the OpenInEditor attribute.
 public void BeforeOpeningFile(ProjectItem projectItem)
 {
 }
        public void RequestAnalysis(string path, string charset, IEnumerable <SonarLanguage> detectedLanguages, IIssueConsumer issueConsumer, ProjectItem projectItem)
        {
            bool handled = false;

            foreach (var language in detectedLanguages)
            {
                switch (language)
                {
                case SonarLanguage.Javascript:
                    handled = true;
                    daemon.RequestAnalysis(path, charset, "js", null, issueConsumer);
                    break;

                case SonarLanguage.CFamily:
                    handled = true;
                    CFamily.ProcessFile(daemon, issueConsumer, logger, projectItem, path, charset);
                    break;

                default:
                    break;
                }
            }

            if (!handled)
            {
                logger.WriteLine($"Unsupported content type for {path}");
            }
        }
Exemplo n.º 37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="VSMDLuaCodeDomProvider"/> class.
 /// </summary>
 /// <param name="projectItem">ProjectItem instance.</param>
 public VSMDLuaCodeDomProvider(ProjectItem projectItem)
 {
     codeDomProvider = new LuaCodeDomProvider(projectItem);
 }
Exemplo n.º 38
0
 public BindingFileInfo(ProjectItem projectItem)
 {
     ProjectRelativePath = VsxHelper.GetProjectRelativePath(projectItem);
     LastChangeDate      = VsxHelper.GetLastChangeDate(projectItem) ?? DateTime.MinValue;
 }
 public FileModel(SolutionModelBase parent, ProjectItem file)
     : base(parent)
 {
     this.file = file;
 }
 protected override void OnFileBecomesIrrelevant(ProjectItem item, string oldName)
 {
     OnFileOutOfScope(item, GetProjectRelativePathWithFileName(item, oldName));
 }
Exemplo n.º 41
0
 public void TestInitialize()
 {
     TestEnvironment.CommonTestInitialize();
     _projectItem = TestEnvironment.LoadFileIntoProject(@"Data\SortUsingStatements.cs");
 }
Exemplo n.º 42
0
 protected override BindingFileInfo CreateFileInfo(ProjectItem projectItem)
 {
     return(new BindingFileInfo(projectItem));
 }
Exemplo n.º 43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object" /> class.
 /// </summary>
 public AnnotationProjectItem(ProjectItem dteProjectItem) : base(dteProjectItem)
 {
 }
Exemplo n.º 44
0
 public void RequestAnalysis(string path, string charset, IEnumerable <AnalysisLanguage> detectedLanguages, IIssueConsumer issueConsumer, ProjectItem projectItem)
 {
     // May be called on the UI thread -> unhandled exceptions will crash VS
     try
     {
         analyzerController.ExecuteAnalysis(path, charset, detectedLanguages, issueConsumer, projectItem);
     }
     catch (Exception ex) when(!Microsoft.VisualStudio.ErrorHandler.IsCriticalException(ex))
     {
         logger.WriteLine($"Analysis error: {ex.ToString()}");
     }
 }
Exemplo n.º 45
0
        // <summary>
        //     This method will log errors to the "Extension" Multi-doc error list.
        // </summary>
        internal static void LogExtensionErrors(IEnumerable <ExtensionError> errors, ProjectItem projectItem)
        {
            if (null == errors)
            {
                throw new ArgumentNullException("errors");
            }

            if (null == projectItem)
            {
                throw new ArgumentNullException("projectItem");
            }

            if (PackageManager.Package != null)
            {
                var hierarchy = VsUtils.GetVsHierarchy(projectItem.ContainingProject, Services.ServiceProvider);
                var itemId    = VsUtils.GetProjectItemId(hierarchy, projectItem);

                var errorList = GetExtensionErrorList(PackageManager.Package);

                var errorCount = 0;

                foreach (var error in errors)
                {
                    // only display the first 100 errors.  VS gets really slow if you try to display more
                    if (errorCount++ > 99)
                    {
                        break;
                    }

                    var category = TaskErrorCategory.Message;
                    if (error.Severity == ExtensionErrorSeverity.Error)
                    {
                        category = TaskErrorCategory.Error;
                    }
                    else if (error.Severity == ExtensionErrorSeverity.Warning)
                    {
                        category = TaskErrorCategory.Warning;
                    }

                    string filePath         = null;
                    var    fullPathProperty = projectItem.Properties.Item("FullPath");
                    if (fullPathProperty != null)
                    {
                        filePath = fullPathProperty.Value as String;
                    }
                    if (filePath == null)
                    {
                        filePath = projectItem.Name;
                    }

                    var textSpan = new TextSpan();
                    textSpan.iStartLine  = error.Line;
                    textSpan.iStartIndex = error.Column;
                    textSpan.iEndLine    = error.Line;
                    textSpan.iEndIndex   = error.Column;
                    errorList.AddItem(
                        EFModelErrorTaskFactory.CreateErrorTask(
                            filePath, error.Message, textSpan, category, hierarchy, itemId, MARKERTYPE.MARKER_OTHER_ERROR));
                }
            }
        }
Exemplo n.º 46
0
 public void TestInitialize()
 {
     TestEnvironment.CommonTestInitialize();
     _projectItem = TestEnvironment.LoadFileIntoProject(@"Data\SortAtBottom.cs");
 }
Exemplo n.º 47
0
 void IWizard.BeforeOpeningFile(ProjectItem projectItem)
 {
 }
Exemplo n.º 48
0
 // <summary>
 //     Logs SchemaErrors to the a special provider for wizard errors.  We won't ever clear this provider,
 //     because we have no way to get the wizard errors back.  This way, they will persist for the time that
 //     the document is open. This will log errors to the 'Wizard' multi-doc error list.
 // </summary>
 internal static void LogWizardErrors(IEnumerable <EdmSchemaError> errors, ProjectItem projectItem)
 {
     LogWizardErrors(errors, projectItem, MARKERTYPE.MARKER_COMPILE_ERROR);
 }
Exemplo n.º 49
0
 public static IProjectItemAccessor Access(this ProjectItem projectItem)
 {
     return(GetterFactory(projectItem));
 }
Exemplo n.º 50
0
 void IWizard.ProjectItemFinishedGenerating(ProjectItem projectItem)
 {
 }
Exemplo n.º 51
0
 public void ProjectItemFinishedGenerating(ProjectItem projectItem)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 52
0
 public static IProjectItemPredicator Is(this ProjectItem projectItem)
 {
     return(PredicatorFactory(projectItem));
 }
Exemplo n.º 53
0
 public void TestInitialize()
 {
     TestEnvironment.CommonTestInitialize();
     _projectItem = TestEnvironment.LoadFileIntoProject(@"Data\VisualBasic.vb");
 }
Exemplo n.º 54
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private async void Execute(object sender, EventArgs e)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            DTE dte = (DTE)await this.ServiceProvider.GetServiceAsync(typeof(DTE));

            foreach (SelectedItem item in dte.SelectedItems)
            {
                ProjectItem pi       = item.ProjectItem;
                string      tarsPath = null;
                switch (pi.ContainingProject.CodeModel.Language)
                {
                case CodeModelLanguageConstants.vsCMLanguageCSharp:
                    tarsPath = this.tars2csPath;
                    break;

                case CodeModelLanguageConstants.vsCMLanguageVC:
                    break;

                default:
                    break;
                }
                if (tarsPath != null)
                {
                    string srcFile = pi.FileNames[0];
                    string tmpFile = Path.GetTempPath() + pi.GetHashCode() + ".tars";
                    File.Copy(srcFile, tmpFile, true);
                    string targetPath = srcFile + "_";
                    string path       = Path.GetTempPath() + pi.GetHashCode();
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path, true);
                    }
                    Directory.CreateDirectory(path);
                    ProjectItems pis = pi.Collection;
                    try
                    {
                        pis.Item(pi.Name + "_").Delete();
                    }
                    catch
                    {
                    }
                    if (Directory.Exists(targetPath))
                    {
                        Directory.Delete(targetPath, true);
                    }
                    pi = pis.AddFolder(pi.Name + "_");
                    ProcessStartInfo psi = new ProcessStartInfo(tarsPath, $"--base-package= \"{tmpFile}\"");
                    psi.UseShellExecute       = false;
                    psi.CreateNoWindow        = true;
                    psi.WorkingDirectory      = path;
                    psi.RedirectStandardError = true;
                    using (Process p = Process.Start(psi))
                    {
                        if (p?.WaitForExit(10 * 1000) == true)
                        {
                            IVsOutputWindowPane outputPane = (IVsOutputWindowPane)await this.ServiceProvider.GetServiceAsync(typeof(SVsGeneralOutputWindowPane));

                            outputPane.OutputString(p.StandardError.ReadToEnd());
                            //string targetPath = Path.GetDirectoryName(srcFile);
                            this.AddLinks(pi, path, targetPath);
                        }
                    }
                    Directory.Delete(path, true);
                    File.Delete(tmpFile);
                }
            }
        }
Exemplo n.º 55
0
 public void BeforeOpeningFile(ProjectItem projectItem)
 {
     // Method intentionally left empty.
 }
Exemplo n.º 56
0
 public void BeforeOpeningFile(ProjectItem projectItem)
 {
     throw new NotImplementedException();
 }
        public void CheckGenerateTypeScriptOutput()
        {
            // get the DTE reference...
            DTE dte = SolutionWorker.GetVisualStudioInstanceOfTypeScriptDefinitionGenerator();

            var worker = new SolutionWorker();

            worker.ExamineSolution(dte.Solution);

            var testFiles = new System.Collections.Generic.Dictionary <string, string>
            {
                {
                    "SomeEnum.cs",
                    "// ------------------------------------------------------------------------------\n" +
                    "// <auto-generated>\n" +
                    "//     This file was generated by TypeScript Definition Generator v2.2.0.0\n" +
                    "// </auto-generated>\n" +
                    "// ------------------------------------------------------------------------------\n" +
                    "export enum SomeEnum {\n" +
                    "  This,\n" +
                    "  That,\n" +
                    "}\n"
                },
                {
                    "SecondClass.cs",
                    "// ------------------------------------------------------------------------------\n" +
                    "// <auto-generated>\n" +
                    "//     This file was generated by TypeScript Definition Generator v2.2.0.0\n" +
                    "// </auto-generated>\n" +
                    "// ------------------------------------------------------------------------------\n" +
                    "import { SomeClass } from \"./SomeClass.generated\";\n" +
                    "import { SomeSomeClass } from \"./SomeSomeClass.generated\";\n" +
                    "export interface SecondClass {\n" +
                    "  myProperty: number;\n" +
                    "  complex1: SomeClass;\n" +
                    "  complex2: SomeSomeClass;\n" +
                    "}\n"
                },
                {
                    "SomeClass.cs",
                    "// ------------------------------------------------------------------------------\n" +
                    "// <auto-generated>\n" +
                    "//     This file was generated by TypeScript Definition Generator v2.2.0.0\n" +
                    "// </auto-generated>\n" +
                    "// ------------------------------------------------------------------------------\n" +
                    "import { SomeEnum } from \"./SomeEnum.generated\";\n" +
                    "export interface SomeClass {\n" +
                    "  inc1: number;\n" +
                    "  some: SomeEnum;\n" +
                    "}\n"
                },
                {
                    "SomeSomeClass.cs",
                    "// ------------------------------------------------------------------------------\n" +
                    "// <auto-generated>\n" +
                    "//     This file was generated by TypeScript Definition Generator v2.2.0.0\n" +
                    "// </auto-generated>\n" +
                    "// ------------------------------------------------------------------------------\n" +
                    "import { SomeClass } from \"./SomeClass.generated\";\n" +
                    "export interface SomeSomeClass extends SomeClass {\n" +
                    "  inc2: number;\n" +
                    "  inc3: number;\n" +
                    "  inc4: number;\n" +
                    "  inc5: number;\n" +
                    "  inc6: string;\n" +
                    "  inc7: any;\n" +
                    "  inc8: number[];\n" +
                    "  inc9: number[];\n" +
                    "  inc10: number[];\n" +
                    "  inc11: number[];\n" +
                    "  inc12: boolean;\n" +
                    "  inc13: { [index: string]: number };\n" +
                    "  inc14: { [index: string]: number };\n" +
                    "}\n"
                },
                {
                    "ThirdClass.cs",
                    "// ------------------------------------------------------------------------------\n" +
                    "// <auto-generated>\n" +
                    "//     This file was generated by TypeScript Definition Generator v2.2.0.0\n" +
                    "// </auto-generated>\n" +
                    "// ------------------------------------------------------------------------------\n" +
                    "import { SomeClass } from \"../SomeClass.generated\";\n" +
                    "import { SomeSomeClass } from \"../SomeSomeClass.generated\";\n" +
                    "export interface ThirdClass {\n" +
                    "  myProperty: number;\n" +
                    "  complex1: SomeClass;\n" +
                    "  complex2: SomeSomeClass;\n" +
                    "}\n"
                }
            };

            foreach (var testFile in testFiles)
            {
                var         testFileName = testFile.Key;
                var         expectedFile = testFile.Value;
                ProjectItem item         = worker.GetProjectItem(dte.Solution, testFileName);

                Assert.NotNull(item, $"Could not find {testFileName}");

                Options.SetOptionsOverrides(new OptionsOverride()
                {
                    CamelCaseEnumerationValues = false,
                    CamelCasePropertyNames     = true,
                    CamelCaseTypeNames         = false,
                    WebEssentials2015          = false,
                    ClassInsteadOfInterface    = false,
                    DeclareModule      = false,
                    DefaultModuleName  = "Server.Dtos",
                    EOLType            = EOLType.LF,
                    IgnoreIntellisense = true,
                    IndentTab          = false,
                    IndentTabSize      = 2,
                    UseNamespace       = true,
                });
                var list           = IntellisenseParser.ProcessFile(item).ToList();
                var sourceItemPath = item.Properties.Item("FullPath").Value as string;
                var tsFile         = IntellisenseWriter.WriteTypeScript(list, sourceItemPath);

                Assert.AreEqual(expectedFile, tsFile);
            }
        }
Exemplo n.º 58
0
 public void ProjectItemFinishedGenerating(ProjectItem projectItem)
 {
     // Method intentionally left empty.
 }
Exemplo n.º 59
0
        private bool SetValue(object currentValue, out object newValue)
        {
            if (currentValue != null)
            {
                newValue = null;
                return(false);
            }

            DTE dte = this.GetService <DTE>(true);

            //first we need the xpath, which is needed by the manifest-recipe
            string manifestXpath          = "";
            string manifestXpathNamespace = "";
            IConfigurationService b       = (IConfigurationService)GetService(typeof(IConfigurationService));

            Microsoft.Practices.RecipeFramework.Configuration.Recipe recipe = b.CurrentRecipe;
            if (recipe.HostData.Any.Attributes["XPath"] != null)
            {
                manifestXpath = recipe.HostData.Any.Attributes["XPath"].Value;
            }
            if (recipe.HostData.Any.Attributes["XPathNamespace"] != null)
            {
                manifestXpathNamespace = recipe.HostData.Any.Attributes["XPathNamespace"].Value;
            }

            //if file is selected we check, if the xpath can be found in this item
            //if folder is selected we search in this folder for the elements.xml which contains the xpath
            if (dte.SelectedItems.Count > 0)
            {
                SelectedItem item         = dte.SelectedItems.Item(1);
                ProjectItem  selectedItem = null;

                if (item is ProjectItem)
                {
                    selectedItem = item as ProjectItem;
                }
                else if (item.ProjectItem is ProjectItem)
                {
                    selectedItem = item.ProjectItem as ProjectItem;
                }

                if (selectedItem != null)
                {
                    if (selectedItem.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFile)
                    {
                        if (selectedItem.Collection.Parent is ProjectItem)
                        {
                            ProjectItem parentItem = selectedItem.Collection.Parent as ProjectItem;
                            newValue = parentItem;
                            return(true);
                        }
                    }
                    else if (selectedItem.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder)
                    {
                        newValue = selectedItem;
                        return(true);
                    }
                }
            }

            newValue = null;
            return(false);
        }
        public void _ShouldWorkProperly()
        {
            //Arrange

            // get the DTE reference...
            DTE dte = SolutionWorker.GetVisualStudioInstanceOfTypeScriptDefinitionGenerator();


            var worker = new SolutionWorker();

            worker.ExamineSolution(dte.Solution);

            ProjectItem item = worker.GetProjectItem(dte.Solution, "Class1.cs");

            if (item == null)
            {
                throw new System.ArgumentNullException(nameof(item), "Class1.cs not found in solution. Close all other instances of Visual Studio!");
            }

            //Act
            Options.SetOptionsOverrides(new OptionsOverride()
            {
                CamelCaseEnumerationValues = false,
                CamelCasePropertyNames     = true,
                CamelCaseTypeNames         = false,

                WebEssentials2015 = false,

                ClassInsteadOfInterface = false,
                DefaultModuleName       = "Server.Dtos",
                UseNamespace            = true,
                DeclareModule           = true,
                IgnoreIntellisense      = true,
            });
            var list           = IntellisenseParser.ProcessFile(item).ToList();
            var sourceItemPath = item.Properties.Item("FullPath").Value as string;
            var tsFile         = IntellisenseWriter.WriteTypeScript(list, sourceItemPath);

            //Assert
            Assert.IsNotNull(list);
            Assert.NotZero(list.Count);
            Assert.AreEqual("TypeScriptDefinitionGenerator.Tests.Class1", list[0].FullName);
            Assert.AreEqual("Class1", list[0].Name);
            Assert.AreEqual(5, list[0].Properties.Count);

            Assert.AreEqual("IntEnumField", list[0].Properties[1].Name);
            Assert.AreEqual("IntEnumField", list[0].Properties[1].NameWithOption);
            Assert.AreEqual(null, list[0].Properties[1].InitExpression);
            Assert.AreEqual(null, list[0].Properties[1].Summary);
            Assert.AreEqual("TypeScriptDefinitionGenerator.Tests.IntEnum", list[0].Properties[1].Type.CodeName);
            Assert.AreNotEqual("any", list[0].Properties[1].Type.TypeScriptName);
            Assert.AreEqual("TypeScriptDefinitionGenerator.Tests.IntEnum", list[0].Properties[1].Type.TypeScriptName);
            Assert.AreNotEqual(null, list[0].Properties[1].Type.ClientSideReferenceName);
            Assert.AreEqual("TypeScriptDefinitionGenerator.Tests.IntEnum", list[0].Properties[1].Type.ClientSideReferenceName);
            Assert.AreEqual(false, list[0].Properties[1].Type.IsArray);
            Assert.AreEqual(false, list[0].Properties[1].Type.IsDictionary);
            Assert.AreEqual(true, list[0].Properties[1].Type.IsKnownType);
            Assert.AreEqual(false, list[0].Properties[1].Type.IsOptional);


            Assert.AreEqual("SomeEnumField", list[0].Properties[3].Name);
            Assert.AreEqual("SomeEnumField", list[0].Properties[3].NameWithOption);
            Assert.AreEqual(null, list[0].Properties[3].InitExpression);
            Assert.AreEqual(null, list[0].Properties[3].Summary);
            Assert.AreEqual("ClassLibrary1.SomeEnum", list[0].Properties[3].Type.CodeName);
            Assert.AreNotEqual("any", list[0].Properties[3].Type.TypeScriptName);
            Assert.AreEqual("ClassLibrary1.SomeEnum", list[0].Properties[3].Type.TypeScriptName);
            Assert.AreNotEqual(null, list[0].Properties[3].Type.ClientSideReferenceName);
            Assert.AreEqual("ClassLibrary1.SomeEnum", list[0].Properties[3].Type.ClientSideReferenceName);
            Assert.AreEqual(false, list[0].Properties[3].Type.IsArray);
            Assert.AreEqual(false, list[0].Properties[3].Type.IsDictionary);
            Assert.AreEqual(true, list[0].Properties[3].Type.IsKnownType);
            Assert.AreEqual(false, list[0].Properties[3].Type.IsOptional);


            Assert.AreEqual("SomeSomeClassField", list[0].Properties[4].Name);
            Assert.AreEqual("SomeSomeClassField", list[0].Properties[4].NameWithOption);
            Assert.AreEqual(null, list[0].Properties[4].InitExpression);
            Assert.AreEqual(null, list[0].Properties[4].Summary);
            Assert.AreEqual("ClassLibrary1.SomeSomeClass", list[0].Properties[4].Type.CodeName);
            Assert.AreNotEqual("any", list[0].Properties[4].Type.TypeScriptName);
            Assert.AreEqual("ClassLibrary1.SomeSomeClass", list[0].Properties[4].Type.TypeScriptName);
            Assert.AreNotEqual(null, list[0].Properties[4].Type.ClientSideReferenceName);
            Assert.AreEqual("ClassLibrary1.SomeSomeClass", list[0].Properties[4].Type.ClientSideReferenceName);
            Assert.AreEqual(false, list[0].Properties[4].Type.IsArray);
            Assert.AreEqual(false, list[0].Properties[4].Type.IsDictionary);
            Assert.AreEqual(true, list[0].Properties[4].Type.IsKnownType);
            Assert.AreEqual(false, list[0].Properties[4].Type.IsOptional);
            Assert.AreEqual(13, list[0].Properties[4].Type.Shape.Count());
            // Inc6
            Assert.AreEqual("System.Guid", list[0].Properties[4].Type.Shape.First(o => o.Name == "Inc6").Type.CodeName);
            Assert.AreNotEqual("any", list[0].Properties[4].Type.Shape.First(o => o.Name == "Inc6").Type.TypeScriptName);
            Assert.AreEqual("string", list[0].Properties[4].Type.Shape.First(o => o.Name == "Inc6").Type.TypeScriptName);
            // Inc13
            Assert.AreEqual("System.Collections.Generic.Dictionary<string, int>", list[0].Properties[4].Type.Shape.First(o => o.Name == "Inc13").Type.CodeName);
            Assert.AreEqual("System.Collections.Generic.Dictionary", list[0].Properties[4].Type.Shape.First(o => o.Name == "Inc13").Type.ClientSideReferenceName);
            Assert.AreEqual(true, list[0].Properties[4].Type.Shape.First(o => o.Name == "Inc13").Type.IsDictionary);
            Assert.AreEqual("{ [index: string]: number }", list[0].Properties[4].Type.Shape.First(o => o.Name == "Inc13").Type.TypeScriptName);
            // Inc14
            Assert.AreEqual("System.Collections.Generic.IDictionary<string, int>", list[0].Properties[4].Type.Shape.First(o => o.Name == "Inc14").Type.CodeName);
            Assert.AreEqual("System.Collections.Generic.IDictionary", list[0].Properties[4].Type.Shape.First(o => o.Name == "Inc14").Type.ClientSideReferenceName);
            Assert.AreEqual(true, list[0].Properties[4].Type.Shape.First(o => o.Name == "Inc14").Type.IsDictionary);
            Assert.AreEqual("{ [index: string]: number }", list[0].Properties[4].Type.Shape.First(o => o.Name == "Inc14").Type.TypeScriptName);
        }