private static void Main(string[] args) { bool showHelp = false; bool verbose = false; bool compress = false; int packageVersion = 8; Big.Target packageTarget = Big.Target.Win64; var options = new OptionSet() { { "v|verbose", "be verbose", v => verbose = v != null }, { "c|compress", "compress data with LZO1x", v => compress = v != null }, { "pv|package-version", "package version (default 8)", v => packageVersion = ParsePackageVersion(v) }, { "pt|package-target", "package platform (default Win64)", v => packageTarget = ParsePackageTarget(v) }, { "h|help", "show this message and exit", v => showHelp = v != null }, }; List <string> extras; try { extras = options.Parse(args); } catch (OptionException e) { Console.Write("{0}: ", GetExecutableName()); Console.WriteLine(e.Message); Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName()); return; } if (extras.Count < 1 || showHelp == true) { Console.WriteLine("Usage: {0} [OPTIONS]+ output_fat input_directory+", GetExecutableName()); Console.WriteLine(); Console.WriteLine("Pack files from input directories into a Big File (FAT/DAT pair)."); Console.WriteLine(); Console.WriteLine("Options:"); options.WriteOptionDescriptions(Console.Out); return; } var inputPaths = new List <string>(); string fatPath, datPath; if (extras.Count == 1) { inputPaths.Add(extras[0]); fatPath = Path.ChangeExtension(extras[0], ".fat"); datPath = Path.ChangeExtension(extras[0], ".dat"); } else { fatPath = extras[0]; if (Path.GetExtension(fatPath) != ".fat") { datPath = fatPath; fatPath = Path.ChangeExtension(datPath, ".fat"); } else { datPath = Path.ChangeExtension(fatPath, ".dat"); } inputPaths.AddRange(extras.Skip(1)); } var pendingEntries = new SortedDictionary <uint, PendingEntry>(); if (verbose == true) { Console.WriteLine("Finding files..."); } foreach (var relativePath in inputPaths) { string inputPath = Path.GetFullPath(relativePath); if (inputPath.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture)) == true) { inputPath = inputPath.Substring(0, inputPath.Length - 1); } foreach (string path in Directory.GetFiles(inputPath, "*", SearchOption.AllDirectories)) { PendingEntry pendingEntry; string fullPath = Path.GetFullPath(path); string partPath = fullPath.Substring(inputPath.Length + 1).ToLowerInvariant(); pendingEntry.FullPath = fullPath; pendingEntry.PartPath = partPath; var pieces = partPath.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); int index = 0; if (index >= pieces.Length) { continue; } if (index >= pieces.Length) { continue; } if (pieces[index].ToUpperInvariant() == "__UNKNOWN") { var partName = Path.GetFileNameWithoutExtension(partPath); if (string.IsNullOrEmpty(partName) == true) { continue; } if (partName.Length > 8) { partName = partName.Substring(0, 8); } pendingEntry.Name = null; pendingEntry.NameHash = uint.Parse(partName, NumberStyles.AllowHexSpecifier); } else { pendingEntry.Name = string.Join("\\", pieces.Skip(index).ToArray()).ToLowerInvariant(); pendingEntry.NameHash = ProjectHelpers.Hasher(ProjectHelpers.Modifier(pendingEntry.Name)); } if (pendingEntries.ContainsKey(pendingEntry.NameHash) == true) { Console.WriteLine("Ignoring duplicate of {0:X}: {1}", pendingEntry.NameHash, partPath); if (verbose == true) { Console.WriteLine(" Previously added from: {0}", pendingEntries[pendingEntry.NameHash].PartPath); } continue; } pendingEntries[pendingEntry.NameHash] = pendingEntry; } } var fat = new BigFile { Version = packageVersion, Target = packageTarget, Platform = TargetToPlatform(packageTarget), }; // reasonable default? // need to figure out what this value actually does if (packageTarget == Big.Target.Win64) { fat.Unknown70 = 0x32; } else if (packageTarget == Big.Target.PS3 || packageTarget == Big.Target.Xbox360) { fat.Unknown70 = 0x37; } else { throw new InvalidOperationException("unknown target"); } using (var output = File.Create(datPath)) { long current = 0; long total = pendingEntries.Count; var padding = total.ToString(CultureInfo.InvariantCulture).Length; foreach (var pendingEntry in pendingEntries.Select(kv => kv.Value)) { current++; if (verbose == true) { Console.WriteLine("[{0}/{1}] {2}", current.ToString(CultureInfo.InvariantCulture).PadLeft(padding), total, pendingEntry.PartPath); } var entry = new Big.Entry(); entry.NameHash = pendingEntry.NameHash; entry.Offset = output.Position; using (var input = File.OpenRead(pendingEntry.FullPath)) { EntryCompression.Compress(fat.Target, ref entry, input, compress, output); output.Seek(output.Position.Align(16), SeekOrigin.Begin); } fat.Entries.Add(entry); } } using (var output = File.Create(fatPath)) { fat.Serialize(output); } }
private void EnableCompileOnBuild(object sender, EventArgs e) { var item = ProjectHelpers.GetSelectedItems().First(); var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel)); if (!_isInstalled) { var question = MessageBox.Show(Text.NugetInstallPrompt, Vsix.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (question == DialogResult.No) { return; } Version version = new Version(BundlerMinifier.Constants.VERSION); if (version == new Version(1, 0, 21)) { version = (Version)null; } System.Threading.ThreadPool.QueueUserWorkItem((o) => { try { string statusInstalling = Text.NugetInstalling.AddParams(Constants.NUGET_ID); BundlerMinifierPackage._dte.StatusBar.Text = statusInstalling; BundlerMinifierPackage._dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationSync); var installer = componentModel.GetService <IVsPackageInstaller>(); installer.InstallPackage(null, item.ContainingProject, Constants.NUGET_ID, version, false); BundlerMinifierPackage._dte.StatusBar.Text = Text.NugetFinishedInstalling.AddParams(Constants.NUGET_ID); } catch (Exception ex) { Logger.Log(ex); BundlerMinifierPackage._dte.StatusBar.Text = Text.NugetErrorInstalling.AddParams(Constants.NUGET_ID); } finally { BundlerMinifierPackage._dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync); } }); } else { System.Threading.ThreadPool.QueueUserWorkItem((o) => { try { BundlerMinifierPackage._dte.StatusBar.Text = Text.NugetUninstalling.AddParams(Constants.NUGET_ID); BundlerMinifierPackage._dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationSync); var uninstaller = componentModel.GetService <IVsPackageUninstaller>(); uninstaller.UninstallPackage(item.ContainingProject, Constants.NUGET_ID, false); BundlerMinifierPackage._dte.StatusBar.Text = Text.NugetFinishedUninstalling.AddParams(Constants.NUGET_ID); } catch (Exception ex) { Logger.Log(ex); BundlerMinifierPackage._dte.StatusBar.Text = Text.NugetErrorUninstalling.AddParams(Constants.NUGET_ID); } finally { BundlerMinifierPackage._dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync); } }); } }
private void AddBundle(object sender, EventArgs e) { var item = ProjectHelpers.GetSelectedItems().FirstOrDefault(); if (item == null || item.ContainingProject == null) { return; } string folder = item.ContainingProject.GetRootFolder(); string configFile = Path.Combine(folder, Constants.CONFIG_FILENAME); IEnumerable <string> files = ProjectHelpers.GetSelectedItemPaths().Select(f => BundlerMinifier.FileHelpers.MakeRelative(configFile, f)); string inputFile = item.Properties.Item("FullPath").Value.ToString(); string outputFile = FileHelpers.GetMinFileName(inputFile); if (files.Count() > 1) { outputFile = GetOutputFileName(inputFile, Path.GetExtension(files.First())); } else { // Reminify file var bundles = BundleFileProcessor.IsFileConfigured(configFile, inputFile); if (bundles.Any()) { BundleService.SourceFileChanged(configFile, inputFile); return; } var bundles2 = BundleService.IsOutputConfigered(configFile, inputFile); if (bundles2.Any()) { BundleService.Process(configFile, bundles2); return; } } if (string.IsNullOrEmpty(outputFile)) { return; } BundlerMinifierPackage._dte.StatusBar.Progress(true, Resources.Text.StatusCreatingBundle, 0, 2); string relativeOutputFile = BundlerMinifier.FileHelpers.MakeRelative(configFile, outputFile); Bundle bundle = CreateBundleFile(files, relativeOutputFile); BundleHandler.AddBundle(configFile, bundle); BundlerMinifierPackage._dte.StatusBar.Progress(true, Resources.Text.StatusCreatingBundle, 1, 2); item.ContainingProject.AddFileToProject(configFile, "None"); BundlerMinifierPackage._dte.StatusBar.Progress(true, Resources.Text.StatusCreatingBundle, 2, 2); BundleService.Process(configFile); BundlerMinifierPackage._dte.StatusBar.Progress(false, Resources.Text.StatusCreatingBundle); BundlerMinifierPackage._dte.StatusBar.Text = Resources.Text.StatusBundleCreated; ProjectEventCommand.Instance?.EnsureProjectIsActive(item.ContainingProject); }
private async void ExecuteAsync(object sender, EventArgs e) { object selectedItem = ProjectHelpers.GetSelectedItem(); string folder = FindFolder(selectedItem); if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { return; } var selectedProjectItem = selectedItem as ProjectItem; var selectedProject = selectedItem as Project; Project project = selectedProjectItem?.ContainingProject ?? selectedProject ?? ProjectHelpers.GetActiveProject(); if (project == null) { return; } string input = PromptForFileName(folder).TrimStart('/', '\\').Replace("/", "\\"); if (string.IsNullOrEmpty(input)) { return; } string[] parsedInputs = GetParsedInput(input); foreach (string inputItem in parsedInputs) { input = inputItem; if (input.EndsWith("\\", StringComparison.Ordinal)) { input = input + "__dummy__"; } var inputLower = input.ToLower(); var inputCamel = inputLower.Substring(0, 1).ToUpper() + inputLower.Substring(1); //添加父级文件夹 var rootFolderName = $"{inputCamel}s"; var appFolder = Path.Combine(folder, rootFolderName); project.ProjectItems.AddFolder(appFolder); foreach (ProjectItem childProject in project.ProjectItems) { if (childProject.Name == rootFolderName) { //添加dto文件夹 var dtoFolder = Path.Combine(appFolder, "Dto"); childProject.ProjectItems.AddFolder(dtoFolder); //添加几个dto类及映射类 await CreateDtoFile(inputCamel, dtoFolder, selectedItem, childProject, project, TemplateType.DefaultDto); await CreateDtoFile(inputCamel, dtoFolder, selectedItem, childProject, project, TemplateType.CreateDto); await CreateDtoFile(inputCamel, dtoFolder, selectedItem, childProject, project, TemplateType.UpdateDto); await CreateDtoFile(inputCamel, dtoFolder, selectedItem, childProject, project, TemplateType.PagedDto); await CreateDtoFile(inputCamel, dtoFolder, selectedItem, childProject, project, TemplateType.MapProfile); break; } } //添加接口 await CreateFile(inputCamel, appFolder, selectedItem, project, TemplateType.Interface); //添加业务类 await CreateFile(inputCamel, appFolder, selectedItem, project, TemplateType.Class); } }
public static async Task <SpriteDocument> FromFile(string fileName) { string root = ProjectHelpers.GetProjectFolder(fileName); string folder = Path.GetDirectoryName(root); if (folder == null || root == null) { return(null); } XDocument doc = null; string contents = await FileHelpers.ReadAllTextRetry(fileName); try { doc = XDocument.Parse(contents); } catch (XmlException) { return(null); } XElement element = null; IEnumerable <string> imageFiles = ProjectHelpers.GetBundleConstituentFiles(doc.Descendants("file").Select(s => s.Value), root, folder, fileName); SpriteDocument sprite = new SpriteDocument(fileName, imageFiles.ToArray()); element = doc.Descendants("optimize").FirstOrDefault(); if (element != null) { sprite.Optimize = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("orientation").FirstOrDefault(); if (element != null) { sprite.IsVertical = element.Value.Equals("vertical", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("margin").FirstOrDefault(); sprite.Margin = WESettings.Instance.Sprite.Margin; // So the current implementation (without margin support) doesn't break. if (element != null) { sprite.Margin = int.Parse(element.Value); } element = doc.Descendants("runOnBuild").FirstOrDefault(); if (element != null) { sprite.RunOnBuild = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("outputType").FirstOrDefault(); if (element != null) { sprite.FileExtension = element.Value; } element = doc.Descendants("fullPathForIdentifierName").FirstOrDefault(); if (element != null) { sprite.UseFullPathForIdentifierName = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("outputDirectory").FirstOrDefault(); if (element != null) { sprite.OutputDirectory = element.Value; } element = doc.Descendants("useAbsoluteUrl").FirstOrDefault(); if (element != null) { sprite.UseAbsoluteUrl = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("outputDirectoryForCss").FirstOrDefault(); if (element != null) { sprite.CssOutputDirectory = element.Value; } element = doc.Descendants("outputDirectoryForLess").FirstOrDefault(); if (element != null) { sprite.LessOutputDirectory = element.Value; } element = doc.Descendants("outputDirectoryForScss").FirstOrDefault(); if (element != null) { sprite.ScssOutputDirectory = element.Value; } return(sprite); }
public static SpriteDocument FromFile(string fileName) { string root = ProjectHelpers.GetProjectFolder(fileName); string folder = Path.GetDirectoryName(root); XDocument doc = XDocument.Load(fileName); XElement element = null; var imageFiles = from f in doc.Descendants("file") select ProjectHelpers.ToAbsoluteFilePath(f.Value, root, folder); SpriteDocument sprite = new SpriteDocument(fileName, imageFiles.ToArray()); element = doc.Descendants("optimize").FirstOrDefault(); if (element != null) { sprite.Optimize = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("orientation").FirstOrDefault(); if (element != null) { sprite.IsVertical = element.Value.Equals("vertical", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("outputType").FirstOrDefault(); if (element != null) { sprite.FileExtension = element.Value; } element = doc.Descendants("fullPathForIdentifierName").FirstOrDefault(); if (element != null) { sprite.UseFullPathForIdentifierName = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("useAbsoluteUrl").FirstOrDefault(); if (element != null) { sprite.UseAbsoluteUrl = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("outputDirectoryForCss").FirstOrDefault(); if (element != null) { sprite.CssOutputDirectory = element.Value; } element = doc.Descendants("outputDirectoryForLess").FirstOrDefault(); if (element != null) { sprite.LessOutputDirectory = element.Value; } element = doc.Descendants("outputDirectoryForScss").FirstOrDefault(); if (element != null) { sprite.ScssOutputDirectory = element.Value; } return(sprite); }
private bool IsEnabledForCurrentProject() { var project = ProjectHelpers.GetActiveProject(); return(IsEnabledForProject(project)); }
private void EnableCompileOnBuild(object sender, EventArgs e) { var item = ProjectHelpers.GetSelectedItems().First(); var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel)); if (!_isInstalled) { var question = MessageBox.Show("A NuGet package will be installed to augment the MSBuild process, but no files will be added to the project.\rThis may require an internet connection.\r\rDo you want to continue?", Constants.VSIX_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (question == DialogResult.No) { return; } Version version = new Version(BundlerMinifierPackage.Version); if (version == new Version(1, 0, 21)) { version = (Version)null; } System.Threading.ThreadPool.QueueUserWorkItem((o) => { try { BundlerMinifierPackage._dte.StatusBar.Text = $"Installing {Constants.NUGET_ID} NuGet package, this may take a minute..."; BundlerMinifierPackage._dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationSync); var installer = componentModel.GetService <IVsPackageInstaller>(); installer.InstallPackage(null, item.ContainingProject, Constants.NUGET_ID, version, false); BundlerMinifierPackage._dte.StatusBar.Text = $"Finished installing the {Constants.NUGET_ID} NuGet package"; } catch (Exception ex) { Logger.Log(ex); BundlerMinifierPackage._dte.StatusBar.Text = $"Unable to install the {Constants.NUGET_ID} NuGet package"; } finally { BundlerMinifierPackage._dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync); } }); } else { System.Threading.ThreadPool.QueueUserWorkItem((o) => { try { BundlerMinifierPackage._dte.StatusBar.Text = $"Uninstalling {Constants.NUGET_ID} NuGet package, this may take a minute..."; BundlerMinifierPackage._dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationSync); var uninstaller = componentModel.GetService <IVsPackageUninstaller>(); uninstaller.UninstallPackage(item.ContainingProject, Constants.NUGET_ID, false); BundlerMinifierPackage._dte.StatusBar.Text = $"Finished uninstalling the {Constants.NUGET_ID} NuGet package"; } catch (Exception ex) { Logger.Log(ex); BundlerMinifierPackage._dte.StatusBar.Text = $"Unable to ininstall the {Constants.NUGET_ID} NuGet package"; } finally { BundlerMinifierPackage._dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync); } }); } }
public async override void Invoke() { string filePath = ProjectHelpers.ToAbsoluteFilePath(_path, _span.TextBuffer.GetFileName()); await ApplyChanges(filePath); }
/// <summary> /// Create an absolute path relative to the solution directory. /// </summary> /// <param name="fileName">The relative path of the file that need to be resolved.</param> /// <returns>The absolute file path</returns> private static string ResolvePathRelativeToSolution(string fileName) { return(ResolvePaths(fileName, ProjectHelpers.GetSolutionFolderPath()).FirstOrDefault()); }
/// <summary> /// css生成dll /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CsDllCommandInvoke(object sender, EventArgs e) { var items = ProjectHelpers.GetSelectedItemPaths(_dte); if (items.Count() != 1) { ProjectHelpers.AddError(_package, "no cs was selected"); return; } try { //System.IServiceProvider oServiceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_dte); //EnvDTE.ProjectItem oProjectItem = _dte.SelectedItems.Item(1).ProjectItem; //Microsoft.Build.Evaluation.Project oBuildProject = Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection.GetLoadedProjects(oProjectItem.ContainingProject.FullName).SingleOrDefault(); //Microsoft.Build.Evaluation.ProjectProperty oGUID = oBuildProject.AllEvaluatedProperties.SingleOrDefault(oProperty => oProperty.Name == "ProjectGuid"); //Microsoft.VisualStudio.Shell.Interop.IVsHierarchy oVsHierarchy = VsShellUtilities.GetHierarchy(oServiceProvider, new Guid(oGUID.EvaluatedValue)); //Microsoft.VisualStudio.Shell.Interop.IVsBuildPropertyStorage oVsBuildPropertyStorage = (Microsoft.VisualStudio.Shell.Interop.IVsBuildPropertyStorage)oVsHierarchy; //string szItemPath = (string)oProjectItem.Properties.Item("FullPath").Value; string szItemPath = ProjectHelpers.GetActiveProject().FullName; var refDll = new List <string>(); var csprojText = File.ReadAllLines(szItemPath).Where(r => r.Contains(@"<ProjectReference Include=") || (r.Contains("<HintPath>"))); var serviceStack = csprojText.Where(r => r.Contains("AntServiceStack")); foreach (var s in serviceStack) { string folder = new FileInfo(szItemPath).DirectoryName; if (s.Trim().EndsWith(".csproj\">")) { var s1 = s.Split('"')[1]; var s2 = s1.Split('\\'); var dotCount = s2.Count(r => r.Equals("..")); for (int i = 0; i < dotCount; i++) { folder = Directory.GetParent(folder).FullName; } for (int i = 0; i < s2.Length - 1; i++) { var ss = s2[i]; if (ss.Equals("..")) { continue; } folder = Path.Combine(folder, ss); } folder = Path.Combine(folder, "bin", "Debug"); if (!Directory.Exists(folder)) { ProjectHelpers.AddError(_package, folder + " not found"); return; } var dllname = s2[s2.Length - 1].Replace(".csproj", ".dll"); var dllPath = Path.Combine(folder, dllname); if (!File.Exists(dllPath)) { ProjectHelpers.AddError(_package, dllPath + " not found"); return; } refDll.Add("\"" + dllPath + "\""); } else if (s.Trim().Contains("<HintPath>") && s.Trim().Contains("AntServiceStack") && s.Trim().Contains("dll")) { var dllPath = s.Trim().Split('>')[1].Split('<')[0]; if (dllPath.StartsWith("..")) { var s2 = dllPath.Split('\\'); var dotCount = s2.Count(r => r.Equals("..")); for (int i = 0; i < dotCount; i++) { folder = Directory.GetParent(folder).FullName; } for (int i = 0; i < s2.Length; i++) { var ss = s2[i]; if (ss.Equals("..")) { continue; } folder = Path.Combine(folder, ss); } dllPath = folder; } refDll.Add("\"" + dllPath + "\""); } } //uint nItemId; //oVsHierarchy.ParseCanonicalName(szItemPath, out nItemId); //string szOut; //oVsBuildPropertyStorage.GetItemAttribute(nItemId, "ClientDllVersion", out szOut); //if (string.IsNullOrEmpty(szOut)) //{ // //oVsBuildPropertyStorage.SetItemAttribute(nItemId, "ItemColor", ); //} string file = items.ElementAt(0); string baseFileName = Path.GetFileNameWithoutExtension(file); FileInfo fileInfo = new FileInfo(file); var frameworkPath = RuntimeEnvironment.GetRuntimeDirectory(); var cscPath = Path.Combine(frameworkPath, "csc.exe"); //C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\csc.exe /t:library /out:MyCScode.dll *.cs /debug /r:System.dll /r:System.Web.dll /r:System.Data.dll /r:System.Xml.dll System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.UseShellExecute = true; startInfo.WorkingDirectory = fileInfo.DirectoryName; startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = cscPath; startInfo.Arguments = "/t:library /out:" + baseFileName + ".dll " + baseFileName + ".cs /r:System.dll /r:System.Configuration.dll /r:System.Core.dll /r:System.Runtime.Serialization.dll /r:System.ServiceModel.dll /r:System.Xml.Linq.dll /r:System.Data.DataSetExtensions.dll /r:Microsoft.CSharp.dll /r:System.Data.dll /r:System.Xml.dll" + (refDll.Count > 0 ? " /r:" + string.Join(" /r:", refDll) : ""); process.StartInfo = startInfo; process.Start(); process.WaitForExit(10000);// 10 seconds timeout int result = process.ExitCode; if (result == -1) { ProjectHelpers.AddError(_package, "cs compile err :" + startInfo.Arguments); MessageBox.Show("Error happens", "Cs Dll Conversion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } MessageBox.Show("compile is success", "Cs Dll Conversion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = fileInfo.DirectoryName, UseShellExecute = true, Verb = "open" }); } catch (Exception ex) { ProjectHelpers.AddError(_package, ex.ToString()); MessageBox.Show("Error happens: " + ex, "Cs Dll Conversion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
/// <summary> /// wsdl生成cs /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void WsdlCommandInvoke(object sender, EventArgs e) { var items = ProjectHelpers.GetSelectedItemPaths(_dte); if (items.Count() != 1 || !(items.ElementAt(0).ToLower().EndsWith(".wsdl", StringComparison.OrdinalIgnoreCase))) { return; } var _file = items.ElementAt(0); var project = ProjectHelpers.GetActiveProject(); var projectFullName = ProjectHelpers.GetActiveProject().FullName; var projectInfo = new FileInfo(projectFullName); var folderproject = projectInfo.Directory?.FullName; try { // Fist display the UI and get the options. WebServiceCodeGenDialogNew dialog = new WebServiceCodeGenDialogNew(); if (!project.IsWebProject()) { dialog.DestinationNamespace = project.GetProjectProperty("DefaultNamespace"); if (string.IsNullOrEmpty(dialog.DestinationNamespace)) { dialog.DestinationNamespace = Path.GetFileNameWithoutExtension(_file); } } else { dialog.DestinationNamespace = Path.GetFileNameWithoutExtension(_file); } dialog.DestinationFilename = ProjectHelpers.GetDefaultDestinationFilename(_file); dialog.WsdlLocation = _file; if (dialog.ShowDialog() == DialogResult.Cancel) { return; } var wsdlFile = _file; // Try the Rpc2DocumentLiteral translation first. // wsdlFile = TryTranslateRpc2DocumentLiteral(wsdlFile); CodeGenOptions options = new CodeGenOptions(); options.MetadataLocation = wsdlFile; options.OutputFileName = dialog.DestinationFilename; options.OutputLocation = folderproject; options.ProjectDirectory = project.FullName; options.Language = CodeLanguage.CSharp; options.ProjectName = project.Name; options.EnableDataBinding = dialog.EnableDataBinding; options.EnableSummaryComment = dialog.Comment; options.GenerateCollections = dialog.Collections; options.GenerateTypedLists = dialog.TypedList; options.EnableLazyLoading = dialog.LazyLoading; options.GenerateSeparateFiles = dialog.GenerateMultipleFiles; options.OnlyUseDataContractSerializer = dialog.OnlyUseDataContractSerializer; options.GenerateSeparateFilesEachNamespace = dialog.GenerateMultipleFilesEachNamespace; options.GenerateSeparateFilesEachXsd = dialog.GenerateSeparateFilesEachXsd; options.AscendingClassByName = dialog.AscendingClassByName; options.OverwriteExistingFiles = dialog.Overwrite; options.ClrNamespace = dialog.DestinationNamespace; options.EnableBaijiSerialization = dialog.EnableBaijiSerialization; options.AddCustomRequestInterface = dialog.AddCustomRequestInterface; options.CustomRequestInterface = dialog.CustomRequestInterface; options.ForceElementName = dialog.ForceElementName; options.ForceElementNamespace = dialog.ForceElementNamespace; options.GenerateAsyncOperations = dialog.GenerateAsyncOperations; if (dialog.ServiceCode) { options.CodeGeneratorMode = CodeGeneratorMode.Service; } else if (dialog.ClientCode) { options.CodeGeneratorMode = CodeGeneratorMode.Client; } else { options.CodeGeneratorMode = CodeGeneratorMode.ClientForTest; } options.EnableInitializeFields = true; CodeGenerator codeGenerator = new CodeGenerator(); CodeWriterOutput output = codeGenerator.GenerateCode(options); AddGeneratedFilesToProject(output); // Finally add the project references. ProjectHelpers.AddAssemblyReferences(project); MessageBox.Show("Code generation successfully completed.", "Ant.SOA.CodeGen", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { ProjectHelpers.AddError(_package, ex.ToString()); MessageBox.Show(ex.Message, "CodeGeneration", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// 根据xsd生成model /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ModelCommandInvoke(object sender, EventArgs e) { //可以选多个 var items = ProjectHelpers.GetSelectedItemPaths(_dte); if (items != null && items.Any(r => !r.ToLower().EndsWith(".xsd", StringComparison.OrdinalIgnoreCase))) { ProjectHelpers.AddError(_package, "select file is not xsd file"); return; } var _file = items.ElementAt(0); var project = ProjectHelpers.GetActiveProject(); var projectFullName = ProjectHelpers.GetActiveProject().FullName; var projectInfo = new FileInfo(projectFullName); var folderproject = projectInfo.Directory?.FullName; try { string[] dataContractFiles = items.ToArray(); XsdCodeGenDialog dialogForm = new XsdCodeGenDialog(dataContractFiles); if (!project.IsWebProject()) { dialogForm.Namespace = project.GetProjectProperty("DefaultNamespace"); if (string.IsNullOrEmpty(dialogForm.Namespace)) { dialogForm.Namespace = Path.GetFileNameWithoutExtension(_file); } } else { dialogForm.Namespace = Path.GetFileNameWithoutExtension(_file); } dialogForm.TargetFileName = ProjectHelpers.GetDefaultDestinationFilename(_file); if (dialogForm.ShowDialog() == DialogResult.Cancel) { return; } CodeGenOptions options = new CodeGenOptions(); options.GenerateDataContractsOnly = true; options.DataContractFiles = dataContractFiles; options.GenerateSeparateFiles = dialogForm.GenerateMultipleFiles; options.GenerateSeparateFilesEachNamespace = dialogForm.GenerateMultipleFilesEachNamespace; options.GenerateSeparateFilesEachXsd = dialogForm.GenerateSeparateFilesEachXsd; options.AscendingClassByName = dialogForm.AscendingClassByName; options.OnlyUseDataContractSerializer = dialogForm.OnlyUseDataContractSerializer; options.OverwriteExistingFiles = dialogForm.OverwriteFiles; options.EnableDataBinding = dialogForm.DataBinding; options.EnableSummaryComment = dialogForm.Comment; options.GenerateCollections = dialogForm.Collections; options.GenerateTypedLists = dialogForm.TypedList; options.EnableLazyLoading = dialogForm.LazyLoading; options.OutputFileName = dialogForm.TargetFileName; options.OutputLocation = folderproject; options.ProjectDirectory = project.FullName; options.Language = CodeLanguage.CSharp; options.ClrNamespace = dialogForm.Namespace; options.EnableSummaryComment = dialogForm.Comment; options.ProjectName = project.Name; options.EnableBaijiSerialization = dialogForm.EnableBaijiSerialization; options.AddCustomRequestInterface = dialogForm.AddCustomRequestInterface; options.CustomRequestInterface = dialogForm.CustomRequestInterface; options.ForceElementName = dialogForm.ForceElementName; options.ForceElementNamespace = dialogForm.ForceElementNamespace; options.GenerateAsyncOperations = dialogForm.GenerateAsyncOperations; options.EnableInitializeFields = true; CodeGenerator codeGenerator = new CodeGenerator(); CodeWriterOutput output = codeGenerator.GenerateCode(options); AddGeneratedFilesToProject(output); // Finally add the project references. ProjectHelpers.AddAssemblyReferences(project); MessageBox.Show("Model generation successfully completed.", "Ant.SOA.CodeGen", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { ProjectHelpers.AddError(_package, ex.ToString()); MessageBox.Show(ex.Message, "CodeGeneration", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public async override Task RunAsync() { var extensionBundleManager = ExtensionBundleHelper.GetExtensionBundleManager(); if (extensionBundleManager.IsExtensionBundleConfigured()) { var hostFilePath = Path.Combine(Environment.CurrentDirectory, ScriptConstants.HostMetadataFileName); if (_showExtensionBundleWarning) { ColoredConsole.WriteLine(WarningColor($"No action performed. Extension bundle is configured in {hostFilePath}")); } return; } if (CommandChecker.CommandExists("dotnet")) { if (!string.IsNullOrEmpty(ConfigPath) && !FileSystemHelpers.DirectoryExists(ConfigPath)) { throw new CliArgumentsException("Invalid config path, please verify directory exists"); } var extensionsProj = await ExtensionsHelper.EnsureExtensionsProjectExistsAsync(_secretsManager, Csx, ConfigPath); if (string.IsNullOrEmpty(Package) && string.IsNullOrEmpty(Version)) { var project = ProjectHelpers.GetProject(extensionsProj); foreach (var extensionPackage in ExtensionsHelper.GetExtensionPackages()) { // Only add / update package referece if it does not exist or forced update is enabled if (!ProjectHelpers.PackageReferenceExists(project, extensionPackage.Name) || Force) { await AddPackage(extensionsProj, extensionPackage.Name, extensionPackage.Version); } } } else if (!string.IsNullOrEmpty(Package) && !string.IsNullOrEmpty(Version)) { await AddPackage(extensionsProj, Package, Version); } else { throw new CliArgumentsException("Must specify extension package name and version", new CliArgument { Name = nameof(Package), Description = "Extension package name" }, new CliArgument { Name = nameof(Version), Description = "Extension package version" } ); } var syncAction = new SyncExtensionsAction(_secretsManager, false) { OutputPath = OutputPath, ConfigPath = ConfigPath }; await syncAction.RunAsync(); } else { ColoredConsole.Error.WriteLine(ErrorColor(Constants.Errors.ExtensionsNeedDotnet)); } }
/// <summary> /// /// </summary> private void UpgradePackagesConfig() { _isProcessing = true; var files = ProjectHelpers.GetSelectedItems().Where(c => _fileNames.Contains(Path.GetFileName(c.GetFullPath()))); if (!files.Any()) { _dte.StatusBar.Text = "Please select a package.config file to nuke from orbit."; _isProcessing = false; return; } //var projectFolder = ProjectHelpers.GetRootFolder(ProjectHelpers.GetActiveProject()); int count = files.Count(); //RWM: Don't mess with these. XNamespace defaultNs = "http://schemas.microsoft.com/developer/msbuild/2003"; var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }; try { string text = count == 1 ? " file" : " files"; _dte.StatusBar.Progress(true, $"Fixing {count} config {text}...", AmountCompleted: 1, Total: count + 1); Parallel.For(0, count, options, i => { var packageReferences = new XElement(defaultNs + "ItemGroup"); var packagesConfigItem = files.ElementAt(i); var packagesConfigPath = packagesConfigItem.GetFullPath(); var projectPath = packagesConfigItem.ContainingProject.FileName; //RWM: Start by backing up the files. File.Copy(packagesConfigPath, $"{packagesConfigPath}.bak", true); File.Copy(projectPath, $"{projectPath}.bak", true); Logger.Log($"Backup created for {packagesConfigPath}."); //RWM: Load the files. var project = XDocument.Load(projectPath); var packagesConfig = XDocument.Load(packagesConfigPath); //RWM: Get references to the stuff we're gonna get rid of. var oldReferences = project.Root.Descendants().Where(c => c.Name.LocalName == "Reference"); var errors = project.Root.Descendants().Where(c => c.Name.LocalName == "Error"); var targets = project.Root.Descendants().Where(c => c.Name.LocalName == "Import"); foreach (var row in packagesConfig.Root.Elements().ToList()) { //RWM: Create the new PackageReference. packageReferences.Add(new XElement(defaultNs + "PackageReference", new XAttribute("Include", row.Attribute("id").Value), new XAttribute("Version", row.Attribute("version").Value))); //RWM: Remove the old Standard Reference. if (oldReferences != null) { oldReferences.Where(c => c.Attribute("Include") != null).Where(c => c.Attribute("Include").Value.Split(new Char[] { ',' })[0].ToLower() == row.Attribute("id").Value.ToLower()).ToList() .ForEach(c => c.Remove()); } //RWM: Remove any remaining Standard References where the PackageId is in the HintPath. if (oldReferences != null) { oldReferences.Where(c => c.Descendants().Any(d => d.Value.Contains(row.Attribute("id").Value))).ToList() .ForEach(c => c.Remove()); } //RWM: Remove any Error conditions for missing Package Targets. if (errors != null) { errors.Where(c => c.Attribute("Condition") != null).Where(c => c.Attribute("Condition").Value.Contains(row.Attribute("id").Value)).ToList() .ForEach(c => c.Remove()); } //RWM: Remove any Package Targets. if (targets != null) { targets.Where(c => c.Attribute("Project") != null).Where(c => c.Attribute("Project").Value.Contains(row.Attribute("id").Value)).ToList() .ForEach(c => c.Remove()); } } //RWM: Fix up the project file by adding PackageReferences, removing packages.config, and pulling NuGet-added Targets. project.Root.Elements().First(c => c.Name.LocalName == "ItemGroup").AddBeforeSelf(packageReferences); var packageConfigReference = project.Root.Descendants().FirstOrDefault(c => c.Name.LocalName == "None" && c.Attribute("Include").Value == "packages.config"); if (packageConfigReference != null) { packageConfigReference.Remove(); } var nugetBuildImports = project.Root.Descendants().FirstOrDefault(c => c.Name.LocalName == "Target" && c.Attribute("Name").Value == "EnsureNuGetPackageBuildImports"); if (nugetBuildImports != null && nugetBuildImports.Descendants().Count(c => c.Name.LocalName == "Error") == 0) { nugetBuildImports.Remove(); } //RWM: Upgrade the ToolsVersion so it can't be opened in VS2015 anymore. project.Root.Attribute("ToolsVersion").Value = "15.0"; //RWM: Save the project and delete Packages.config. ProjectHelpers.CheckFileOutOfSourceControl(projectPath); ProjectHelpers.CheckFileOutOfSourceControl(packagesConfigPath); project.Save(projectPath, SaveOptions.None); File.Delete(packagesConfigPath); Logger.Log($"Update complete. Visual Studio will prompt you to reload the project now."); }); } catch (AggregateException agEx) { _dte.StatusBar.Progress(false); Logger.Log($"Update failed. Exceptions:"); foreach (var ex in agEx.InnerExceptions) { Logger.Log($"Message: {ex.Message}{Environment.NewLine}{ex.StackTrace}"); } _dte.StatusBar.Text = "Operation failed. Please see Output Window for details."; _isProcessing = false; } finally { _dte.StatusBar.Progress(false); _dte.StatusBar.Text = "Operation finished. Please see Output Window for details."; _isProcessing = false; } }
private string FindFile(IEnumerable <string> extensions, out int position) { string root = ProjectHelpers.GetProjectFolder(TextView.TextBuffer.GetFileName()); position = -1; bool isLow = false, isMedium = false; string result = null; foreach (string ext in extensions) { ICssParser parser = CssParserLocator.FindComponent(Mef.GetContentType(ext.Trim('.'))).CreateParser(); foreach (string file in Directory.EnumerateFiles(root, "*" + ext, SearchOption.AllDirectories)) { if (file.EndsWith(".min" + ext, StringComparison.OrdinalIgnoreCase) || file.Contains("node_modules") || file.Contains("bower_components")) { continue; } string text = FileHelpers.ReadAllTextRetry(file).ConfigureAwait(false).GetAwaiter().GetResult(); int index = text.IndexOf("." + _className, StringComparison.Ordinal); if (index == -1) { continue; } var css = parser.Parse(text, true); var visitor = new CssItemCollector <ClassSelector>(false); css.Accept(visitor); var selectors = visitor.Items.Where(c => c.ClassName.Text == _className); var high = selectors.FirstOrDefault(c => c.FindType <AtDirective>() == null && (c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ",")); if (high != null) { position = high.Start; return(file); } var medium = selectors.FirstOrDefault(c => c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ","); if (medium != null && !isMedium) { position = medium.Start; result = file; isMedium = true; continue; } var low = selectors.FirstOrDefault(); if (low != null && !isMedium && !isLow) { position = low.Start; result = file; isLow = true; continue; } } } return(result); }
static void AddProjectFile(string path, string contents) { File.WriteAllText(path, contents); ProjectHelpers.GetActiveProject().ProjectItems.AddFromFile(path); }
private void BeforeQueryStatus(object sender, EventArgs e) { Project project = ProjectHelpers.GetSelectedItem() as Project; ((OleMenuCommand)sender).Visible = project != null; }
private void MenuItemCallback(object sender, EventArgs e, bool visitor) { try { // Return if I can't determine what application this is. DTE application = Workspaces.Help.GetApplication(); if (application == null) { return; } // Get active view and determine if it's a grammar file. var grammar_view = AntlrLanguagePackage.Instance.GetActiveView(); if (grammar_view == null) { return; } ITextCaret car = grammar_view.Caret; CaretPosition cp = car.Position; SnapshotPoint bp = cp.BufferPosition; int pos = bp.Position; ITextBuffer buffer = grammar_view.TextBuffer; var g4_file_path = buffer.GetFFN().Result; if (g4_file_path == null) { return; } IGrammarDescription grammar_description = LanguageServer.GrammarDescriptionFactory.Create(g4_file_path); if (!grammar_description.IsFileType(g4_file_path)) { return; } // Get name of base class for listener and visitor. These are generated by Antlr, // constructed from the name of the file. var grammar_name = Path.GetFileName(g4_file_path); grammar_name = Path.GetFileNameWithoutExtension(grammar_name); var listener_baseclass_name = visitor ? (grammar_name + "BaseVisitor") : (grammar_name + "BaseListener"); var listener_class_name = visitor ? ("My" + grammar_name + "Visitor") : ("My" + grammar_name + "Listener"); // In the current view, find the details of the Antlr symbol at the cursor. TextExtent extent = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Navigator[grammar_view] .GetExtentOfWord(bp); SnapshotSpan span = extent.Span; AntlrLanguagePackage.Instance.Span = span; // Now, check for valid classification type. var cla = -1; bool can_gotovisitor = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Aggregator[grammar_view].GetClassificationSpans(span).Where( classification => { var name = classification.ClassificationType.Classification; if (!grammar_description.InverseMap.TryGetValue(name, out int c)) { return(false); } cla = c; return(grammar_description.CanGotovisitor[cla]); }).Any(); if (!can_gotovisitor) { return; } // Find defining occurrence. List <Antlr4.Runtime.Tree.TerminalNodeImpl> where = new List <Antlr4.Runtime.Tree.TerminalNodeImpl>(); List <ParserDetails> where_details = new List <ParserDetails>(); Antlr4.Runtime.Tree.TerminalNodeImpl token = null; foreach (var kvp in ParserDetailsFactory.AllParserDetails) { string file_name = kvp.Key; ParserDetails details = kvp.Value; { var it = details.Defs.Where( (t) => t.Value == cla && t.Key.Symbol.Text == span.GetText()).Select(t => t.Key); where.AddRange(it); foreach (var i in it) { where_details.Add(details); } } } if (where.Any()) { token = where.First(); } else { System.Windows.Forms.MessageBox.Show( "Symbol '" + span.GetText() + "' definer not found."); return; } // Get the symbol name as a string. var symbol_name = token.Symbol.Text; var capitalized_symbol_name = Capitalized(symbol_name); // Parse all the C# files in the solution. Dictionary <string, SyntaxTree> trees = new Dictionary <string, SyntaxTree>(); foreach (var item in DteExtensions.SolutionFiles(application)) { string file_name = item.Name; if (file_name != null) { string prefix = file_name.TrimSuffix(".cs"); if (prefix == file_name) { continue; } try { object prop = item.Properties.Item("FullPath").Value; string ffn = (string)prop; StreamReader sr = new StreamReader(ffn); string code = sr.ReadToEnd(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[ffn] = tree; } catch (Exception) { } } } // Find all occurrences of visitor class. List <ClassDeclarationSyntax> found_class = new List <ClassDeclarationSyntax>(); string class_file_path = null; try { foreach (var kvp in trees) { var file_name = kvp.Key; var tree = kvp.Value; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); if (root == null) { continue; } foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); throw new Exception(); } } } } } } catch { } if (found_class.Count == 0) { if (!global::Options.POptions.GetBoolean("GenerateVisitorListener")) { return; } // Look in grammar directory for any C# files. string name_space = null; string ffn = Path.GetFullPath(g4_file_path); ffn = Path.GetDirectoryName(ffn); foreach (var i in DteExtensions.SolutionFiles(application)) { string file_name = i.Name; if (file_name != null) { string prefix = file_name.TrimSuffix(".cs"); if (prefix == file_name) { continue; } try { object prop = i.Properties.Item("FullPath").Value; string ffncs = (string)prop; // Look for namespace. var t = trees[ffncs]; if (t == null) { continue; } var root = t.GetCompilationUnitRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } name_space = namespace_member.Name.ToString(); break; } } catch (Exception) { } } } if (name_space == null) { name_space = "Generated"; } // Create class. string clazz = visitor ? $@" using System; using System.Collections.Generic; using System.Text; namespace {name_space} {{ class {listener_class_name}<Result> : {listener_baseclass_name}<Result> {{ //public override Result VisitA([NotNull] A3Parser.AContext context) //{{ // return VisitChildren(context); //}} }} }} " : $@" using System; using System.Collections.Generic; using System.Text; namespace {name_space} {{ class {listener_class_name} : {listener_baseclass_name} {{ //public override void EnterA(A3Parser.AContext context) //{{ // base.EnterA(context); //}} //public override void ExitA(A3Parser.AContext context) //{{ // base.ExitA(context); //}} }} }} "; class_file_path = ffn + Path.DirectorySeparatorChar + listener_class_name + ".cs"; System.IO.File.WriteAllText(class_file_path, clazz); var item = ProjectHelpers.GetSelectedItem(); string folder = FindFolder(item); if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { return; } var file = new FileInfo(class_file_path); var selectedItem = Workspaces.Workspace.Instance.FindDocument(class_file_path); if (selectedItem == null) { //var selectedProject = item as Project; //Project project = selectedItem?.ContainingProject ?? selectedProject ?? null; //var projectItem = project.AddFileToProject(file); } // Redo parse. try { StreamReader sr = new StreamReader(class_file_path); string code = sr.ReadToEnd(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[class_file_path] = tree; } catch (Exception) { } // Redo find class. try { var tree = trees[class_file_path]; var save = class_file_path; class_file_path = null; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); throw new Exception(); } } } } } catch { } } // Look for enter or exit method for symbol. MethodDeclarationSyntax found_member = null; var ctl = CtrlKeyState.GetStateForView(grammar_view).Enabled; var capitalized_member_name = ""; if (visitor) { capitalized_member_name = "Visit" + capitalized_symbol_name; } else if (ctl) { capitalized_member_name = "Exit" + capitalized_symbol_name; } else { capitalized_member_name = "Enter" + capitalized_symbol_name; } var capitalized_grammar_name = Capitalized(grammar_name); try { foreach (var fc in found_class) { foreach (var me in fc.Members) { var method_member = me as MethodDeclarationSyntax; if (method_member == null) { continue; } if (method_member.Identifier.ValueText.ToLower() == capitalized_member_name.ToLower()) { found_member = method_member; throw new Exception(); } } } } catch { } if (found_member == null) { if (!global::Options.POptions.GetBoolean("GenerateVisitorListener")) { return; } // Find point for edit. var fc = found_class.First(); var here = fc.OpenBraceToken; var spn = here.FullSpan; var end = spn.End; IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); if (vstv == null) { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { return; } ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot; var res = vstv.GetBuffer(out IVsTextLines ppBuffer); var nss = new SnapshotSpan(cc, spn.End + 1, 0); var txt_span = nss.Span; int line_number; int colum_number; vstv.GetLineAndColumn(txt_span.Start, out line_number, out colum_number); res = ppBuffer.CreateEditPoint(line_number, colum_number, out object ppEditPoint); EditPoint editPoint = ppEditPoint as EditPoint; // Create class. string member = visitor ? $@" public override Result {capitalized_member_name}([NotNull] {capitalized_grammar_name}Parser.{capitalized_symbol_name}Context context) {{ return VisitChildren(context); }} " : $@" public override void {capitalized_member_name}({capitalized_grammar_name}Parser.{capitalized_symbol_name}Context context) {{ base.{capitalized_member_name}(context); }} "; editPoint.Insert(member); // Redo parse. try { vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); if (vstv == null) { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } var text_buffer = vstv.GetITextBuffer(); var code = text_buffer.GetBufferText(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[class_file_path] = tree; } catch (Exception) { } // Redo find class. try { var tree = trees[class_file_path]; var save = class_file_path; class_file_path = null; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); class_file_path = save; throw new Exception(); } } } } } catch { } try { foreach (var fcc in found_class) { foreach (var me in fcc.Members) { var method_member = me as MethodDeclarationSyntax; if (method_member == null) { continue; } if (method_member.Identifier.ValueText.ToLower() == capitalized_member_name.ToLower()) { found_member = method_member; throw new Exception(); } } } } catch { } } { // Open to this line in editor. IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { return; } int line_number; int colum_number; var txt_span = found_member.Identifier.Span; vstv.GetLineAndColumn(txt_span.Start, out line_number, out colum_number); // Create new span in the appropriate view. ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot; SnapshotSpan ss = new SnapshotSpan(cc, txt_span.Start, txt_span.Length); SnapshotPoint sp = ss.Start; // Put cursor on symbol. wpftv.Caret.MoveTo(sp); // This sets cursor, bot does not center. // Center on cursor. //wpftv.Caret.EnsureVisible(); // This works, sort of. It moves the scroll bar, but it does not CENTER! Does not really work! if (line_number > 0) { vstv.CenterLines(line_number - 1, 2); } else { vstv.CenterLines(line_number, 1); } return; } } catch (Exception exception) { Logger.Log.Notify(exception.StackTrace); } }
public static async Task <SpriteDocument> FromFile(string fileName) { string root = ProjectHelpers.GetProjectFolder(fileName); string folder = Path.GetDirectoryName(root); if (folder == null || root == null) { return(null); } XDocument doc = null; string contents = await FileHelpers.ReadAllTextRetry(fileName); try { doc = XDocument.Parse(contents); } catch (XmlException) { return(null); } XElement element = null; var imageFiles = from f in doc.Descendants("file") select ProjectHelpers.ToAbsoluteFilePath(f.Value, root, folder); SpriteDocument sprite = new SpriteDocument(fileName, imageFiles.ToArray()); element = doc.Descendants("optimize").FirstOrDefault(); if (element != null) { sprite.Optimize = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("orientation").FirstOrDefault(); if (element != null) { sprite.IsVertical = element.Value.Equals("vertical", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("runOnBuild").FirstOrDefault(); if (element != null) { sprite.RunOnBuild = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("outputType").FirstOrDefault(); if (element != null) { sprite.FileExtension = element.Value; } element = doc.Descendants("fullPathForIdentifierName").FirstOrDefault(); if (element != null) { sprite.UseFullPathForIdentifierName = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("useAbsoluteUrl").FirstOrDefault(); if (element != null) { sprite.UseAbsoluteUrl = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase); } element = doc.Descendants("outputDirectoryForCss").FirstOrDefault(); if (element != null) { sprite.CssOutputDirectory = element.Value; } element = doc.Descendants("outputDirectoryForLess").FirstOrDefault(); if (element != null) { sprite.LessOutputDirectory = element.Value; } element = doc.Descendants("outputDirectoryForScss").FirstOrDefault(); if (element != null) { sprite.ScssOutputDirectory = element.Value; } return(sprite); }
protected override async Task ExecuteAsync(object parameter) { var location = parameter as string; // switch from one active project to another if (_projectManager.ActiveProject != null && !string.IsNullOrEmpty(location)) { if (_projectManager.ActiveProject.Location == location) { return; } } try { if (string.IsNullOrWhiteSpace(location) || !File.Exists(location)) { // file was moved or deleted if (_recentlyUsedItemsService.Items.Items.Any(_ => _.Name == location)) { // would you like to locate it? location = await ProjectHelpers.LocateMissingProjectAsync(location); if (string.IsNullOrEmpty(location)) { // user canceled locating a project return; } } // open an existing project else { var result = await _openFileService.DetermineFileAsync(new DetermineOpenFileContext { Filter = "Cyberpunk 2077 Project | *.cpmodproj|Witcher 3 Project (*.w3modproj)|*.w3modproj", IsMultiSelect = false, Title = "Please select the WolvenKit project you would like to open." }); if (!result.Result) { // user canceled locating a project return; } location = result.FileName; } } // one last check if (!File.Exists(location)) { return; } RibbonViewModel.GlobalRibbonVM.StartScreenShown = false; RibbonViewModel.GlobalRibbonVM.BackstageIsOpen = false; // if a valid location has been set //using (_pleaseWaitService.PushInScope()) { await _projectManager.LoadAsync(location); switch (Path.GetExtension(location)) { case ".w3modproj": await _tw3Controller.HandleStartup().ContinueWith(t => { _notificationService.Success( "Project " + Path.GetFileNameWithoutExtension(location) + " loaded!"); }, TaskContinuationOptions.OnlyOnRanToCompletion); break; case ".cpmodproj": await _cp77Controller.HandleStartup().ContinueWith( t => { _notificationService.Success("Project " + Path.GetFileNameWithoutExtension(location) + " loaded!"); }, TaskContinuationOptions.OnlyOnRanToCompletion); break; default: break; } //TODO:ORC //if (StaticReferences.GlobalShell != null) //{ // StaticReferences.GlobalShell.SetCurrentValue(System.Windows.Window.TitleProperty, Path.GetFileNameWithoutExtension(location)); //} StaticReferencesVM.GlobalStatusBar.CurrentProject = Path.GetFileNameWithoutExtension(location); } } catch (Exception) { // TODO: Are we intentionally swallowing this? //Log.Error(ex, "Failed to open file"); } }