private ViewModel GenerateJsFileFromProjectItem(ProjectItem item, bool fromCodeSnippet)
        {
            var fileExtension = Path.GetExtension(item.GetFullPath());
            var language      = fileExtension.Equals(".cs") ? SupportedLanguage.CSharp : SupportedLanguage.VBNet;

            if (!item.Saved)
            {
                item.Save();
            }

            try
            {
                JsFile jsFile;

                if (fromCodeSnippet)
                {
                    dynamic comObject = item.Document.Selection;
                    jsFile = _codeGenerator.GetJsFileFromCodeSnippet(comObject.Text, language);
                }
                else
                {
                    jsFile = _codeGenerator.GetJsFileFromCodeFile(item.GetFullPath(), language);
                }

                return(ViewModelExtensions.MapViewModelFromJsFile(jsFile));
            }
            catch (Exception)
            {
                _schell.Toast("Error parsing file");
            }

            return(null);
        }
Example #2
0
        /// <summary>
        /// Treats given ProjectItem as a VB code file, using VBCodeExplorer to examine the file. LookInVB method is called as a callback,
        /// given plain methods text.
        /// </summary>
        protected override void ProcessVB(ProjectItem projectItem, Predicate <CodeElement> exploreable, bool verbose)
        {
            if (isInitial || editorInstance.UIControl.sourceFilesThatNeedUpdate.Contains(projectItem.GetFullPath().ToLower()))
            {
                base.ProcessVB(projectItem, exploreable, verbose);
            }
            else
            {
                bool           fileOpened;
                FileCodeModel2 codeModel = projectItem.GetCodeModel(false, false, out fileOpened);

                if (codeModel == null && !RDTManager.IsFileOpen(projectItem.GetFullPath()))
                {
                    editorInstance.UIControl.RegisterAsStaticReferenceSource(projectItem);
                    return;
                }

                if (codeModel == null)
                {
                    if (verbose)
                    {
                        VLOutputWindow.VisualLocalizerPane.WriteLine("\tCannot process {0}, file code model does not exist.", projectItem.Name);
                    }
                    return;
                }
                if (verbose)
                {
                    VLOutputWindow.VisualLocalizerPane.WriteLine("\tProcessing {0}", projectItem.Name);
                }

                currentlyProcessedItem = projectItem;

                try {
                    VBCodeExplorer.Instance.Explore(this, exploreable, codeModel);
                } catch (COMException ex) {
                    if (ex.ErrorCode == -2147483638)
                    {
                        VLOutputWindow.VisualLocalizerPane.WriteLine("\tError occured during processing {0} - the file is not yet compiled.", projectItem.Name);
                    }
                    else
                    {
                        throw;
                    }
                }

                currentlyProcessedItem = null;
            }
            editorInstance.UIControl.sourceFilesThatNeedUpdate.Remove(projectItem.GetFullPath().ToLower());
        }
Example #3
0
        private static void WriteDesigner(this ProjectItem projectItem, CremaDataTable dataTable, bool isPublic)
        {
            var project          = projectItem.ContainingProject;
            var projectPath      = Path.GetDirectoryName(project.GetFullName());
            var designerFileName = Path.Combine(projectPath, projectItem.GetCustomToolOutput());
            var resxFileName     = projectItem.GetFullPath();
            var ss            = StringUtility.SplitPath(Path.GetDirectoryName(projectItem.GetLocalPath()));
            var codeNamespace = $"{project.GetRootNamespace()}.{string.Join(".", ss)}";
            var baseName      = Path.GetFileNameWithoutExtension(projectItem.GetLocalPath());

            using (var sw = new StreamWriter(designerFileName))
            {
                var errors   = null as string[];
                var provider = new CSharpCodeProvider();
                var code     = StronglyTypedResourceBuilder.Create(resxFileName, baseName, codeNamespace, provider, isPublic == false, out errors);
                if (errors.Length > 0)
                {
                    foreach (var error in errors)
                    {
                        Console.WriteLine(error);
                    }
                    return;
                }

                provider.GenerateCodeFromCompileUnit(code, sw, new CodeGeneratorOptions());
                Console.WriteLine(designerFileName);
            }
        }
