protected virtual string GenerateError(IVsGeneratorProgress pGenerateProgress, Exception ex)
        {
            var Message = GetMessage(ex);

            pGenerateProgress.GeneratorError(0, 4, Message, 0xFFFFFFFF, 0xFFFFFFFF);

            return Message;
        }
Exemple #2
0
 private static void GenerateErrorInternal(IVsGeneratorProgress pGenerateProgress, Exception exception)
 {
     if (!TestingUtility.IsRunningFromUnitTest)
     {
         ThreadHelper.ThrowIfNotOnUIThread();
     }
     pGenerateProgress?.GeneratorError(0, 0, exception.Message, 0, 0);
     Trace.WriteLine(exception);
 }
 protected void Error(string message, int line, int column)
 {
     try
     {
         IVsGeneratorProgress progress = codeGeneratorProgress;
         if (progress != null)
         {
             progress.GeneratorError(false, 1, message, line, column);
         }
     }
     catch { }
 }
        private static void HandleException(
            Exception e,
            IVsGeneratorProgress pGenerateProgress,
            IntPtr[] rgbOutputFileContents,
            out uint pcbOutput)
        {
            rgbOutputFileContents[0] = string.Empty.ConvertToIntPtr(out pcbOutput);
            pGenerateProgress.GeneratorError(e);

            Trace.WriteLine("Unable to generate code");
            Trace.WriteLine(e);
        }
Exemple #5
0
        public int Generate(
            string wszInputFilePath,
            string bstrInputFileContents,
            string wszDefaultNamespace,
            IntPtr[] rgbOutputFileContents,
            out uint pcbOutput,
            IVsGeneratorProgress pGenerateProgress)
        {
            try
            {
                pGenerateProgress.Progress(5);

                var codeGenerator = Factory.Create(
                    wszDefaultNamespace,
                    bstrInputFileContents,
                    wszInputFilePath,
                    supportedLanguage,
                    CodeGenerator);

                var code = codeGenerator.GenerateCode(new ProgressReporter(pGenerateProgress));
                if (string.IsNullOrWhiteSpace(code))
                {
                    pcbOutput = 0;
                    return(1);
                }

                if (supportedLanguage == SupportedLanguage.VisualBasic && converter != null)
                {
                    Trace.WriteLine(Environment.NewLine);
                    Trace.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                    Trace.WriteLine("!!! EXPERIMENTAL - Attempting to convert C# code to Visual Basic !!!");
                    Trace.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                    Trace.WriteLine(Environment.NewLine);

                    code = converter
                           .ConvertAsync(code)
                           .GetAwaiter()
                           .GetResult();
                }

                rgbOutputFileContents[0] = code.ConvertToIntPtr(out pcbOutput);
                pGenerateProgress.Progress(100);
            }
            catch (Exception e)
            {
                pGenerateProgress.GeneratorError(e);
                Trace.WriteLine("Unable to generate code");
                Trace.WriteLine(e);
                throw;
            }

            return(0);
        }
Exemple #6
0
        protected virtual void GeneratorErrorCallback(bool warning, int level, string message, int line, int column)
        {
            IVsGeneratorProgress progress1 = this.CodeGeneratorProgress;

            if (progress1 != null)
            {
                if (line > 0)
                {
                    line--;
                }
                progress1.GeneratorError(warning, level, message, line, column);
            }
        }
Exemple #7
0
        /// <summary>
        /// method that will communicate an error via the shell callback mechanism.
        /// </summary>
        /// <param name="warning">true if this is a warning</param>
        /// <param name="level">level or severity</param>
        /// <param name="message">text displayed to the user</param>
        /// <param name="line">line number of error/warning</param>
        /// <param name="column">column number of error/warning</param>
        protected virtual void GeneratorErrorCallback(
            bool warning,
            int level,
            string message,
            int line,
            int column)
        {
            IVsGeneratorProgress progress = CodeGeneratorProgress;

            if (progress != null)
            {
                progress.GeneratorError(warning, level, message, line, column);
            }
        }
Exemple #8
0
        protected override string GenerateError(IVsGeneratorProgress pGenerateProgress, Exception ex)
        {
            if (ex == null)
            {
                VisualStudioTracer.Assert(generationResult != null, "no reneration result found");
                VisualStudioTracer.Assert(!generationResult.Success, "generation result is not a failure");

                foreach (var error in generationResult.Errors)
                {
                    pGenerateProgress.GeneratorError(0, 4, error.Message, (uint)error.Line, (uint)error.LinePosition);
                }

                return(string.Join(Environment.NewLine, generationResult.Errors.Select(e => e.Message)));
            }
            return(base.GenerateError(pGenerateProgress, ex));
        }
        protected override string GenerateError(IVsGeneratorProgress pGenerateProgress, Exception ex)
        {
            if (ex == null)
            {
                VisualStudioTracer.Assert(generationResult != null, "no reneration result found");
                VisualStudioTracer.Assert(!generationResult.Success, "generation result is not a failure");

                foreach (var error in generationResult.Errors)
                {
                    pGenerateProgress.GeneratorError(0, 4, error.Message, (uint) error.Line, (uint) error.LinePosition);
                }

                return string.Join(Environment.NewLine, generationResult.Errors.Select(e => e.Message));
            }
            return base.GenerateError(pGenerateProgress, ex);
        }
        bool ReportMessage(IVsGeneratorProgress p, string m, int line = 0, int column = 0, bool error = true)
        {
            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                if (null != p)
                {
                    p.GeneratorError((error) ? 0 : 1, 1, m, (uint)line, (uint)column);
                    return(true);
                }
            }
            catch
            {
            }

            return(false);
        }
 public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
 {
     var sw = new Stopwatch();
       sw.Start();
       var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
       var workspace = componentModel.GetService<VisualStudioWorkspace>();
       var docIds = workspace.CurrentSolution.GetDocumentIdsWithFilePath(wszInputFilePath);
       var project = FindContainingProject(workspace.CurrentSolution.Projects.ToList(), wszInputFilePath);
       var compilationResult = HbsCompiler.Compile(bstrInputFileContents, wszDefaultNamespace, Path.GetFileNameWithoutExtension(wszInputFilePath), project);
       sw.Stop();
       if (compilationResult.Item2.Any())
       {
     foreach(var error in compilationResult.Item2)
       pGenerateProgress.GeneratorError(0, 1, error.Message, (uint)error.Line-1, (uint)error.Column-1);
       }
       byte[] bytes = Encoding.UTF8.GetBytes(compilationResult.Item1);
       rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(bytes.Length);
       Marshal.Copy(bytes, 0, rgbOutputFileContents[0], bytes.Length);
       pcbOutput = (uint)bytes.Length;
       return compilationResult.Item2.Any()?VSConstants.E_FAIL:VSConstants.S_OK;
 }