Example #4
0
        public static void Write(this ProjectItem projectItem, CremaDataTable projectInfoTable)
        {
            if (FindTable(projectItem, projectInfoTable) is CremaDataTable dataTable)
            {
                var cultureInfo = projectItem.GetResourceCulture();
                var valueName   = cultureInfo == null ? "Value" : cultureInfo.Name.Replace('-', '_');
                var path        = projectItem.GetFullPath();
                using (var writer = new ResXResourceWriter(path))
                {
                    foreach (var item in dataTable.Rows)
                    {
                        var name = $"{item["Type"]}" == "None" ? $"{item["Name"]}" : $"{item["Type"]}_{item["Name"]}";
                        var node = new ResXDataNode(name, item[valueName])
                        {
                            Comment = $"{item["Comment"]}",
                        };
                        writer.AddResource(node);
                    }
                    writer.Close();
                }

                if (projectItem.GetCustomTool() == ResXFileCodeGenerator)
                {
                    WriteDesigner(projectItem, dataTable, false);
                }
                else if (projectItem.GetCustomTool() == PublicResXFileCodeGenerator)
                {
                    WriteDesigner(projectItem, dataTable, true);
                }
            }
            else
            {
                throw new Exception("항목을 찾을 수 없습니다.");
            }
        }
Example #5
0
        public static GenerateDatabaseCodeLauncher Create(ProjectItem projectItem)
        {
            DatabaseConfig config   = new DatabaseConfig();
            XDocument      document = XDocument.Parse(File.ReadAllText(projectItem.GetFullPath()));

            config.Load(document);

            GenerateDatabaseCodeLauncher launcher = null;

            switch (config.Generation.Mode)
            {
            case DatabaseConfig.GenerateMode.EF6:
                launcher = new EF6GenerateDatabaseCodeLauncher(projectItem);
                break;

            case DatabaseConfig.GenerateMode.EFCore:
                launcher = new EFCoreGenerateDatabaseCodeLauncher(projectItem);
                break;

            default:
                return(null);
            }

            launcher.Config            = config;
            launcher.WorkingDictionary = Path.GetDirectoryName(launcher.InputFilePath);
            launcher.Initialize();
            return(launcher);
        }
Example #6
0
        /// <summary>
        /// Searches given UIHieararchy recursively for UIHierarchyItem with specified path
        /// </summary>        
        public static UIHierarchyItem FindUIHierarchyItem(UIHierarchyItems list, string path) {
            if (list == null) return null;
            if (!list.Expanded) list.Expanded = true;

            UIHierarchyItem result = null;
            foreach (UIHierarchyItem item in list) {
                if (item.Object is ProjectItem) {
                    ProjectItem p = (ProjectItem)item.Object;                    
                    result = ComparePathsSearch(p.GetFullPath(), path, item);
                } else if (item.Object is Project) {
                    Project p = (Project)item.Object;                    
                    result = ComparePathsSearch(p.FileName, path, item);
                } else if (item.Object is Solution) {
                    Solution s = (Solution)item.Object;                    
                    result = ComparePathsSearch(s.FileName, path, item);
                } else if (item.Object is UIHierarchyItem) {
                    ComparePathsSearch(item.Name, path, item);
                } else if (item.Object is Reference) {
                    
                } else throw new Exception(item.Object.GetVisualBasicType());

                if (result != null) break;
            }
            return result;
        }