Exemple #12
0
        protected override byte[] Generate(string inputFilePath, string inputFileContents, string defaultNamespace, IVsGeneratorProgress progressCallback)
        {
            var codeProvider = CodeDomProvider.CreateProvider("CSharp");

            var compileUnit = new CodeCompileUnit();

            compileUnit.ReferencedAssemblies.Add(typeof(string).Assembly.Location);

            var parser      = new RecSharpParser();
            var parseResult = parser.TryParse(inputFileContents);

            if (parseResult.Field0 < 0)
            {
                var errorInfo = parser.GetMaxRollbackPosAndNames();
                var location  = parser.ParsingSource.GetSourceLine(errorInfo.Field0);
                var lineInfo  = location.StartLineColumn;
                var startPos  = location.StartPos;

                progressCallback.GeneratorError(0, 0, $"Error parsing source, expected {string.Join(" or ", errorInfo.Field1)}", (uint)lineInfo.Field0, (uint)(errorInfo.Field0 - startPos));
                return(new byte[0]);
            }

            foreach (var reference in parseResult.Field1.References)
            {
                compileUnit.ReferencedAssemblies.Add(reference.Path);
            }

            foreach (var nmspace in parseResult.Field1.Namespaces)
            {
                var builder = new NamespaceDeclarationBuilder(nmspace);
                compileUnit.Namespaces.Add(builder.Build());
            }

            var codeStringBuilder = new StringBuilder();
            var codeWriter        = new StringWriter(codeStringBuilder);

            codeProvider.GenerateCodeFromCompileUnit(compileUnit, codeWriter, null);

            return(Encoding.UTF8.GetBytes(codeStringBuilder.ToString()));
        }
        public int Generate(string inputFilePath, string inputFileContents, string defaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress generateProgress)
        {
            BeforeCodeGenerated();

            string generatedContent;
            Action <SingleFileGeneratorError> onError =
                delegate(SingleFileGeneratorError error)
            {
                generateProgress.GeneratorError(0, 4, error.Message, (uint)(error.Line + 1), (uint)(error.LinePosition + 1));
            };

            Project project = GetProjectForSourceFile(Dte, inputFilePath);
            bool    successfulGeneration = false;

            if (project == null)
            {
                onError(new SingleFileGeneratorError("Unable to detect current project."));
                generatedContent = "";
            }
            else
            {
                successfulGeneration = GenerateInternal(inputFilePath, inputFileContents, project, defaultNamespace, onError, out generatedContent);
            }

            byte[] bytes = Encoding.UTF8.GetBytes(generatedContent);

            byte[] utf8BOM      = new byte[] { 0xEF, 0xBB, 0xBF };
            int    outputLength = utf8BOM.Length + bytes.Length;

            byte[] output = new byte[outputLength];
            Array.Copy(utf8BOM, 0, output, 0, utf8BOM.Length);
            Array.Copy(bytes, 0, output, utf8BOM.Length, bytes.Length);
            rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
            Marshal.Copy(output, 0, rgbOutputFileContents[0], outputLength);
            pcbOutput = (uint)outputLength;

            AfterCodeGenerated(!successfulGeneration);

            return(VSConstants.S_OK);
        }
        protected override byte[] Generate(string inputFilePath, string inputFileContents, string defaultNamespace, IVsGeneratorProgress progressCallback)
        {
            var codeProvider = CodeDomProvider.CreateProvider("CSharp");

            var compileUnit = new CodeCompileUnit();
            compileUnit.ReferencedAssemblies.Add(typeof(string).Assembly.Location);

            var parser = new RecSharpParser();
            var parseResult = parser.TryParse(inputFileContents);

            if (parseResult.Field0 < 0)
            {
                var errorInfo = parser.GetMaxRollbackPosAndNames();
                var location = parser.ParsingSource.GetSourceLine(errorInfo.Field0);
                var lineInfo = location.StartLineColumn;
                var startPos = location.StartPos;

                progressCallback.GeneratorError(0, 0, $"Error parsing source, expected {string.Join(" or ", errorInfo.Field1)}", (uint)lineInfo.Field0, (uint)(errorInfo.Field0 - startPos));
                return new byte[0];
            }

            foreach (var reference in parseResult.Field1.References)
            {
                compileUnit.ReferencedAssemblies.Add(reference.Path);
            }

            foreach (var nmspace in parseResult.Field1.Namespaces)
            {
                var builder = new NamespaceDeclarationBuilder(nmspace);
                compileUnit.Namespaces.Add(builder.Build());
            }

            var codeStringBuilder = new StringBuilder();
            var codeWriter = new StringWriter(codeStringBuilder);

            codeProvider.GenerateCodeFromCompileUnit(compileUnit, codeWriter, null);

            return Encoding.UTF8.GetBytes(codeStringBuilder.ToString());
        }
Exemple #15
0
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace,
                            IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            using (var ms = new MemoryStream())
            {
                MatchResult <char, AstNode> result;

                using (var tw = new StreamWriter(ms, Encoding.UTF8))
                {
                    pGenerateProgress.Progress(0, 1);
                    result = CSharpShell.Process(wszInputFilePath, bstrInputFileContents, tw, wszDefaultNamespace);
                    pGenerateProgress.Progress(1, 1);
                }

                if (result.Success)
                {
                    byte[] bytes = ms.ToArray();
                    rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(bytes.Length);
                    Marshal.Copy(bytes, 0, rgbOutputFileContents[0], bytes.Length);
                    pcbOutput = (uint)bytes.Length;

                    return(VSConstants.S_OK);
                }
                else
                {
                    int num, offset;
                    var line = result.MatchState.GetLine(result.ErrorIndex, out num, out offset);

                    pGenerateProgress.GeneratorError(0, 0, result.Error, (uint)(num - 1), (uint)offset);

                    rgbOutputFileContents = null;
                    pcbOutput             = 0;

                    return(VSConstants.E_FAIL);
                }
            }
        }
Exemple #16
0
        private void WriteError(
            IVsGeneratorProgress progress,
            string code,
            Exception exception,
            AphidExpression expression = null)
        {
            Tuple <int, int> pos = null;

            if (expression?.Index > -1)
            {
                pos = TokenHelper.GetIndexPosition(
                    code,
                    expression.Index);
            }

            progress.GeneratorError(
                0,
                0,
                exception.ToString(),
                pos == null || pos.Item1 == -1 ? 0xffffffffu : (uint)pos.Item1,
                pos == null || pos.Item2 == -1 ? 0xffffffffu : (uint)pos.Item2);
        }
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, 
            IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            using (var ms = new MemoryStream())
            {
                MatchResult<char, AstNode> result;

                using (var tw = new StreamWriter(ms, Encoding.UTF8))
                {
                    pGenerateProgress.Progress(0, 1);
                    result = CSharpShell.Process(wszInputFilePath, bstrInputFileContents, tw, wszDefaultNamespace);
                    pGenerateProgress.Progress(1, 1);
                }

                if (result.Success)
                {
                    byte[] bytes = ms.ToArray();
                    rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(bytes.Length);
                    Marshal.Copy(bytes, 0, rgbOutputFileContents[0], bytes.Length);
                    pcbOutput = (uint)bytes.Length;

                    return VSConstants.S_OK;
                }
                else
                {
                    int num, offset;
                    var line = result.MatchState.GetLine(result.ErrorIndex, out num, out offset);
                    pGenerateProgress.GeneratorError(0, 0, result.Error, (uint)(num - 1), (uint)offset);

                    rgbOutputFileContents = null;
                    pcbOutput = 0;

                    return VSConstants.E_FAIL;
                }
            }
        }
        void ReportErrorToVS(IVsGeneratorProgress generatorProgress, Severity severity, object context, string message, object[] args)
        {
            int    line = 0, col = 1;
            string message2 = message.Localized(args);

            if (context is LNode)
            {
                var range = ((LNode)context).Range;
                line = range.Start.Line;
                col  = range.Start.PosInLine;
            }
            else if (context is SourcePos)
            {
                line = ((SourcePos)context).Line;
                col  = ((SourcePos)context).PosInLine;
            }
            else if (context is SourceRange)
            {
                line = ((SourceRange)context).Start.Line;
                col  = ((SourceRange)context).Start.PosInLine;
            }
            else if (context is Pred)
            {
                line = ((Pred)context).Basis.Range.Start.Line;
                col  = ((Pred)context).Basis.Range.Start.PosInLine;
            }
            else
            {
                message2 = MessageSink.LocationString(context) + ": " + message2;
            }

            bool subwarning = severity < Severity.Warning;
            int  n          = subwarning ? 2 : severity == Severity.Warning ? 1 : 0;

            generatorProgress.GeneratorError(n, 0u, message2, (uint)line - 1u, (uint)col - 1u);
        }
 public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
 {
     rgbOutputFileContents[0] = IntPtr.Zero;
     pcbOutput = 0;
     string fileName = "";
     try
     {
         if (wszInputFilePath != null)
         {
             fileName = Path.GetFileName(wszInputFilePath);
         }
         bool error = false;
         string className = null;
         if (wszInputFilePath != null)
         {
             className = Path.GetFileNameWithoutExtension(wszInputFilePath).Trim();
             int length = 0;
             while (length < className.Length && (char.IsLetterOrDigit(className[length]) || className[length] == '_'))
             {
                 ++length;
             }
             className = className.Substring(0, length);
         }
         OsloErrorReporter errorReporter = new OsloErrorReporter();
         OsloCodeGeneratorInfo info = null;
         try
         {
             info = new OsloCodeGeneratorInfo(wszInputFilePath, new StringReader(bstrInputFileContents), true, errorReporter);
             if (info.ClassName == null && !string.IsNullOrEmpty(className))
             {
                 info.ClassName = className;
             }
             if (info.NamespaceName == null)
             {
                 info.NamespaceName = wszDefaultNamespace;
             }
         }
         catch (Exception ex)
         {
             error = true;
             info = null;
             pGenerateProgress.GeneratorError(0, 0, string.Format("[OsloCodeGeneratorGenerator] Could not process input file: {0}. Error: {1}", fileName, ex.ToString()), 0, 0);
         }
         MemoryStream memory = new MemoryStream();
         if (info != null && !error)
         {
             using (TemplatePrinter printer = new TemplatePrinter(new StreamWriter(memory, Encoding.UTF8)))
             {
                 info.GenerateTemporaryCode(printer, (uint current, uint total) => pGenerateProgress.Progress(current, total));
                 printer.ForcedWriteLine();
                 printer.Flush();
             }
         }
         memory.Flush();
         byte[] contents = new byte[memory.Length];
         memory.Position = 0;
         memory.Read(contents, 0, contents.Length);
         rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(contents.Length);
         Marshal.Copy(contents, 0, rgbOutputFileContents[0], contents.Length);
         pcbOutput = (uint)contents.Length;
         foreach (var errorMessage in errorReporter.Errors)
         {
             int lineNumber = errorMessage.LineNumber - 1;
             int columnNumber = errorMessage.ColumnNumber - 1;
             if (lineNumber < 0) lineNumber = 0;
             if (columnNumber < 0) columnNumber = 0;
             if (errorMessage.Level == ErrorLevel.Error)
             {
                 error = true;
                 pGenerateProgress.GeneratorError(0, 0, errorMessage.ToString(), (uint)lineNumber, (uint)columnNumber);
             }
             else
             {
                 pGenerateProgress.GeneratorError(1, 0, errorMessage.ToString(), (uint)lineNumber, (uint)columnNumber);
             }
         }
         if (!error)
         {
             return Microsoft.VisualStudio.VSConstants.S_OK;
         }
     }
     catch(Exception ex)
     {
         pGenerateProgress.GeneratorError(0, 0, string.Format("[OsloCodeGeneratorGenerator] Could not process input file: {0}. Error: {1}", fileName, ex.ToString()), 0, 0);
     }
     return Microsoft.VisualStudio.VSConstants.E_FAIL;
 }