Example #7
0
        /// <summary>
        /// Returns true if given solution contains given project item
        /// </summary>
        public static bool ContainsProjectItem(this Solution solution, ProjectItem item)
        {
            if (solution == null)
            {
                return(false);
            }
            if (!solution.IsOpen)
            {
                return(false);
            }
            if (item == null)
            {
                return(false);
            }
            if (item.Object == null)
            {
                return(false);
            }

            try {
                ProjectItem found = solution.FindProjectItem(item.GetFullPath());
                return(found != null);
            } catch (Exception) {
                return(false);
            }
        }
        // disclaimer: visual studio doesn't support adding dependent file under linked file
        // so no dependent transformed config under linked app.config in designer
        private static void CreateConfigFiles(Project project, ProjectItem projectItem)
        {
            string appConfigName           = projectItem.Name;
            var    buildConfigurationNames = project.GetBuildConfigurationNames();
            var    projectFileIsDirty      = false;
            // get app.config directory. new transform config will be created there.
            //var path = projectItem.GetFullPath();
            string path = null;

            if (projectItem.IsLink())
            {
                path = Directory.GetParent(projectItem.ContainingProject.FullName).FullName;
            }
            else
            {
                path = Directory.GetParent(projectItem.GetFullPath()).FullName;
            }

            foreach (var buildConfigurationName in buildConfigurationNames)
            {
                var dependentConfig         = GetTransformConfigName(appConfigName, buildConfigurationName);
                var dependentConfigFullPath = Path.Combine(path, dependentConfig);
                // check if config file exist
                if (!FileWrapper.Exists(dependentConfigFullPath))
                {
                    using (var file = FileWrapper.AppendText(dependentConfigFullPath))
                    {
                        file.Write(DependencyConfigContent);
                    }
                    projectFileIsDirty = true;
                    projectItem.ProjectItems.AddFromFile(dependentConfigFullPath);
                    //project.ProjectItems.AddFromFile(dependentConfigFullPath);
                }
            }
        }
        public static void PreviewTransform(ProjectItem projectItem)
        {
            var parent = projectItem.ParentProjectItemOrDefault();

            if (parent == null)
            {
                VsServices.Instance.ShowMessageBox("Cannot find source config");
                return;
            }
            var targetFileName = projectItem.Name;
            var sourceLabel    = parent.Name;
            var sourcePath     = parent.GetFullPath();
            var targetLabel    = targetFileName;

            // apply transform on file
            var xmlString = GetTransformString(sourcePath, projectItem.GetFullPath());
            // create temp file
            var tempFilePath = GetTempFilePath(targetFileName);

            var targetPath = tempFilePath;

            // write to temp file
            WriteToFile(tempFilePath, xmlString);

            VsService.OpenDiff(sourcePath, targetPath, sourceLabel, targetLabel);
        }
Example #10
0
        /// <summary>
        /// Если файл папке проекта <paramref name="sourceProjectDirectory"/> отсутствует, то создаёт новый файл с именем <paramref name="name"/>
        /// и содержанием <paramref name="content"/> в кодировке <paramref name="encoding"/>. Файл копируется в <paramref name="targetDirectory"/>.
        /// </summary>
        /// <param name="sourceProjectDirectory"></param>
        /// <param name="targetDirectory"></param>
        /// <param name="name"></param>
        /// <param name="content"></param>
        /// <param name="encoding"></param>
        private void EnsureFile(ProjectItem sourceProjectDirectory, DirectoryInfo targetDirectory, string name, string content, Encoding encoding)
        {
            if (sourceProjectDirectory == null)
            {
                throw new ArgumentNullException(nameof(sourceProjectDirectory));
            }
            if (targetDirectory == null)
            {
                throw new ArgumentNullException(nameof(targetDirectory));
            }
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (String.IsNullOrEmpty(content))
            {
                throw new ArgumentNullException(nameof(content));
            }
            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            ProjectItem projectFile = sourceProjectDirectory.GetChildItem(name);

            if (projectFile == null)
            {
                File.WriteAllText(Path.Combine(targetDirectory.FullName, name), content, encoding);
            }
            else
            {
                this.CopyAndOverwrite(projectFile.GetFullPath(), Path.Combine(targetDirectory.FullName, projectFile.Name));
            }
        }
Example #11
0
        private static TemplateRenderingResult GetTemplateOutput(Project project, IFileSystem fileSystem, string template, string projectRelativeOutputPath, Hashtable model, bool force)
        {
            var templateFullPath = FindTemplateAssertExists(project, fileSystem, template);
            var templateContent  = fileSystem.ReadAllText(templateFullPath);

            templateContent = PreprocessTemplateContent(templateContent);

            // Create the T4 host and engine
            using (var host = new DynamicTextTemplatingEngineHost {
                TemplateFile = templateFullPath
            }) {
                var t4Engine = GetT4Engine();

                // Make it possible to reference the same assemblies that your project references
                // using <@ Assembly @> directives.
                host.AddFindableAssembly(FindProjectAssemblyIfExists(project));
                foreach (dynamic reference in ((dynamic)project.Object).References)
                {
                    if ((!string.IsNullOrEmpty(reference.Path)) && (!reference.AutoReferenced))
                    {
                        host.AddFindableAssembly(reference.Path);
                    }
                }

                string      projectRelativeOutputPathWithExtension = null;
                ProjectItem existingOutputProjectItem = null;
                if (!string.IsNullOrEmpty(projectRelativeOutputPath))
                {
                    // Respect the <#@ Output Extension="..." #> directive
                    projectRelativeOutputPathWithExtension = projectRelativeOutputPath + GetOutputExtension(host, t4Engine, templateContent);

                    // Resolve the output path and ensure it doesn't already exist (unless "Force" is set)
                    var outputDiskPath = Path.Combine(project.GetFullPath(), projectRelativeOutputPathWithExtension);
                    existingOutputProjectItem = project.GetProjectItem(projectRelativeOutputPathWithExtension);
                    if (existingOutputProjectItem != null)
                    {
                        outputDiskPath = existingOutputProjectItem.GetFullPath();
                    }
                    if ((!force) && fileSystem.FileExists(outputDiskPath))
                    {
                        return(new TemplateRenderingResult(projectRelativeOutputPathWithExtension)
                        {
                            SkipBecauseFileExists = true
                        });
                    }
                }

                // Convert the incoming Hashtable to a dynamic object with properties for each of the Hashtable entries
                host.Model = DynamicViewModel.FromObject(model);

                // Run the text transformation
                var templateOutput = t4Engine.ProcessTemplate(templateContent, host);
                return(new TemplateRenderingResult(projectRelativeOutputPathWithExtension)
                {
                    Content = templateOutput,
                    Errors = host.Errors,
                    ExistingProjectItemToOverwrite = existingOutputProjectItem,
                });
            }
        }
Example #12
0
        /// <summary>
        /// Search given ProjectItem and its dependant items
        /// </summary>
        protected virtual void Process(ProjectItem projectItem, bool verbose)
        {
            if (projectItem.CanShowCodeContextMenu())
            {
                Process(projectItem, (e) => { return(true); }, verbose);
            }

            if (projectItem.ProjectItems != null)
            {
                foreach (ProjectItem item in projectItem.ProjectItems)
                {
                    Process(item, verbose);
                }
            }

            // in ASP .NET projects, ProjectItems returns null even though there are child items
            if (projectItem.GetFileType() == FILETYPE.ASPX)
            {
                foreach (string ext in StringConstants.CodeExtensions)   // try adding .vb and .cs extensions and search for the file
                {
                    string      path = projectItem.GetFullPath() + ext;
                    ProjectItem item = VisualLocalizerPackage.Instance.DTE.Solution.FindProjectItem(path);
                    if (item != null && item != projectItem)
                    {
                        Process(item, verbose);
                    }
                }
            }
        }
Example #13
0
        private void OverwriteProjectItemTextContent(ProjectItem item, string text)
        {
            var path = item.GetFullPath();

            SolutionManager.EnsureCheckedOutIfExists(path);
            _fileSystem.WriteAllText(path, text);
        }
        /// <summary>
        /// Explores given file, using parent batch command's methods as callbacks
        /// </summary>
        /// <param name="parentCommand"></param>
        /// <param name="projectItem"></param>
        /// <param name="maxLine">Line where parser should stop</param>
        /// <param name="maxIndex">Column where parser should stop</param>
        public void Explore(AbstractBatchCommand parentCommand, ProjectItem projectItem, int maxLine, int maxIndex)
        {
            if (parentCommand == null)
            {
                throw new ArgumentNullException("parentCommand");
            }
            if (projectItem == null)
            {
                throw new ArgumentNullException("projectItem");
            }

            lock (syncObject) {
                fullPath = projectItem.GetFullPath();
                if (string.IsNullOrEmpty(fullPath))
                {
                    throw new Exception("Cannot process item " + projectItem.Name);
                }

                this.parentCommand = parentCommand;
                this.declaredNamespaces.Clear();
                this.ClassFileName = Path.GetFileNameWithoutExtension(fullPath);
                this.projectItem   = projectItem;
                this.openedElements.Clear();

                // initialize type resolver
                if (parentCommand is BatchMoveCommand)
                {
                    webConfig = WebConfig.Get(projectItem, VisualLocalizerPackage.Instance.DTE.Solution);
                }
                else
                {
                    webConfig = null;
                }
                fileText = null;

                if (RDTManager.IsFileOpen(fullPath))                                             // file is open
                {
                    var textLines = VLDocumentViewsManager.GetTextLinesForFile(fullPath, false); // get text buffer
                    if (textLines == null)
                    {
                        return;
                    }

                    int lastLine, lastLineIndex;
                    int hr = textLines.GetLastLineIndex(out lastLine, out lastLineIndex);
                    Marshal.ThrowExceptionForHR(hr);

                    hr = textLines.GetLineText(0, 0, lastLine, lastLineIndex, out fileText); // get plain text
                    Marshal.ThrowExceptionForHR(hr);
                }
                else     // file is closed - read it from disk
                {
                    fileText = File.ReadAllText(fullPath);
                }

                Parser parser = new Parser(fileText, this, maxLine, maxIndex); // run ASP .NET parser
                parser.Process();
            }
        }