Exemple #20
0
		private static MessageSinkFromDelegate ToMessageSink(IVsGeneratorProgress progressCallback)
		{
			var sink = new MessageSinkFromDelegate(
				(Symbol severity, object context, string message, object[] args) =>
				{
					if (MessageSink.GetSeverity(severity) >= MessageSink.GetSeverity(MessageSink.Warning))
					{
						int line = 0, col = 0;
						if (context is LNode)
						{
							var range = ((LNode)context).Range;
							line = range.Begin.Line;
							col = range.Begin.PosInLine;
						}
						progressCallback.GeneratorError(severity == MessageSink.Warning ? 1 : 0, 0u,
							Localize.From(message, args), (uint)line - 1u, (uint)col);
					}
					else
						MessageSink.Console.Write(severity, context, message, args);
				});
			return sink;
		}
Exemple #21
0
		void ReportErrorToVS(IVsGeneratorProgress generatorProgress, Severity severity, object context, string message, object[] args)
		{
			int line = 0, col = 1;
			string message2 = message.Localized(args);
			if (context is LNode) {
				var range = ((LNode)context).Range;
				line = range.Start.Line;
				col = range.Start.PosInLine;
			} else if (context is SourcePos) {
				line = ((SourcePos)context).Line;
				col = ((SourcePos)context).PosInLine;
			} else if (context is SourceRange) {
				line = ((SourceRange)context).Start.Line;
				col = ((SourceRange)context).Start.PosInLine;
			} else if (context is Pred) {
				line = ((Pred)context).Basis.Range.Start.Line;
				col = ((Pred)context).Basis.Range.Start.PosInLine;
			} else
				message2 = MessageSink.LocationString(context) + ": " + message2;

			bool subwarning = severity < Severity.Warning;
			int n = subwarning ? 2 : severity == Severity.Warning ? 1 : 0;
			generatorProgress.GeneratorError(n, 0u, message2, (uint)line - 1u, (uint)col - 1u);
		}