Example #15
0
        public static string GetRelativePath(this ProjectItem source)
        {
            var filePath = source.GetFullPath();
            var projectContainingFile = source.ContainingProject.FullName;
            var relativePath          = filePath.RelativePath(projectContainingFile);

            return(relativePath);
        }
Example #16
0
        /// <summary>
        /// Добавляет или обновляет файл с чекаутом.
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="targetFile"></param>
        private void AddOrReplaceFile(FileInfo sourceFile, ProjectItem targetFile)
        {
            if (targetFile != null)
            {
                this.DTE.CheckOutItem(targetFile);
                FileInfo targetFileInfo = new FileInfo(targetFile.GetFullPath());
                if (targetFileInfo.IsReadOnly)
                {
                    throw new NotificationException("Не удалось сделать чекаут для файла '{0}'", targetFileInfo.FullName);
                }

                File.Copy(sourceFile.FullName, targetFile.GetFullPath(), true);
            }
            else
            {
                this.Release.ProjectItems.AddFromFileCopy(sourceFile.FullName);
            }
        }
Example #17
0
 /// <summary>
 /// 리소스 디자이너 파일명
 /// </summary>
 public static string GetCustomToolOutput(this ProjectItem projectItem)
 {
     if (projectItem.GetProperty("CustomToolOutput") is string value)
     {
         var directoryPath = Path.GetDirectoryName(projectItem.GetFullPath());
         return(Path.Combine(directoryPath, value));
     }
     return(string.Empty);
 }
Example #18
0
        private static bool IsInSolution(string fileName)
        {
            if (WebLinterPackage.Dte == null)
            {
                return(false);
            }
            ProjectItem item = WebLinterPackage.Dte.Solution.FindProjectItem(fileName);

            return(item?.GetFullPath() is string);
        }
Example #19
0
        public static ProjectItem GetProjectItemContainingFullPath(this ProjectItem source, bool isLink = false)
        {
            // get target app.config full path
            var projectItemFullPath = source.GetFullPath();
            var dte = (DTE)source.DTE;

            return
                (dte.GetProjectItemHavingProperties(properties =>
                                                    properties.GetFullPath() == projectItemFullPath &&
                                                    properties.GetIsLink() == isLink));
        }
Example #20
0
        public static bool IsConfigFile(this ProjectItem item)
        {
            if (item == null || item.Properties == null || !item.IsKind(EnvDTE.Constants.vsProjectItemKindPhysicalFile) || item.ContainingProject == null)
            {
                return(false);
            }

            string fileName = Path.GetFileName(item.GetFullPath());

            return(fileName.Equals(VSPackage.ManifestFileName, StringComparison.OrdinalIgnoreCase));
        }