Exemple #22
0
        public int Generate(string wszInputFilePath, string bstrInputFileContents,
                            string wszDefaultNamespace, IntPtr[] rgbOutputFileContents,
                            out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            pcbOutput = 0;
            string sFile = Path.GetTempFileName();

            try
            {
                StringBuilder cmdLine = new StringBuilder();
                cmdLine.Append(QuoteArgument(wszInputFilePath) + " //gencs " + QuoteArgument(sFile));
                if (!string.IsNullOrEmpty(wszDefaultNamespace))
                {
                    cmdLine.Append(" //namespace " + QuoteArgument(wszDefaultNamespace));
                }

                try
                {
                    XmlDocument x = new XmlDocument();
                    x.LoadXml(bstrInputFileContents);
                    var n = x.CreateNavigator();
                    XmlProcessingInstruction proci = ((XmlProcessingInstruction)x.SelectSingleNode("//processing-instruction('xsharper-args')"));
                    if (proci != null)
                    {
                        cmdLine.Append(" ");
                        cmdLine.Append(proci.Value.Trim());
                    }
                }
                catch
                {
                }



                ProcessStartInfo pi = new ProcessStartInfo("xsharper", cmdLine.ToString());
                pi.RedirectStandardError = true;
                pi.ErrorDialog           = true;
                pi.UseShellExecute       = false;
                pi.WindowStyle           = ProcessWindowStyle.Hidden;

                StringBuilder sb = new StringBuilder();
                Process       p  = new Process();
                p.StartInfo = pi;

                p.ErrorDataReceived += (f, x) =>
                {
                    lock (sb)
                        sb.AppendLine(x.Data);
                };
                if (p.Start())
                {
                    p.BeginErrorReadLine();
                    p.WaitForExit();

                    int exitCode = p.ExitCode;
                    p.Close();

                    if (exitCode == 0)
                    {
                        byte[] bytes  = File.ReadAllBytes(sFile);
                        int    length = bytes.Length;
                        rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(length);
                        Marshal.Copy(bytes, 0, rgbOutputFileContents[0], length);
                        pcbOutput = (uint)length;
                        return(VSConstants.S_OK);
                    }
                    else
                    {
                        throw new ApplicationException(sb.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                pGenerateProgress.GeneratorError(0, 20, ex.Message, 0xffffffff, 0xffffffff);
                pcbOutput = 0;
            }
            finally
            {
                File.Delete(sFile);
            }
            return(VSConstants.E_FAIL);
        }
 private static void GenerateErrorInternal(IVsGeneratorProgress pGenerateProgress, Exception exception)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     pGenerateProgress?.GeneratorError(0, 0, exception.Message, 0, 0);
     Trace.WriteLine(exception);
 }
Exemple #24
0
        int IVsSingleFileGenerator.Generate(string InputFilePath, string InputFileContents, string DefaultNamespace, IntPtr[] OutputFileContents, out uint Output, IVsGeneratorProgress GenerateProgress)
        {
            byte[] bOutputFileContents = GenerateCode(InputFileContents, InputFilePath, GenerateProgress);
            string szOutputFilePath    = InputFilePath.Replace(Path.GetExtension(InputFilePath), _Ext);

            if (bOutputFileContents != null)
            {
                uint          nItemId;
                uint          nMinItemId;
                VSADDRESULT[] oAddResult  = new VSADDRESULT[1];
                FileStream    oOutputFile = File.Create(szOutputFilePath);

                oOutputFile.Write(bOutputFileContents, 0, bOutputFileContents.Length);
                oOutputFile.Close( );

                nItemId = GetProjectItemId(InputFilePath);

                if (VsProject.AddItem(nItemId, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, szOutputFilePath, 1, new string[] { szOutputFilePath }, IntPtr.Zero, oAddResult) == VSConstants.S_OK)
                {
                    nMinItemId = GetProjectItemId(szOutputFilePath);

                    Microsoft.Build.Evaluation.ProjectItem oItem    = GetProjectItem(InputFilePath);
                    Microsoft.Build.Evaluation.ProjectItem oMinItem = GetProjectItem(szOutputFilePath);

                    VsBuildPropertyStorage.SetItemAttribute(nItemId, "LastGenOutput", Path.GetFileName(szOutputFilePath));

                    VsBuildPropertyStorage.SetItemAttribute(nMinItemId, "AutoGen", "True");
                    VsBuildPropertyStorage.SetItemAttribute(nMinItemId, "DesignTime", "True");
                    VsBuildPropertyStorage.SetItemAttribute(nMinItemId, "DependentUpon", Path.GetFileName(InputFilePath));

                    switch (OptionPage.CompileTargetType)
                    {
                    case CompileTargetType.Default:
                    {
                        oItem.Xml.Condition    = string.Empty;
                        oMinItem.Xml.Condition = string.Empty;
                    }
                    break;

                    case CompileTargetType.Mixed:
                    {
                        oItem.Xml.Condition    = " '$(Configuration)' == 'Debug' ";
                        oMinItem.Xml.Condition = " '$(Configuration)' == 'Release' ";
                    }
                    break;
                    }

                    switch (OptionPage.BuildActionType)
                    {
                    case BuildActionType.Copy:
                    {
                        oMinItem.ItemType = oItem.ItemType;
                    }
                    break;

                    case BuildActionType.Custom:
                    {
                        oItem.ItemType    = OptionPage.OriginalBuildAction;
                        oMinItem.ItemType = OptionPage.MinifiedBuildAction;
                    }
                    break;
                    }


                    //////////////////////

                    Application.Windows.Item(EnvDTE.Constants.vsWindowKindSolutionExplorer).Activate( );
                    Application.ToolWindows.SolutionExplorer.GetItem(string.Format("{0}\\{1}", Path.GetFileNameWithoutExtension(Application.Solution.FullName), ProjectName.EvaluatedValue)).Select(vsUISelectionType.vsUISelectionTypeSelect);

                    BuildProject.Save( );

                    Application.ExecuteCommand("Project.UnloadProject");
                    Application.ExecuteCommand("Project.ReloadProject");

                    Application.Windows.Item(EnvDTE.Constants.vsWindowKindSolutionExplorer).Activate( );
                    Application.ToolWindows.SolutionExplorer.GetItem(string.Format("{0}\\{1}\\{2}", Path.GetFileNameWithoutExtension(Application.Solution.FullName), ProjectName.EvaluatedValue, oItem.EvaluatedInclude)).Select(vsUISelectionType.vsUISelectionTypeSelect);
                }
                else
                {
                    GenerateProgress.GeneratorError(1, 1, "VSMinifier can't add minified file to project...", 0, 0);
                }
            }

            Output = 0;

            return(VSConstants.E_FAIL);
        }
Exemple #25
0
 /// <summary>
 /// Returns the error information to the project system.
 /// </summary>
 /// <param name="message">The text message of the error to be displayed to the user.</param>
 /// <param name="line">The zero-based line number that indicates where in the source file the error occurred.</param>
 /// <param name="column">The one-based column number that indicates where in the source file the error occurred.</param>
 protected void GenerateError(string message, int line, int column)
 {
     progress?.GeneratorError(0, 0, message, (uint)line, (uint)column);
 }
Exemple #26
0
 public void ReportError(string message)
 {
     progress.GeneratorError(0, 0, message, 0, 0);
     failed = true;
 }
Exemple #27
0
        public int Generate(string wszInputFilePath, string bstrInputFileContents,
            string wszDefaultNamespace, IntPtr[] rgbOutputFileContents,
            out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            pcbOutput = 0;
            string sFile = Path.GetTempFileName();
            try
            {
                StringBuilder cmdLine=new StringBuilder();
                cmdLine.Append(QuoteArgument(wszInputFilePath) + " //gencs " + QuoteArgument(sFile));
                if (!string.IsNullOrEmpty(wszDefaultNamespace))
                    cmdLine.Append(" //namespace " + QuoteArgument(wszDefaultNamespace));

                try
                {
                    XmlDocument x = new XmlDocument();
                    x.LoadXml(bstrInputFileContents);
                    var n=x.CreateNavigator();
                    XmlProcessingInstruction proci=((XmlProcessingInstruction)x.SelectSingleNode("//processing-instruction('xsharper-args')"));
                    if (proci != null)
                    {
                        cmdLine.Append(" ");
                        cmdLine.Append(proci.Value.Trim());
                    }
                }
                catch
                {

                }

                ProcessStartInfo pi=new ProcessStartInfo("xsharper", cmdLine.ToString());
                pi.RedirectStandardError = true;
                pi.ErrorDialog = true;
                pi.UseShellExecute = false;
                pi.WindowStyle = ProcessWindowStyle.Hidden;

                StringBuilder sb=new StringBuilder();
                Process p=new Process();
                p.StartInfo = pi;

                p.ErrorDataReceived += (f,x)=>
                    {
                        lock (sb)
                            sb.AppendLine(x.Data);
                    };
                if (p.Start())
                {
                    p.BeginErrorReadLine();
                    p.WaitForExit();

                    int exitCode = p.ExitCode;
                    p.Close();

                    if (exitCode == 0)
                    {
                        byte[] bytes = File.ReadAllBytes(sFile);
                        int length = bytes.Length;
                        rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(length);
                        Marshal.Copy(bytes, 0, rgbOutputFileContents[0], length);
                        pcbOutput = (uint) length;
                        return VSConstants.S_OK;
                    }
                    else
                    {
                        throw new ApplicationException(sb.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                pGenerateProgress.GeneratorError(0, 20, ex.Message, 0xffffffff, 0xffffffff);
                pcbOutput = 0;
            }
            finally
            {
                File.Delete(sFile);
            }
            return VSConstants.E_FAIL;
        }
Exemple #28
0
        public int Generate(string wszInputFilePath, string bstrInputFileContents,
                            string wszDefaultNamespace, IntPtr[] rgbOutputFileContents,
                            out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            pcbOutput = 0;
            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                pGenerateProgress.Progress(0, 4);
                var hasErrors = false;
                using (var stm = new MemoryStream())
                {
                    EbnfDocument ebnf = null;
                    try
                    {
                        ebnf = EbnfDocument.ReadFrom(wszInputFilePath);
                    }
                    catch (ExpectingException ee)
                    {
                        hasErrors = true;
                        ThreadHelper.ThrowIfNotOnUIThread();
                        pGenerateProgress.GeneratorError(0, 0, "Error parsing the EBNF: " + ee.Message, (uint)ee.Line - 1, (uint)ee.Column - 1);
                    }
                    ThreadHelper.ThrowIfNotOnUIThread();
                    pGenerateProgress.Progress(1, 4);
                    foreach (var msg in ebnf.Validate(false))
                    {
                        switch (msg.ErrorLevel)
                        {
                        case EbnfErrorLevel.Error:
                            ThreadHelper.ThrowIfNotOnUIThread();
                            pGenerateProgress.GeneratorError(0, 0, "EBNF " + msg.Message, (uint)msg.Line - 1, (uint)msg.Column - 1);
                            hasErrors = true;
                            break;

                        case EbnfErrorLevel.Warning:
                            ThreadHelper.ThrowIfNotOnUIThread();
                            pGenerateProgress.GeneratorError(1, 0, "EBNF " + msg.Message, (uint)msg.Line - 1, (uint)msg.Column - 1);
                            break;
                        }
                    }
                    ThreadHelper.ThrowIfNotOnUIThread();
                    pGenerateProgress.Progress(3, 4);
                    var cfg = ebnf.ToCfg();
                    foreach (var msg in cfg.PrepareLL1(false))
                    {
                        switch (msg.ErrorLevel)
                        {
                        case CfgErrorLevel.Error:
                            ThreadHelper.ThrowIfNotOnUIThread();
                            pGenerateProgress.GeneratorError(0, 0, "CFG " + msg.Message, 0, 0);
                            hasErrors = true;
                            break;

                        case CfgErrorLevel.Warning:
                            ThreadHelper.ThrowIfNotOnUIThread();
                            pGenerateProgress.GeneratorError(1, 0, "CFG " + msg.Message, 0, 0);
                            break;
                        }
                    }
                    if (!hasErrors)
                    {
                        var sw = new StreamWriter(stm);
                        LLCodeGenerator.WriteParserAndGeneratorClassesTo(ebnf, cfg, wszDefaultNamespace, null, Path.GetFileNameWithoutExtension(wszInputFilePath), "cs", sw);
                        sw.Flush();
                        int length = (int)stm.Length;
                        rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(length);
                        Marshal.Copy(stm.GetBuffer(), 0, rgbOutputFileContents[0], length);
                        pcbOutput = (uint)length;
                    }
                    ThreadHelper.ThrowIfNotOnUIThread();
                    pGenerateProgress.Progress(4, 4);
                }
            }
            catch (Exception ex)
            {
                string s      = string.Concat("/* ", ex.Message, " */");
                byte[] b      = Encoding.UTF8.GetBytes(s);
                int    length = b.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(length);
                Marshal.Copy(b, 0, rgbOutputFileContents[0], length);
                pcbOutput = (uint)length;
            }
            return(VSConstants.S_OK);
        }
Exemple #29
0
 public void Warn(int line, int column, string message) =>
 progress.GeneratorError(1, 0, message, (uint)line, (uint)column);
Exemple #30
0
        static void _DumpErrors(string errp, IVsGeneratorProgress progress)
        {
            var    tr    = new StringReader(errp);
            var    found = false;
            string line  = null;

            while (null != (line = tr.ReadLine()))
            {
                var i = line.IndexOf('(');
                if (0 > i)
                {
                    continue;
                }
                var fn = line.Substring(0, i);
                if (-1 < fn.IndexOfAny(Path.GetInvalidPathChars()))
                {
                    continue;
                }
                var i2 = line.IndexOf(')', i + 1);
                if (0 > i2)
                {
                    continue;
                }
                if (line.Length <= i2 || ':' != line[i2 + 1])
                {
                    continue;
                }
                var s  = line.Substring(i + 1, i2 - i - 2);
                var sa = s.Split(',');
                if (2 != sa.Length)
                {
                    continue;
                }
                int l = 0;
                int c = 0;
                if (!int.TryParse(sa[0].Trim(), out l) || !int.TryParse(sa[1].Trim(), out c))
                {
                    continue;
                }
                var i3 = line.IndexOf(' ', i2 + 1);
                if (0 > i3)
                {
                    continue;
                }
                var el        = line.Substring(i2 + 1, i3 - (i2 + 1));
                int isWarning = 0;
                if (el.Equals(":warning", StringComparison.Ordinal))
                {
                    isWarning = 1;
                }
                else if (!el.Equals(":error", StringComparison.Ordinal))
                {
                    continue;
                }
                var i4 = line.IndexOf(':', i3 + 1);
                if (0 > i4)
                {
                    continue;
                }
                var ec = 0;
                s = line.Substring(i3 + 1, i4 - (i3 + 1));
                if (!int.TryParse(s, out ec))
                {
                    continue;
                }
                s     = line.Substring(i4 + 1);
                found = true;
                if (null != progress)
                {
                    progress.GeneratorError(isWarning, 0, s, unchecked ((uint)l - 1), unchecked ((uint)c));
                }
            }
            if (!found)
            {
                progress.GeneratorError(0, 0, errp, 0u, 0u);
            }
        }
Exemple #31
0
        protected byte[] GenerateCode(
            IVsGeneratorProgress progress,
            string file,
            string contents,
            string ns)
        {
            try
            {
                // Parse options from Xml source doc
                Options = new Options(contents);

                // read all sprocs from the database
                var sigs = new SqlSignatures(Options);

                // Create the code generator
                var g = new Generators.SqlServer.Generator(
                        Options,
                        sigs);

                // Setup code generation options
                var options = new CodeGeneratorOptions
                {
                    BlankLinesBetweenMembers = false,
                    BracingStyle = "C",
                    ElseOnClosing = false,
                    IndentString = "\t"
                };

                // Create the output
                var output = new StringWriter();

                GetProvider()
                    .GenerateCodeFromNamespace(
                    g.GenerateCode(ns),
                    output,
                    options);
                output.Close();
                return Encoding.UTF8.GetBytes(output.ToString());

            }
            catch (LineNumberedException e)
            {
                progress.GeneratorError(false, 1, e.Message, e.Line, e.Col);
                return null;
            }
            catch (Exception e)
            {
                progress.GeneratorError(false, 1, e.ToString(), 0, 0);
                return null;
            }
        }
Exemple #32
0
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace,
                            IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            // SwitchDomainForRazorEngine();
            byte[] resultBytes;
            try
            {
                var model = new RazorModel();
                //set file name and namespace for model using
                model.DefaultNameSpace = wszDefaultNamespace;
                var info = new FileInfo(wszInputFilePath);
                if (info.Exists)
                {
                    model.FileName = info.Name;
                }
                int                  iFound;
                uint                 itemId;
                ProjectItem          item;
                VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];

                // obtain a reference to the current project as an IVsProject type
                IVsProject vsProject = VsHelper.ToVsProject(project);
                // this locates, and returns a handle to our source file, as a ProjectItem
                vsProject.IsDocumentInProject(wszInputFilePath, out iFound, pdwPriority, out itemId);

                // if our source file was found in the project (which it should have been)
                if (iFound != 0 && itemId != 0)
                {
                    IServiceProvider oleSp;
                    vsProject.GetItemContext(itemId, out oleSp);
                    if (oleSp != null)
                    {
                        ServiceProvider sp = new ServiceProvider(oleSp);
                        // convert our handle to a ProjectItem
                        item = sp.GetService(typeof(ProjectItem)) as ProjectItem;
                    }
                    else
                    {
                        throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");
                    }
                }
                else
                {
                    throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");
                }

                var generator = new RazorGenerator(wszInputFilePath, bstrInputFileContents, model);
                generator.Init();
                //get extension from header file
                if (!string.IsNullOrEmpty(generator.RazorTemplate.OutPutExtension))
                {
                    _extenstion = generator.RazorTemplate.OutPutExtension;
                }
                //generate code
                var result = generator.Render();
                resultBytes = Encoding.UTF8.GetBytes(result);
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint)outputLength;
                return(VSConstants.S_OK);
            }
            catch (TemplateCompilationException tex)
            {
                //Display error in result template
                foreach (var compilerError in tex.CompilerErrors)
                {
                    pGenerateProgress.GeneratorError(0, 1, compilerError.ErrorText, (uint)compilerError.Line,
                                                     (uint)compilerError.Column);
                }
                var message = MRazorUtil.GetError(tex);
                resultBytes = Encoding.UTF8.GetBytes(message);
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint)outputLength;
                return(VSConstants.S_FALSE);// Change to E_Fail will display error in error list
            }
            catch (Exception ex)
            {
                var messageBuilder = new StringBuilder(ex.Message);
                messageBuilder.AppendLine();
                if (ex.Source != null)
                {
                    messageBuilder.Append(ex.Source);
                }
                messageBuilder.Append(ex.StackTrace);
                if (ex.InnerException != null)
                {
                    messageBuilder.AppendLine();
                    messageBuilder.Append(ex.InnerException.Message + ex.InnerException.StackTrace);
                }
                resultBytes = Encoding.UTF8.GetBytes(messageBuilder.ToString());
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint)outputLength;
                return(VSConstants.S_FALSE);// Change to E_Fail will display error in error list
            }
            //finally
            //{
            //    //unload domain for unload dll loaded from InputDllFolder
            //    if (_domain != null) AppDomain.Unload(_domain);
            //}
        }
        public int Generate(string wszInputFilePath,
                            string bstrInputFileContents, string wszDefaultNamespace,
                            IntPtr[] rgbOutputFileContents, out uint pcbOutput,
                            IVsGeneratorProgress pGenerateProgress)
        {
            // Redirect console output
            StringWriter writer = new StringWriter();

            Console.SetOut(writer);



            // Execute coco
            string[] args = GetCocoArguments(wszInputFilePath, wszDefaultNamespace);
            Console.Write("Console Arguments: ");
            foreach (var s in args)
            {
                Console.Write(s + " ");
            }
            Console.WriteLine();

            int retVal = Coco.Main(args);

            // If success, add parser and scanner
            if (retVal == 0)
            {
                // Get the associated Projetect Item
                ProjectItem pi = GetProjectItem();

                // Check if there are already scanner and parser project items
                bool hasScanner = false;
                bool hasParser  = false;
                bool hasTrace   = false;

                foreach (ProjectItem sub in pi.ProjectItems)
                {
                    if (sub.Name.EndsWith("Scanner.cs"))
                    {
                        hasScanner = true;
                    }
                    if (sub.Name.EndsWith("Parser.cs"))
                    {
                        hasParser = true;
                    }
                    if (sub.Name.EndsWith("trace.txt"))
                    {
                        hasTrace = true;
                    }
                }

                if (!hasParser)
                {
                    pi.ProjectItems.AddFromFile(
                        Path.Combine(Path.GetDirectoryName(wszInputFilePath),
                                     "Parser.cs"));
                }

                if (!hasScanner)
                {
                    pi.ProjectItems.AddFromFile(
                        Path.Combine(Path.GetDirectoryName(wszInputFilePath),
                                     "Scanner.cs"));
                }

                if (!hasTrace
                    &&
                    File.Exists(
                        Path.Combine(Path.GetDirectoryName(wszInputFilePath),
                                     "trace.txt")))
                {
                    pi.ProjectItems.AddFromFile(
                        Path.Combine(Path.GetDirectoryName(wszInputFilePath),
                                     "trace.txt"));
                }
            }
            else
            {
                // Parse console output for error messages
                string          errorText = writer.ToString();
                MatchCollection mc        = Regex.Matches(errorText,
                                                          "-- line ([0-9]*) col ([0-9]*)\\: (.*)");

                // Generate error messages
                foreach (Match match in mc)
                {
                    pGenerateProgress.GeneratorError(0, 1, match.Groups[3].Value,
                                                     uint.Parse(match.Groups[1].Value) - 1,
                                                     uint.Parse(match.Groups[2].Value) - 1);
                }
            }

            //Get the Encoding used by the writer. We're getting the WindowsCodePage encoding,
            //which may not work with all languages
            Encoding enc = Encoding.GetEncoding(writer.Encoding.WindowsCodePage);

            //Get the preamble (byte-order mark) for our encoding
            byte[] preamble       = enc.GetPreamble();
            int    preambleLength = preamble.Length;

            //Convert the writer contents to a byte array
            byte[] body = enc.GetBytes(writer.ToString());

            //Prepend the preamble to body (store result in resized preamble array)
            Array.Resize(ref preamble, preambleLength + body.Length);
            Array.Copy(body, 0, preamble, preambleLength, body.Length);

            int outputLength = preamble.Length;

            rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
            Marshal.Copy(preamble, 0, rgbOutputFileContents[0], outputLength);
            pcbOutput = (uint)outputLength;

            return((retVal == 0) ? VSConstants.S_OK : VSConstants.S_FALSE);
        }
        /// <summary>
        /// Method that will communicate a warning via the shell callback mechanism
        /// </summary>
        /// <param name="level">Level or severity</param>
        /// <param name="message">Text displayed to the user</param>
        /// <param name="line">Line number of warning</param>
        /// <param name="column">Column number of warning</param>
        protected virtual void GeneratorWarning(uint level, string message, uint line, uint column)
        {
            IVsGeneratorProgress progress = CodeGeneratorProgress;

            progress?.GeneratorError(1, level, message, line, column);
        }
        public int Generate(string inputFilePath, string inputFileContents, string defaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress generateProgress)
        {
            BeforeCodeGenerated();

            string generatedContent;
            Action<SingleFileGeneratorError> onError = 
                delegate(SingleFileGeneratorError error)
                    {
                        generateProgress.GeneratorError(0, 4, error.Message, (uint)(error.Line + 1), (uint)(error.LinePosition + 1));
                    };

            Project project = GetProjectForSourceFile(Dte, inputFilePath);
            bool successfulGeneration = false;
            if (project == null)
            {
                onError(new SingleFileGeneratorError("Unable to detect current project."));
                generatedContent = "";
            }
            else
            {
                successfulGeneration = GenerateInternal(inputFilePath, inputFileContents, project, defaultNamespace, onError, out generatedContent);
            }

            byte[] bytes = Encoding.UTF8.GetBytes(generatedContent);

            byte[] utf8BOM = new byte[] { 0xEF, 0xBB, 0xBF };
            int outputLength = utf8BOM.Length + bytes.Length;
            byte[] output = new byte[outputLength];
            Array.Copy(utf8BOM, 0, output, 0, utf8BOM.Length);
            Array.Copy(bytes, 0, output, utf8BOM.Length, bytes.Length);
            rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
            Marshal.Copy(output, 0, rgbOutputFileContents[0], outputLength);
            pcbOutput = (uint)outputLength;

            AfterCodeGenerated(!successfulGeneration);

            return VSConstants.S_OK;
        }
Exemple #36
0
        /// <summary>
        /// Implements the IVsSingleFileGenerator.Generate method.
        /// Executes the transformation and returns the newly generated output file, whenever a custom tool is loaded, or the input file is saved
        /// </summary>
        /// <param name="wszInputFilePath">The full path of the input file. May be a null reference (Nothing in Visual Basic) in future releases of Visual Studio, so generators should not rely on this value</param>
        /// <param name="bstrInputFileContents">The contents of the input file. This is either a UNICODE BSTR (if the input file is text) or a binary BSTR (if the input file is binary). If the input file is a text file, the project system automatically converts the BSTR to UNICODE</param>
        /// <param name="wszDefaultNamespace">This parameter is meaningful only for custom tools that generate code. It represents the namespace into which the generated code will be placed. If the parameter is not a null reference (Nothing in Visual Basic) and not empty, the custom tool can use the following syntax to enclose the generated code</param>
        /// <param name="rgbOutputFileContents">[out] Returns an array of bytes to be written to the generated file. You must include UNICODE or UTF-8 signature bytes in the returned byte array, as this is a raw stream. The memory for rgbOutputFileContents must be allocated using the .NET Framework call, System.Runtime.InteropServices.AllocCoTaskMem, or the equivalent Win32 system call, CoTaskMemAlloc. The project system is responsible for freeing this memory</param>
        /// <param name="pcbOutput">[out] Returns the count of bytes in the rgbOutputFileContent array</param>
        /// <param name="pGenerateProgress">A reference to the IVsGeneratorProgress interface through which the generator can report its progress to the project system</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns E_FAIL</returns>
        int IVsSingleFileGenerator.Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            if (bstrInputFileContents == null)
            {
                debugOut.Flush();
                throw new ArgumentNullException(bstrInputFileContents);
            }

            if (wszInputFilePath == null)
            {
                throw new ArgumentNullException(bstrInputFileContents);
            }

            string InputFilePath  = wszInputFilePath;
            string tempPath       = Path.GetTempPath();
            string outputFilePath = Path.Combine(tempPath, Path.ChangeExtension(Path.GetFileName(wszInputFilePath), ".cs"));
            string FileNameSpace  = wszDefaultNamespace;
            string errorFilePath  = Path.Combine(tempPath, Path.ChangeExtension(Path.GetFileName(wszInputFilePath), ".error.txt"));

            try
            {
                var    splitedNameSpec = wszDefaultNamespace.Split(',');
                string languageName    = splitedNameSpec.Length > 0 ? splitedNameSpec[0] : "CS";
                string namespaceName   = splitedNameSpec.Length > 1 ? splitedNameSpec[1] : "";
                string namespaceParam  = string.IsNullOrEmpty(namespaceName) ? "" : string.Format("/namespace:{0}", namespaceName);

                var StartInfo = new ProcessStartInfo();

                StartInfo.CreateNoWindow         = false;
                StartInfo.UseShellExecute        = false;
                StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                StartInfo.StandardErrorEncoding  = Encoding.UTF8;
                StartInfo.StandardOutputEncoding = Encoding.UTF8;
                StartInfo.RedirectStandardError  = true;
                StartInfo.RedirectStandardInput  = true;
                StartInfo.RedirectStandardOutput = true;
                StartInfo.FileName  = Path.Combine(GetMSSDKPath(), "xsd.exe");
                StartInfo.Arguments = string.Format(" {0} /o:{1} /classes /language:{2} {3}", InputFilePath, tempPath, languageName, namespaceParam);

                var m_RunningProcess = new Process();
                m_RunningProcess.StartInfo = StartInfo;

                m_RunningProcess.Start();
                var output = m_RunningProcess.StandardOutput.ReadToEnd();
                if (m_RunningProcess.ExitCode != 0)
                {
                    pGenerateProgress.GeneratorError(0, 0, output, 0, 0);
                    throw new Exception(string.Format("XSD process returned error {0}, {1}", m_RunningProcess.ExitCode, output));
                }

                using (var outFileStream = new FileStream(outputFilePath, FileMode.Open))
                {
                    if (outFileStream == null || outFileStream.Length == 0)
                    {
                        rgbOutputFileContents = null;
                        throw new Exception("Opening output file is failed");
                    }
                    byte[] buffer   = new byte[outFileStream.Length];
                    int    readSize = outFileStream.Read(buffer, 0, buffer.Length);
                    if (readSize != buffer.Length)
                    {
                        rgbOutputFileContents = null;
                        throw new Exception("Writing file is failed");
                    }

                    int outputLength = buffer.Length;
                    rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                    Marshal.Copy(buffer, 0, rgbOutputFileContents[0], outputLength);
                    pcbOutput = (uint)outputLength;
                }

                if (File.Exists(errorFilePath))
                {
                    File.Delete(errorFilePath);
                }

                return(VSConstants.S_OK);
            }
            catch (Exception exp)
            {
                rgbOutputFileContents = null;
                pcbOutput             = 0;

                pGenerateProgress.GeneratorError(0, 0, exp.Message, 0, 0);

                using (var outFileStream = new FileStream(errorFilePath, FileMode.Create))
                {
                    var bytes = Encoding.UTF8.GetBytes(exp.Message);
                    outFileStream.Write(bytes, 0, bytes.Length);
                }

                DebugOutput.ShowMessage("Error while compiling: " + exp.Message);

                return(VSConstants.E_FAIL);
            }
        }
 public static void ReportWarning(IVsGeneratorProgress progress, string message, uint line = 0xFFFFFFFF, uint column = 0xFFFFFFFF)
 {
     if (progress != null)
         progress.GeneratorError(1, 0, message, line, column);
 }