Example #21
0
        /// <summary>
        /// Returns filetype for given project item
        /// </summary>
        public static FILETYPE GetFileType(this ProjectItem item)
        {
            if (item == null)
            {
                return(FILETYPE.UNKNOWN);
            }
            if (item.Kind.ToUpper() != StringConstants.PhysicalFile)
            {
                return(FILETYPE.UNKNOWN);
            }

            string s = (item.GetFullPath()).ToLowerInvariant();

            return(s.GetFileType());
        }
        public static IEnumerable <ProjectItem> GetChildItemsIncludingSubfolders(this ProjectItem folder, IFileSystem fileSystem, string filter, params string[] kinds)
        {
            if (folder == null)
            {
                return(Enumerable.Empty <ProjectItem>());
            }

            var physicalFolderPath    = folder.GetFullPath();
            var matchingPhysicalFiles = fileSystem.FindFiles(physicalFolderPath, filter, true);

            return(from physicalFile in matchingPhysicalFiles
                   let projectItem = FindProjectItemMatchingPhysicalFile(folder.ContainingProject, physicalFile)
                                     where (projectItem != null) && (kinds.Contains(projectItem.Kind))
                                     select projectItem);
        }
        public static string GetProjectRelativePath(ProjectItem projectItem)
        {
            Project project = projectItem.ContainingProject;
            string projRelativePath = null;

            string rootProjectDir = project.GetFullPath();
            rootProjectDir = EnsureTrailingBackSlash(rootProjectDir);
            string fullPath = projectItem.GetFullPath();

            if (!String.IsNullOrEmpty(rootProjectDir) && !String.IsNullOrEmpty(fullPath))
            {
                projRelativePath = MakeRelativePath(fullPath, rootProjectDir);
            }

            return projRelativePath;
        }
        /// <summary>
        /// Выполняет чек-аут элемента проекта.
        /// </summary>
        /// <param name="dte"></param>
        /// <param name="item"></param>
        internal static void CheckOutItem(this DTE dte, ProjectItem item)
        {
            if (dte == null)
            {
                throw new ArgumentNullException(nameof(dte));
            }
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }


            string itemName = item.GetFullPath();

            dte.CheckOutItem(itemName);
        }
        public static string GetProjectRelativePath(ProjectItem projectItem)
        {
            Project project = projectItem.ContainingProject;
            string projRelativePath = null;

            string rootProjectDir = project.GetFullPath();
            rootProjectDir = EnsureTrailingBackSlash(rootProjectDir);
            string fullPath = projectItem.GetFullPath();

            if (!String.IsNullOrEmpty(rootProjectDir) && !String.IsNullOrEmpty(fullPath))
            {
                projRelativePath = MakeRelativePath(fullPath, rootProjectDir);
            }

            return projRelativePath;
        }
Example #26
0
        // TODO: This is a good candidate to get into Core, since this seems like a common thing to do
        public static string GetProjectRelativePath(this ProjectItem projectItem)
        {
            Project project          = projectItem.ContainingProject;
            string  projRelativePath = null;

            string rootProjectDir = project.GetFullPath();

            rootProjectDir = MvcProjectUtil.EnsureTrailingBackSlash(rootProjectDir);
            string fullPath = projectItem.GetFullPath();

            if (!String.IsNullOrEmpty(rootProjectDir) && !String.IsNullOrEmpty(fullPath))
            {
                projRelativePath = CoreScaffoldingUtil.MakeRelativePath(fullPath, rootProjectDir);
            }

            return(projRelativePath);
        }
        /// <summary>
        /// If the given item is ResX file, adds it to the list of ResX files
        /// </summary>
        private void SearchForResxFiles(ProjectItem item, List <GlobalTranslateProjectItem> resxFiles)
        {
            if (searchedProjectItems.Contains(item))
            {
                return;
            }
            SearchForResxFiles(item.ProjectItems, resxFiles);

            if (item.IsItemResX())
            {
                GlobalTranslateProjectItem r = new GlobalTranslateProjectItem(item);
                r.Checked  = false;
                r.Readonly = VLDocumentViewsManager.IsFileLocked(item.GetFullPath()) || RDTManager.IsFileReadonly(item.GetFullPath());

                resxFiles.Add(r);
            }
        }
Example #28
0
        public void Add(ProjectItem item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            var path = item.GetFullPath();
            var existing = Lookup(path);

            if (existing == null)
            {
                this.files[MakeKey(path)] = item;

                Logger.WriteLine($"{item.Name} was added to the cache");
            }
        }
        private static void FindInProjectItem(ProjectItem projectItem, Dictionary <string, string> fileToProjectMap)
        {
            string itemPath = projectItem.GetFullPath();

            if (LintableFiles.IsLintableTsTsxJsJsxFile(itemPath) && !fileToProjectMap.ContainsKey(itemPath))
            {
                fileToProjectMap.Add(itemPath, projectItem.ContainingProject.Name);
            }
            if (projectItem.ProjectItems == null)
            {
                return;
            }
            foreach (ProjectItem subProjectItem in projectItem.ProjectItems)
            {
                FindInProjectItem(subProjectItem, fileToProjectMap);
            }
        }