Exemple #38
0
        public int Generate(string wszInputFilePath, string bstrInputFileContents,
                            string wszDefaultNamespace, IntPtr[] rgbOutputFileContents,
                            out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            string outputfile = null;
            string log        = "";

            try
            {
                if (null == _site)
                {
                    throw new InvalidOperationException("The Lexly custom tool can only be used in a design time environment. Consider using Lexly as a pre-build step instead.");
                }
                wszInputFilePath = Path.GetFullPath(wszInputFilePath);
                var item = _FindItem(wszInputFilePath);
                if (null == item)
                {
                    throw new ApplicationException("Design time environment project item fetch failed.");
                }
                foreach (EnvDTE.ProjectItem childItem in item.ProjectItems)
                {
                    childItem.Delete();
                }

                var dir  = Path.GetDirectoryName(wszInputFilePath);
                var lang = VSUtility.GetProjectLanguageFromItem(item);
                if (null == lang)
                {
                    lang = "cs";
                }
                outputfile = Path.Combine(dir, Path.GetFileNameWithoutExtension(wszInputFilePath) + "." + lang);
                var args = new List <string>();
                args.Add(wszInputFilePath);
                args.Add("/output");
                args.Add(outputfile);
                if (0 != string.Compare("cs", lang, StringComparison.InvariantCultureIgnoreCase))
                {
                    args.Add("/language");
                    args.Add(lang);
                }
                if (!string.IsNullOrWhiteSpace(wszDefaultNamespace))
                {
                    args.Add("/namespace");
                    args.Add(wszDefaultNamespace);
                }

                var sw = new StringWriter();
                var ec = global::Lexly.Program.Run(args.ToArray(), TextReader.Null, TextWriter.Null, sw);
                log = sw.ToString();

                var isSuccess = 0 == ec;
                if (isSuccess)
                {
                    EnvDTE.ProjectItem outitm = item.ProjectItems.AddFromFile(outputfile);
                }
                else
                {
                    pGenerateProgress.GeneratorError(0, 0, "Lexly returned error code: " + ec.ToString(), unchecked ((uint)-1), unchecked ((uint)-1));
                }
            }
            catch (Exception ex)
            {
                pGenerateProgress.GeneratorError(0, 0, "Lexly custom tool failed with: " + ex.Message, unchecked ((uint)-1), unchecked ((uint)-1));
                log += "Lexly custom tool failed with: " + ex.Message;
            }
            finally
            {
                try
                {
                    pGenerateProgress.Progress(2, 2);
                }
                catch { }
            }
            // have used streams here in the past to scale, but even for huge items, this is faster!
            // most likely due to the lack of extra copies (memory/array resizing)
            byte[] bytes  = Encoding.UTF8.GetBytes(log);
            int    length = bytes.Length;

            rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(length);
            Marshal.Copy(bytes, 0, rgbOutputFileContents[0], length);
            pcbOutput = (uint)length;
            return(VSConstants.S_OK);
        }
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace,
            IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
           // SwitchDomainForRazorEngine();
            byte[] resultBytes;
            try
            {
                var model = new RazorModel();
                //set file name and namespace for model using
                model.DefaultNameSpace = wszDefaultNamespace;
                var info=new FileInfo(wszInputFilePath);
                if (info.Exists)
                {
                    model.FileName = info.Name;
                }
                int iFound;
                uint itemId;
                ProjectItem item;
                VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];

                // obtain a reference to the current project as an IVsProject type
                IVsProject vsProject = VsHelper.ToVsProject(project);
                // this locates, and returns a handle to our source file, as a ProjectItem
                vsProject.IsDocumentInProject(wszInputFilePath, out iFound, pdwPriority, out itemId);

                // if our source file was found in the project (which it should have been)
                if (iFound != 0 && itemId != 0)
                {
                    IServiceProvider oleSp;
                    vsProject.GetItemContext(itemId, out oleSp);
                    if (oleSp != null)
                    {
                        ServiceProvider sp = new ServiceProvider(oleSp);
                        // convert our handle to a ProjectItem
                        item = sp.GetService(typeof(ProjectItem)) as ProjectItem;
                    }
                    else
                        throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");
                }
                else
                    throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");

                var generator = new RazorGenerator(wszInputFilePath,bstrInputFileContents, model);
                generator.Init();
                //get extension from header file
                if (!string.IsNullOrEmpty(generator.RazorTemplate.OutPutExtension))
                {
                    _extenstion = generator.RazorTemplate.OutPutExtension;
                }
                //generate code
                var result = generator.Render();
                resultBytes = Encoding.UTF8.GetBytes(result);
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint) outputLength;
                return VSConstants.S_OK;
            }
            catch (TemplateCompilationException tex)
            {
                //Display error in result template
                foreach (var compilerError in tex.CompilerErrors)
                {
                    pGenerateProgress.GeneratorError(0, 1, compilerError.ErrorText, (uint) compilerError.Line,
                        (uint) compilerError.Column);
                }
                var message = MRazorUtil.GetError(tex);
                resultBytes = Encoding.UTF8.GetBytes(message);
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint) outputLength;
                return VSConstants.S_FALSE;// Change to E_Fail will display error in error list
            }
            catch (Exception ex)
            {
                var messageBuilder =new StringBuilder( ex.Message);
                messageBuilder.AppendLine();
                if (ex.Source != null) messageBuilder.Append(ex.Source);
                messageBuilder.Append(ex.StackTrace);
                if (ex.InnerException != null)
                {
                    messageBuilder.AppendLine();
                    messageBuilder.Append(ex.InnerException.Message + ex.InnerException.StackTrace);
                }
                resultBytes = Encoding.UTF8.GetBytes(messageBuilder.ToString());
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint) outputLength;
                return VSConstants.S_FALSE;// Change to E_Fail will display error in error list
            }
            //finally
            //{
            //    //unload domain for unload dll loaded from InputDllFolder
            //    if (_domain != null) AppDomain.Unload(_domain);
            //}

        }
 public void GenerateError(string errorMessage, int sourceFileLineNumber, int sourceFileColumnNumber)
 {
     vsProgress.GeneratorError(0, 0, errorMessage, (uint)sourceFileLineNumber, (uint)sourceFileColumnNumber);
 }
Exemple #41
0
        private byte[] GenerateCode(string InputFileContent, string InputFilePath, IVsGeneratorProgress GenerateProgress)
        {
            bool   bDo = false;
            string OutputFileContent = InputFileContent;

            string[] szFiles;
            string   szInputContent  = string.Empty;
            string   szOutputContent = string.Empty;

            _Ext = Path.GetExtension(InputFilePath);

            if (_Ext.Equals(Consts.CSSExt))
            {
                _Ext = OptionPage.CSSExt;
                bDo  = true;
            }

            if (_Ext.Equals(Consts.JSExt))
            {
                _Ext = OptionPage.JSExt;
                bDo  = true;
            }

            if (bDo)
            {
                if (InputFileContent.StartsWith("// FILE LIST"))
                {
                    szFiles = GetFileList(InputFileContent);
                }
                else
                {
                    szFiles = new string[] { string.Empty };
                }

                foreach (string szFile in szFiles)
                {
                    if (szFile == string.Empty)
                    {
                        szInputContent = InputFileContent;
                    }
                    else
                    {
                        string szPath = Path.Combine(Path.GetDirectoryName(InputFilePath), szFile.Replace("//", string.Empty).Trim( ));

                        szInputContent = File.ReadAllText(szPath);
                    }

                    if (_Ext == OptionPage.JSExt)
                    {
                        switch (OptionPage.JSEngine)
                        {
                        case JSEngineType.MicrosoftAjaxMinifier:
                        {
                            Minifier     oMinifier = new Minifier( );
                            CodeSettings oSettings = new CodeSettings( );

                            oSettings.LocalRenaming                 = OptionPage.JSMsLocalRename;
                            oSettings.OutputMode                    = OptionPage.JSMsOutputMode;
                            oSettings.PreserveImportantComments     = OptionPage.JSMsPreserveImportantComments;
                            oSettings.RemoveUnneededCode            = OptionPage.JSMsRemoveUnneededCode;
                            oSettings.PreserveFunctionNames         = OptionPage.JSMsPreserveFunctionNames;
                            oSettings.RemoveFunctionExpressionNames = OptionPage.JSMsRemoveFunctionExpressionNames;

                            szOutputContent += oMinifier.MinifyJavaScript(szInputContent, oSettings);
                        }
                        break;

                        case JSEngineType.GoogleClosureCompiler:
                        {
                            GoogleClosure oCompiler = new GoogleClosure( );

                            szOutputContent += oCompiler.Compress(szInputContent, OptionPage.JSGCompilationLevel);
                        }
                        break;

                        case JSEngineType.YUICompressor:
                        {
                            JavaScriptCompressor oCompressor = new JavaScriptCompressor( );

                            oCompressor.CompressionType = CompressionType.Standard;

                            oCompressor.DisableOptimizations  = OptionPage.JSYDisableOptimizations;
                            oCompressor.PreserveAllSemicolons = OptionPage.JSYPreserveAllSemicolons;
                            oCompressor.ObfuscateJavascript   = OptionPage.JSYObfuscateJavascript;

                            szOutputContent += oCompressor.Compress(szInputContent);
                        }
                        break;
                        }
                    }

                    if (_Ext == OptionPage.CSSExt)
                    {
                        switch (OptionPage.CSSEngine)
                        {
                        case CSSEngineType.MicrosoftAjaxMinifier:
                        {
                            Minifier    oMinifier = new Minifier( );
                            CssSettings oSettings = new CssSettings( );

                            oSettings.ColorNames        = OptionPage.CSSMsColorNames;
                            oSettings.CommentMode       = OptionPage.CSSMsCommentMode;
                            oSettings.CssType           = OptionPage.CSSMsCssType;
                            oSettings.MinifyExpressions = OptionPage.CSSMsMinifyExpressions;
                            oSettings.OutputMode        = OptionPage.CSSMsOutputMode;

                            szOutputContent += oMinifier.MinifyStyleSheet(szInputContent, oSettings);
                        }
                        break;

                        case CSSEngineType.YUICompressor:
                        {
                            CssCompressor oCompressor = new CssCompressor( );

                            oCompressor.CompressionType = CompressionType.Standard;

                            oCompressor.RemoveComments = OptionPage.CSSYRemoveComments;

                            szOutputContent += oCompressor.Compress(szInputContent);
                        }
                        break;
                        }
                    }


                    szOutputContent += Environment.NewLine;

                    OutputFileContent = szOutputContent;
                }

                return(Encoding.UTF8.GetBytes(OutputFileContent));
            }
            else
            {
                GenerateProgress.GeneratorError(1, 1, "VSMinifier can handle only js and css files...", 0, 0);

                return(null);
            }
        }