Example #30
0
        private static void FindTsConfigsInProjectItem(ProjectItem projectItem, HashSet <string> result)
        {
            string itemPath = projectItem.GetFullPath();

            if (LintableFiles.IsLintableTsconfig(itemPath) && !result.Contains(itemPath))
            {
                result.Add(itemPath);
            }
            // A project item can be a folder or a nested file, so we may need to continue searching down the tree
            if (projectItem.ProjectItems == null || LintableFiles.ContainsIgnorePattern(itemPath))
            {
                return;
            }
            foreach (ProjectItem subProjectItem in projectItem.ProjectItems)
            {
                FindTsConfigsInProjectItem(subProjectItem, result);
            }
        }
        public static string GetProjectRelativePath(ProjectItem projectItem)
        {
            Project project = projectItem.ContainingProject;
            string projRelativePath = null;

            //string namex = project.Properties.Item("TargetFramework").Name;
            //var valuex = project.Properties.Item("TargetFramework").Value;

            string rootProjectDir = project.GetFullPath();
            rootProjectDir = EnsureTrailingBackSlash(rootProjectDir);
            string fullPath = projectItem.GetFullPath();

            if (!String.IsNullOrEmpty(rootProjectDir) && !String.IsNullOrEmpty(fullPath))
            {
                projRelativePath = MakeRelativePath(fullPath, rootProjectDir);
            }

            return projRelativePath;
        }
        private void UpdateGeneratedDtos(ProjectItem projectItem, INativeTypesHandler typesHandler)
        {
            OutputWindowWriter.Show();
            OutputWindowWriter.ShowOutputPane(dte);
            OutputWindowWriter.WriteLine("--- Updating ServiceStack Reference '" + projectItem.Name + "' ---");
            string projectItemPath = projectItem.GetFullPath();
            var    selectedFiles   = projectItem.DTE.SelectedItems.Cast <SelectedItem>().ToList();
            bool   isDtoSelected   = selectedFiles.Any(item => item.Name.ToLowerInvariant().EndsWith(typesHandler.CodeFileExtension));

            if (isDtoSelected)
            {
                string filePath = projectItemPath;
                var    existingGeneratedCode = File.ReadAllLines(filePath).Join(Environment.NewLine);

                string baseUrl;
                if (!typesHandler.TryExtractBaseUrl(existingGeneratedCode, out baseUrl))
                {
                    OutputWindowWriter.WriteLine("Unable to read URL from DTO file. Please ensure the file was generated correctly from a ServiceStack server.");
                    return;
                }
                try
                {
                    var    options     = typesHandler.ParseComments(existingGeneratedCode);
                    string updatedCode = typesHandler.GetUpdatedCode(baseUrl, options);
                    using (var streamWriter = File.CreateText(filePath))
                    {
                        streamWriter.Write(updatedCode);
                        streamWriter.Flush();
                    }
                }
                catch (Exception e)
                {
                    OutputWindowWriter.WriteLine("Failed to update ServiceStack Reference: Unhandled error - " + e.Message);
                }

                OutputWindowWriter.WriteLine("--- Update ServiceStack Reference Complete ---");
            }
            else
            {
                OutputWindowWriter.WriteLine("--- Valid file not found ServiceStack Reference '" + projectItem.Name + "' ---");
            }
        }