Exemple #42
0
        public int Generate(string wszInputFilePath, string bstrInputFileContents,
                            string wszDefaultNamespace, IntPtr[] rgbOutputFileContents,
                            out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            string outp = "";
            string errp = "";

            try
            {
                if (null == _site)
                {
                    throw new InvalidOperationException("The Rolex custom tool can only be used in a design time environment. Consider using Rolex as a pre-build step instead.");
                }
                wszInputFilePath = Path.GetFullPath(wszInputFilePath);
                var item = _FindItem(wszInputFilePath);
                if (null == item)
                {
                    throw new ApplicationException("Design time environment project item fetch failed.");
                }
                if (0 != string.Compare("cs", VSUtility.GetProjectLanguageFromItem(item), StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new NotSupportedException("The Rolex generator only supports C# projects");
                }
                var dir         = Path.GetDirectoryName(wszInputFilePath);
                var scannerFile = Path.GetFileNameWithoutExtension(wszInputFilePath) + ".cs";
                var proj        = item.ContainingProject;
                var pil         = new List <object>(proj.ProjectItems.Count);
                foreach (EnvDTE.ProjectItem pi in proj.ProjectItems)
                {
                    if (pi != item)
                    {
                        pil.Add(pi);
                    }
                }
                var genShared = !VSUtility.HasClassOrStruct(pil, wszDefaultNamespace, "Token");
                pGenerateProgress.Progress(0, 2);
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName        = "rolex";
                psi.CreateNoWindow  = true;
                psi.UseShellExecute = false;
                psi.Arguments       = "\"" + wszInputFilePath.Replace("\"", "\"\"") + "\"";
                psi.Arguments      += " /output -";//\"" + Path.Combine(dir, scannerFile).Replace("\"", "\"\"") + "\"";
                psi.Arguments      += " /namespace \"" + wszDefaultNamespace + "\"";
                if (!genShared)
                {
                    psi.Arguments += " /noshared";
                }
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardError  = true;

                var isSuccess = false;
                using (var proc = new Process())
                {
                    proc.StartInfo = psi;
                    proc.Start();
                    outp = proc.StandardOutput.ReadToEnd().TrimEnd();
                    errp = proc.StandardError.ReadToEnd().TrimEnd();
                    if (!proc.HasExited)
                    {
                        proc.WaitForExit();
                    }
                    isSuccess = 0 == proc.ExitCode;
                }

                var outputPath = Path.Combine(dir, scannerFile);
                pGenerateProgress.Progress(1, 2);
                if (!isSuccess)
                {
                    _DumpErrors(errp, pGenerateProgress);
                    //pGenerateProgress.GeneratorError(0, 0, "Rolex failed: " + errp, unchecked((uint)-1), unchecked((uint)-1));
                }
                else
                {
                    // have used streams here in the past to scale, but even for huge items, this is faster!
                    // most likely due to the lack of extra copies (memory/array resizing)
                    byte[] bytes  = Encoding.UTF8.GetBytes(outp);
                    int    length = bytes.Length;
                    rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(length);
                    Marshal.Copy(bytes, 0, rgbOutputFileContents[0], length);
                    pcbOutput = (uint)length;
                    return(VSConstants.S_OK);
                }
            }
            catch (Exception ex)
            {
                pGenerateProgress.GeneratorError(0, 0, "Rolex custom tool failed with: " + ex.Message, unchecked ((uint)-1), unchecked ((uint)-1));
                errp += "Rolex custom tool failed with: " + ex.Message;
            }
            finally
            {
                try
                {
                    pGenerateProgress.Progress(2, 2);
                }
                catch { }
            }

            // have used streams here in the past to scale, but even for huge items, this is faster!
            // most likely due to the lack of extra copies (memory/array resizing)
            pcbOutput = (uint)0;
            return(VSConstants.S_OK);
        }
Exemple #43
0
        public int Generate(
            string wszInputFilePath,
            string bstrInputFileContents,
            string wszDefaultNamespace,
            IntPtr[] rgbOutputFileContents,
            out uint pcbOutput,
            IVsGeneratorProgress pGenerateProgress)
        {
            try
            {
                pGenerateProgress.Progress(5);

                var options = GetOptionsFromOptionsPage();

                string baseDirectory = Path.GetDirectoryName(wszInputFilePath);
                string apiName       = Path.GetFileNameWithoutExtension(wszInputFilePath);

                if (options.UseUserOptions)
                {
                    string optionsPath = Path.Combine(baseDirectory, $"{apiName}.RestEaseOptions");

                    if (!File.Exists(optionsPath))
                    {
                        try
                        {
                            string json = _optionsFactory.Serialize(options);
                            File.WriteAllText(optionsPath, json);
                        }
                        catch
                        {
                            Trace.WriteLine($"Unable to write custom settings file '{optionsPath}'.");
                        }
                    }
                    else
                    {
                        try
                        {
                            var restEaseUserOptions = _optionsFactory.Deserialize(File.ReadAllText(optionsPath));
                            options.MergeWith(restEaseUserOptions);
                        }
                        catch
                        {
                            Trace.WriteLine($"Unable to read custom settings file '{optionsPath}'.");
                        }
                    }
                }

                Trace.WriteLine("Generating Interface and Models");
                var settings = AutoMapperUtils.Instance.Mapper.Map <GeneratorSettings>(options);
                settings.SingleFile = true;
                settings.Namespace  = wszDefaultNamespace;
                settings.ApiName    = apiName;

                //var settings = new GeneratorSettings
                //{
                //    SingleFile = true,
                //    Namespace = wszDefaultNamespace,
                //    ApiName = apiName,
                //    ArrayType = options.ArrayType,
                //    UseDateTimeOffset = options.UseDateTimeOffset,
                //    MethodReturnType = options.MethodReturnType,
                //    AppendAsync = options.AppendAsync,
                //    GenerateFormUrlEncodedExtensionMethods = options.GenerateFormUrlEncodedExtensionMethods,
                //    GenerateApplicationOctetStreamExtensionMethods = options.GenerateApplicationOctetStreamExtensionMethods,
                //    GenerateMultipartFormDataExtensionMethods = options.GenerateMultipartFormDataExtensionMethods,
                //    MultipartFormDataFileType = options.MultipartFormDataFileType,
                //    ApplicationOctetStreamType = options.ApplicationOctetStreamType,
                //    ApiNamespace = options.ApiNamespace,
                //    ModelsNamespace = options.ModelsNamespace,
                //    ReturnObjectFromMethodWhenResponseIsDefinedButNoModelIsSpecified = options.ReturnObjectFromMethodWhenResponseIsDefinedButNoModelIsSpecified,
                //    PreferredContentType = options.PreferredContentType,
                //    ForceContentTypeToApplicationJson = options.ForceContentTypeToApplicationJson,
                //    UseOperationIdAsMethodName = options.UseOperationIdAsMethodName,
                //    PreferredSecurityDefinitionType = options.PreferredSecurityDefinitionType,
                //    GeneratePrimitivePropertiesAsNullableForOpenApi20 = options.GeneratePrimitivePropertiesAsNullableForOpenApi20
                //};
                var result = _generator.FromStream(File.OpenRead(wszInputFilePath), settings, out var diagnostic);

                if (options.FailOnOpenApiErrors && diagnostic.Errors.Any())
                {
                    var errorMessages = string.Join(" | ", diagnostic.Errors.Select(e => JsonSerializer.Serialize(e)));
                    Trace.WriteLine($"OpenApi Errors: {errorMessages}");

                    pcbOutput = 0;
                    return(1);
                }

                pGenerateProgress.Progress(90);
                string code = result.First().Content;

                rgbOutputFileContents[0] = code.ConvertToIntPtr(out pcbOutput);
                pGenerateProgress.Progress(100);

                Trace.WriteLine("All done");
            }
            catch (Exception e)
            {
                pGenerateProgress.GeneratorError(e);
                Trace.WriteLine("Unable to generate code");
                Trace.WriteLine(e);
                throw;
            }

            return(0);
        }