Example #33
0
        /// <summary>
        /// Returns code model for given item
        /// </summary>
        public static FileCodeModel2 GetCodeModel(this ProjectItem item, bool throwOnNull, bool openFileIfNecessary, out bool fileOpened)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            fileOpened = false;

            if (item.FileCodeModel == null && !RDTManager.IsFileOpen(item.GetFullPath()) && openFileIfNecessary)
            {
                item.Open(EnvDTE.Constants.vsext_vk_Code);
                fileOpened = true;
            }

            if (item.FileCodeModel == null && throwOnNull)
            {
                throw new InvalidOperationException("FileCodeModel for " + item.Name + " cannot be obtained. Try recompiling the file.");
            }
            return((FileCodeModel2)item.FileCodeModel);
        }
        private static ProjectItem FindProjectItemByFullPath(ProjectItem projectItem, string fullPath)
        {
            if (projectItem != null && projectItem.GetFullPath() == fullPath)
                return projectItem;

            foreach (ProjectItem childItem in projectItem.ProjectItems)
            {
                var re = FindProjectItemByFullPath(childItem, fullPath);
                if (re != null)
                    return re;
            }

            return null;
        }
        private ViewModel GenerateJsFileFromProjectItem(ProjectItem item, bool fromCodeSnippet)
        {
            var fileExtension = Path.GetExtension(item.GetFullPath());
            var language = fileExtension.Equals(".cs") ? SupportedLanguage.CSharp : SupportedLanguage.VBNet;

            if (!item.Saved)
                item.Save();

            try
            {
                JsFile jsFile;

                if (fromCodeSnippet)
                {
                    dynamic comObject = item.Document.Selection;
                    jsFile = _codeGenerator.GetJsFileFromCodeSnippet(comObject.Text, language);
                }
                else
                {
                    jsFile = _codeGenerator.GetJsFileFromCodeFile(item.GetFullPath(), language);
                }

                return ViewModelExtensions.MapViewModelFromJsFile(jsFile);
            }
            catch (Exception)
            {
                _schell.Toast("Error parsing file");
            }

            return null;
        }
        private void UpdateGeneratedDtos(ProjectItem projectItem, INativeTypesHandler typesHandler)
        {
            OutputWindowWriter.Show();
            OutputWindowWriter.ShowOutputPane(dte);
            OutputWindowWriter.WriteLine("--- Updating ServiceStack Reference '" + projectItem.Name + "' ---");
            string projectItemPath = projectItem.GetFullPath();
            var selectedFiles = projectItem.DTE.SelectedItems.Cast<SelectedItem>().ToList();
            bool isDtoSelected = false;
            isDtoSelected = selectedFiles
                .Any(item => item.Name.ToLowerInvariant()
                    .EndsWith(typesHandler.CodeFileExtension));

            //Handle FSharp file extension name change for DTO files, eg .dto.fs to .dtos.fs
            if (!isDtoSelected && typesHandler is FSharpNativeTypesHandler)
            {
                isDtoSelected = selectedFiles
                .Any(item => item.Name.ToLowerInvariant()
                    .EndsWith(".dto.fs"));
            }

            if (isDtoSelected)
            {
                string filePath = projectItemPath;
                var existingGeneratedCode = File.ReadAllLines(filePath).Join(Environment.NewLine);

                string baseUrl;
                if (!typesHandler.TryExtractBaseUrl(existingGeneratedCode, out baseUrl))
                {
                    OutputWindowWriter.WriteLine("Unable to read URL from DTO file. Please ensure the file was generated correctly from a ServiceStack server.");
                    return;
                }
                try
                {
                    var options = typesHandler.ParseComments(existingGeneratedCode);
                    bool setSslValidationCallback = false;
                    //Don't set validation callback if one has already been set for VS.
                    if (ServicePointManager.ServerCertificateValidationCallback == null)
                    {
                        //Temp set validation callback to return true to avoid common dev server ssl certificate validation issues.
                        setSslValidationCallback = true;
                        ServicePointManager.ServerCertificateValidationCallback =
                            (sender, certificate, chain, errors) => true;
                    }
                    string updatedCode = typesHandler.GetUpdatedCode(baseUrl, options);
                    if (setSslValidationCallback)
                    {
                        //If callback was set to return true, reset back to null.
                        ServicePointManager.ServerCertificateValidationCallback = null;
                    }
                    using (var streamWriter = File.CreateText(filePath))
                    {
                        streamWriter.Write(updatedCode);
                        streamWriter.Flush();
                    }
                }
                catch (Exception e)
                {
                    OutputWindowWriter.WriteLine("Failed to update ServiceStack Reference: Unhandled error - " + e.Message);
                }

                OutputWindowWriter.WriteLine("--- Update ServiceStack Reference Complete ---");
            }
            else
            {
                OutputWindowWriter.WriteLine("--- Valid file not found ServiceStack Reference '" + projectItem.Name + "' ---");
            }
        }
Example #37
0
 public void Remove(ProjectItem projectItem)
 {
     this.Remove(projectItem.GetFullPath());
 }
 private void OverwriteProjectItemTextContent(ProjectItem item, string text)
 {
     var path = item.GetFullPath();
     SolutionManager.EnsureCheckedOutIfExists(path);
     _fileSystem.WriteAllText(path, text);
 }