public int Generate(
            string wszInputFilePath,
            string bstrInputFileContents,
            string wszDefaultNamespace,
            IntPtr[] rgbOutputFileContents,
            out uint pcbOutput,
            IVsGeneratorProgress pGenerateProgress)
        {
            pcbOutput = 0;
            try
            {
                pGenerateProgress.Progress(5);

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

                var code = codeGenerator.GenerateCode(new ProgressReporter(pGenerateProgress));
                if (string.IsNullOrWhiteSpace(code))
                {
                    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);
            }
            catch (NotSupportedException e)
            {
                MessageBox.Show(e.Message, "Not Supported");
                HandleException(e, pGenerateProgress, rgbOutputFileContents, out pcbOutput);
            }
            catch (Exception e)
            {
                HandleException(e, pGenerateProgress, rgbOutputFileContents, out pcbOutput);
                throw;
            }
            finally
            {
                pGenerateProgress.Progress(100);
            }

            return(0);
        }
        /// <summary>
        /// Generate the code from the custom tool.
        /// </summary>
        /// <param name="wszInputFilePath">The name of the input file.</param>
        /// <param name="bstrInputFileContents">The contents of the input file.</param>
        /// <param name="wszDefaultNamespace">The namespace FluidTrade.ClientGenerator the generated code.</param>
        /// <param name="pbstrOutputFileContents">The generated code.</param>
        /// <param name="pbstrOutputFileContentSize">The buffer size of the generated code.</param>
        /// <param name="pGenerateProgress">An indication of the tools progress.</param>
        /// <returns>0 indicates the tool handled the command.</returns>
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace,
                            IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            // Throw an execption if there is nothing to process.
            if (bstrInputFileContents == null)
            {
                throw new ArgumentNullException(bstrInputFileContents);
            }

            // This schema describes the data model that is to be generated.
            DataModelSchema dataModelSchema = new DataModelSchema(bstrInputFileContents);

            dataModelSchema.GeneratorType   = typeof(ClientGenerator);
            dataModelSchema.TargetNamespace = wszDefaultNamespace;

            // This is where all the work is done to translate the input schema into the CodeDOM for the data model and the CodeDOM
            // for the interface to that data model.
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            codeCompileUnit.Namespaces.Add(new Namespace(dataModelSchema));
            CodeNamespace emptyNamespace = new CodeNamespace();

            emptyNamespace.Types.Add(new FluidTrade.Core.TargetInterface.TargetInterface(dataModelSchema));
            emptyNamespace.Types.Add(new FluidTrade.ClientGenerator.DataSetClientClass.DataSetClientClass(dataModelSchema));
            codeCompileUnit.Namespaces.Add(emptyNamespace);

            // If a handler was provided for the generation of the code, then call it with an update.
            if (pGenerateProgress != null)
            {
                pGenerateProgress.Progress(50, 100);
            }

            // This will generate the target source code in the language described by the CodeDOM provider.
            StringWriter stringWriter = new StringWriter();

            //There is no elegant way to generate preprocessor directives through CodeDom.  All the solutions
            //require string replacement after the fact.  So not elegant but effective.
            //This pragma suppresses build errors from uncommented files - which generated files are.
            this.codeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, stringWriter, this.codeGeneratorOptions);

            // If a handler was provided for the progress, then let it know that the task is complete.
            if (pGenerateProgress != null)
            {
                pGenerateProgress.Progress(100, 100);
            }

            // This will pack the generated buffer into an unmanaged block of memory that can be passed back to Visual Studio.
            byte[] generatedBuffer = System.Text.Encoding.UTF8.GetBytes(stringWriter.ToString());
            rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(generatedBuffer.Length);
            Marshal.Copy(generatedBuffer, 0, rgbOutputFileContents[0], generatedBuffer.Length);
            pcbOutput = (uint)generatedBuffer.Length;

            // At this point the code generation was a success.
            return(VSConstants.S_OK);
        }
Exemple #3
0
        /// <summary>
        /// Generate the code from the custom tool.
        /// </summary>
        /// <param name="wszInputFilePath">The name of the input file.</param>
        /// <param name="bstrInputFileContents">The contents of the input file.</param>
        /// <param name="wszDefaultNamespace">The namespace FluidTrade.Core.Client the generated code.</param>
        /// <param name="pbstrOutputFileContents">The generated code.</param>
        /// <param name="pbstrOutputFileContentSize">The buffer size of the generated code.</param>
        /// <param name="pGenerateProgress">An indication of the tools progress.</param>
        /// <returns>0 indicates the tool handled the command.</returns>
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace,
                            IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            // Throw an execption if there is nothing to process.
            if (bstrInputFileContents == null)
            {
                throw new ArgumentNullException(bstrInputFileContents);
            }

            // This schema describes the data model that is to be generated.
            PresentationSchema presentationSchema = new PresentationSchema(wszInputFilePath, bstrInputFileContents);

            // This is where all the work is done to translate the input schema into the CodeDOM for the data model and the CodeDOM
            // for the interface to that data model.
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            // This creates an association between an XAML namespace and the CLR namespace in the target assembly.
            codeCompileUnit.AssemblyCustomAttributes.Add(new CodeAttributeDeclaration(
                                                             new CodeTypeReference(typeof(System.Windows.Markup.XmlnsDefinitionAttribute)),
                                                             new CodeAttributeArgument(new CodePrimitiveExpression(presentationSchema.SourceNamespace)),
                                                             new CodeAttributeArgument(new CodePrimitiveExpression(presentationSchema.TargetNamespace))));

            // Most of the work to create the target assembly takes place in creating the namespace.
            codeCompileUnit.Namespaces.Add(new Namespace(presentationSchema));

            // If a handler was provided for the generation of the code, then call it with an update.
            if (pGenerateProgress != null)
            {
                pGenerateProgress.Progress(50, 100);
            }

            // This will generate the target source code in the language described by the CodeDOM provider.
            StringWriter stringWriter = new StringWriter();

            //There is no elegant way to generate preprocessor directives through CodeDom.  All the solutions
            //require string replacement after the fact.  So not elegant but effective.
            //This pragma suppresses build errors from uncommented files - which generated files are.
            this.codeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, stringWriter, this.codeGeneratorOptions);

            // If a handler was provided for the progress, then let it know that the task is complete.
            if (pGenerateProgress != null)
            {
                pGenerateProgress.Progress(100, 100);
            }

            // This will pack the generated buffer into an unmanaged block of memory that can be passed back to Visual Studio.
            byte[] generatedBuffer = System.Text.Encoding.UTF8.GetBytes(stringWriter.ToString());
            rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(generatedBuffer.Length);
            Marshal.Copy(generatedBuffer, 0, rgbOutputFileContents[0], generatedBuffer.Length);
            pcbOutput = (uint)generatedBuffer.Length;

            // At this point the code generation was a success.
            return(VSConstants.S_OK);
        }
Exemple #4
0
        protected override byte[] Generate(string inputFilePath, string inputFileContents, string defaultNamespace, IVsGeneratorProgress progressCallback)
        {

            var viewGen = new DryHtml.ViewGen.ViewGenerator(inputFilePath);
            viewGen.GenerateAll();

            progressCallback.Progress(100, 100);

            return new byte[0];
        }
 public static void Progress(
     this IVsGeneratorProgress pGenerateProgress,
     uint complete)
 {
     try
     {
         ThreadHelper.JoinableTaskFactory?.Run(
             async() =>
         {
             await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
             pGenerateProgress.Progress(complete, 100);
         });
     }
     catch
     {
         ThreadHelper.ThrowIfNotOnUIThread();
         pGenerateProgress.Progress(complete, 100);
     }
 }
Exemple #6
0
        public string GenerateCode(IVsGeneratorProgress pGenerateProgress)
        {
            try
            {
                pGenerateProgress.Progress(10);

                var jarFile = options.OpenApiGeneratorPath;
                if (!File.Exists(jarFile))
                {
                    Trace.WriteLine(jarFile + " does not exist");
                    jarFile = DependencyDownloader.InstallOpenApiGenerator();
                }

                pGenerateProgress.Progress(30);

                var output = Path.Combine(
                    Path.GetDirectoryName(swaggerFile) ?? throw new InvalidOperationException(),
                    "TempApiClient");

                Directory.CreateDirectory(output);
                pGenerateProgress.Progress(40);

                var arguments =
                    $"-jar \"{jarFile}\" generate " +
                    "-g csharp " +
                    $"--input-spec \"{swaggerFile}\" " +
                    $"--output \"{output}\" " +
                    "-DapiTests=false -DmodelTests=false " +
                    $"-DpackageName={defaultNamespace} " +
                    "--skip-overwrite ";

                ProcessHelper.StartProcess(javaPathProvider.GetJavaExePath(), arguments);
                pGenerateProgress.Progress(80);

                return(CSharpFileMerger.MergeFilesAndDeleteSource(output));
            }
            finally
            {
                pGenerateProgress.Progress(90);
            }
        }
Exemple #7
0
        public string GenerateCode(IVsGeneratorProgress pGenerateProgress)
        {
            pGenerateProgress?.Progress(10);

            var command = options.NSwagPath;

            if (!File.Exists(command))
            {
                Trace.WriteLine(command + " does not exist! Retrying with default NSwag.exe path");
                command = PathProvider.GetNSwagPath();
                if (!File.Exists(command))
                {
                    throw new NotInstalledException("NSwag not installed. Please install NSwagStudio");
                }
            }

            TryRemoveSwaggerJsonSpec(nswagStudioFile);
            ProcessHelper.StartProcess(command, $"run \"{nswagStudioFile}\"");
            pGenerateProgress?.Progress(90);
            return(null);
        }
Exemple #8
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 #9
0
        public string GenerateCode(IVsGeneratorProgress pGenerateProgress)
        {
            try
            {
                pGenerateProgress?.Progress(10);

                var document = SwaggerDocument
                               .FromFileAsync(swaggerFile)
                               .GetAwaiter()
                               .GetResult();

                pGenerateProgress?.Progress(20);

                var settings = new SwaggerToCSharpClientGeneratorSettings
                {
                    ClassName                = GetClassName(document),
                    InjectHttpClient         = options.InjectHttpClient,
                    GenerateClientInterfaces = options.GenerateClientInterfaces,
                    GenerateDtoTypes         = options.GenerateDtoTypes,
                    UseBaseUrl               = options.UseBaseUrl,
                    CSharpGeneratorSettings  =
                    {
                        Namespace  = defaultNamespace,
                        ClassStyle = options.ClassStyle
                    },
                };

                pGenerateProgress?.Progress(50);

                var generator = new SwaggerToCSharpClientGenerator(document, settings);
                return(generator.GenerateFile());
            }
            finally
            {
                pGenerateProgress?.Progress(90);
            }
        }
Exemple #10
0
        public virtual string GenerateCode(IVsGeneratorProgress pGenerateProgress)
        {
            try
            {
                pGenerateProgress.Progress(10);
                var path       = Path.GetDirectoryName(SwaggerFile);
                var outputFile = Path.Combine(
                    path ?? throw new InvalidOperationException(),
                    $"{Guid.NewGuid()}.cs");

                var command   = GetCommand();
                var arguments = GetArguments(outputFile);
                pGenerateProgress.Progress(30);

                ProcessHelper.StartProcess(command, arguments);
                pGenerateProgress.Progress(80);

                return(FileHelper.ReadThenDelete(outputFile));
            }
            finally
            {
                pGenerateProgress.Progress(90);
            }
        }
        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;
                }
            }
        }
        bool ReportProgress(IVsGeneratorProgress p, int step, int steps)
        {
            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                if (null != p)
                {
                    p.Progress((uint)step, (uint)steps);
                    return(true);
                }
            }
            catch
            {
            }

            return(false);
        }
 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 #14
0
 public void Progress(uint progress, uint total = 100)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     pGenerateProgress.Progress(progress, total);
 }
        public override byte[] GenerateCode(string inputFileName, string inputFileContent)
        {
            // Validate parameters.
            if (inputFileContent == null || inputFileContent.Length == 0)
            {
                string errorMessage = "WMICodeGenerator - Input file content is null or empty.";
                GeneratorErrorCallback(false, 1, errorMessage, 0, 0);
                // Should I throw an exception?
                // throw new ArgumentException(inputFileContent);
                return(null);
            }

            //Here parse the input file and get all the necessary info

            // Set generator progress to 0 out of 100.
            IVsGeneratorProgress progress = CodeGeneratorProgress;

            if (progress != null)
            {
                progress.Progress(0, 100);
            }

            StreamWriter writer = new StreamWriter(new MemoryStream(), Encoding.UTF8);
            //writer.Write((char) 0xFEFF);

            /*
             * tw = new StreamWriter(new FileStream (genFileName,
             *      FileMode.Create));
             */

            ICodeGenerator codeGenerator = CodeGenerator;

            if (codeGenerator == null)
            {
                string errorMessage = "WMICodeGenerator - No code generator available for this language.";
                GeneratorErrorCallback(false, 1, errorMessage, 0, 0);

                Debug.Fail(errorMessage);
                return(null);
            }

            try {
                ManagementClassGenerator mcg = new ManagementClassGenerator();
                string language = "CS";
                switch (GetDefaultExtension().ToUpper())
                {
                case ".VB":
                    language = "VB";
                    break;

                case ".JScript":
                    language = "JS";
                    break;

                default:
                    language = "CS";
                    break;
                }

                if (!mcg.GenerateCode(inputFileContent, codeGenerator, writer, language))
                {
                    throw new Exception("GenerateCode() failed");
                }
            }
            catch (Exception e) {
                string errorMessage = "Code generator: " + codeGenerator.GetType().Name + " failed.  Exception = " + e.Message;
                GeneratorErrorCallback(false, 1, errorMessage, 0, 0);

                Debug.Fail(errorMessage);
                return(null);
            }

            // Set generator progress to 0 out of 100.
            if (progress != null)
            {
                progress.Progress(100, 100);
            }

            writer.Flush();
            return(StreamToBytes(writer.BaseStream));
        }
Exemple #16
0
        private string GetContents(string inputFilePath, string inputFileContents, string defaultNamespace, IVsGeneratorProgress progress)
        {
            progress.Progress(0, 100);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(inputFileContents);
            XmlNode controlNode = doc.SelectSingleNode("/control");
            string fullClassName = defaultNamespace + "." + Path.GetFileNameWithoutExtension(inputFilePath);
            if (controlNode != null)
            {
                XmlAttribute classNameAttribute = controlNode.Attributes == null ? null : controlNode.Attributes["classname"];
                if (classNameAttribute != null)
                {
                    fullClassName = classNameAttribute.Value;
                }
            }
            int lastDot = fullClassName.LastIndexOf(".", StringComparison.Ordinal);
            string ns = fullClassName.Substring(0, lastDot);
            string className = fullClassName.Substring(lastDot + 1);
            StringBuilder contents = new StringBuilder();
            contents.AppendLine("namespace " + ns);
            contents.AppendLine("{");
            contents.AppendLine("\tpublic abstract class " + className + "Base<T> : global::" + typeof (MarkupControlBase<>).Namespace + ".MarkupControlBase<T>");
            contents.AppendLine("\t{");
            IEnumerable<ElementTypeAndId> elements = ((IEnumerable) doc.SelectNodes("/control//@controlid") ?? new XmlAttribute[0]).Cast<XmlAttribute>().Select(a =>
                {
                    string id = a.Value;
                    XmlElement element = a.OwnerElement;

                    if (element == null)
                    {
                        return null;
                    }

                    if (element.Name == "control")
                    {
                        XmlAttribute typeAttribute = element.Attributes["type"];
                        if (typeAttribute == null)
                        {
                            return null;
                        }
                        return new ElementTypeAndId(typeAttribute.Value, id);
                    }

                    return new ElementTypeAndId(typeof (HtmlControl).FullName, id);
                });
            foreach (ElementTypeAndId element in elements)
            {
                if (element == null)
                {
                    continue;
                }

                contents.AppendLine("\t\tprotected global::" + element.Type + " @" + element.Id + " { get { return FindControl<global::" + element.Type + ">(\"" + element.Id + "\"); } }");
            }
            contents.AppendLine();
            contents.AppendLine("\t\tprotected override string Markup");
            contents.AppendLine("\t\t{");
            contents.AppendLine("\t\t\tget");
            contents.AppendLine("\t\t\t{");
            contents.AppendLine("\t\t\t\treturn");
            contents.Append("@\"");
            contents.Append(inputFileContents.Replace("\"", "\"\""));
            contents.AppendLine("\";");
            contents.AppendLine("\t\t\t}");
            contents.AppendLine("\t\t}");
            contents.AppendLine("\t}");
            contents.AppendLine("}");
            progress.Progress(100, 100);
            return contents.ToString();
        }
Exemple #17
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 #18
0
 /// <summary>
 /// Sets an index that specifies how much of the generation has been completed.
 /// </summary>
 /// <param name="complete">An index that specifies how much of the generation has been completed.</param>
 /// <param name="total">The maximum value for the <paramref name="complete"/>.</param>
 protected void ReportProgress(int complete, int total)
 {
     progress?.Progress((uint)complete, (uint)total);
 }
        void IVsSingleFileGenerator.Generate(string wszInputFilePath,
                                             string bstrInputFileContents,
                                             string wszDefaultNamespace,
                                             out IntPtr outputFileContents,
                                             out int outputFileContentSize,
                                             IVsGeneratorProgress generationProgress)
        {
            if (bstrInputFileContents == null || bstrInputFileContents.Length <= 0)
            {
                outputFileContents    = IntPtr.Zero;
                outputFileContentSize = 0;

                if (generationProgress != null)
                {
                    generationProgress.Progress(100, 100);
                }

                return;
            }

            try {
                MemoryStream          outputStream = new MemoryStream();
                IResourceReader       reader       = ResXResourceReader.FromFileContents(bstrInputFileContents, this.typeResolver);
                IResourceWriter       writer       = new ResourceWriter(outputStream);
                IDictionaryEnumerator resEnum      = reader.GetEnumerator();

                // main conversion loop
                while (resEnum.MoveNext())
                {
                    string name  = (string)resEnum.Key;
                    object value = resEnum.Value;
                    writer.AddResource(name, value);
                }

                // cleanup
                reader.Close();
                writer.Generate();
                // don't close writer just yet -- that closes the stream, which we still need

                // Marshal into a bstr
                byte[] buffer        = outputStream.ToArray();
                int    bufferLength  = buffer.Length;
                IntPtr bufferPointer = Marshal.AllocCoTaskMem(bufferLength);
                Marshal.Copy(buffer, 0, bufferPointer, bufferLength);

                outputFileContents    = bufferPointer;
                outputFileContentSize = bufferLength;

                if (generationProgress != null)
                {
                    generationProgress.Progress(100, 100);
                }

                // Now close the stream
                writer.Close();
                outputStream.Close();

                writer       = null;
                outputStream = null;
                reader       = null;
            }
            catch (Exception e) {
                if (e.InnerException != null)
                {
                    throw e.InnerException;
                }
                else
                {
                    throw;
                }
            }
        }
Exemple #20
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 void ReportProgress(int currentStep, int totalSteps)
 {
     vsProgress.Progress((uint)currentStep, (uint)totalSteps);
 }
Exemple #22
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);
        }
Exemple #23
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);
        }
        void IVsSingleFileGenerator.Generate(string wszInputFilePath,
                                             string bstrInputFileContents,
                                             string wszDefaultNamespace,
                                             out IntPtr outputFileContents,
                                             out int outputFileContentSize,
                                             IVsGeneratorProgress generationProgress)
        {
            LicenseContext ctx = null;

            if (this.provider != null)
            {
                ctx = new LicXDesigntimeLicenseContext(this.provider, this.typeResolver);
            }

            string exeName  = "lc.exe";
            string pathName = NET_SDKInstallRoot;

            if (pathName != null)
            {
                exeName = Path.Combine(Path.Combine(pathName, "bin"), exeName);
            }

            Assembly lcAssem = Assembly.LoadFrom(exeName);

            Debug.Assert(lcAssem != null, "No assembly found at " + exeName);

            Type lcType = lcAssem.GetType("System.Tools.LicenseCompiler");

            Debug.Assert(lcType != null, "No type found at System.Tools.LicenseCompiler");

            MethodInfo mi = lcType.GetMethod("GenerateLicenses", BindingFlags.Public | BindingFlags.Static, null,
                                             new Type[] { typeof(string), typeof(string), typeof(ITypeResolutionService), typeof(DesigntimeLicenseContext) },
                                             null);

            Debug.Assert(mi != null, "No method found at GenerateLicenses");

            Debug.Assert(wszInputFilePath != null, "Null input file name");
            FileInfo fileInfo = new FileInfo(wszInputFilePath);
            string   targetPE = fileInfo.Name;

            MemoryStream outputStream = null;

            try {
                outputStream = (MemoryStream)mi.Invoke(null, BindingFlags.Static, null,
                                                       new object[] { bstrInputFileContents, targetPE, this.typeResolver, ctx },
                                                       CultureInfo.InvariantCulture);
            }
            catch (TargetInvocationException tie) {
                if (tie.InnerException != null)
                {
                    throw tie.InnerException;
                }
                else
                {
                    throw tie;
                }
            }

            // Marshal into a bstr
            byte[] buffer        = outputStream.ToArray();
            int    bufferLength  = buffer.Length;
            IntPtr bufferPointer = Marshal.AllocCoTaskMem(bufferLength);

            Marshal.Copy(buffer, 0, bufferPointer, bufferLength);

            outputFileContents    = bufferPointer;
            outputFileContentSize = bufferLength;

            if (generationProgress != null)
            {
                generationProgress.Progress(100, 100);
            }

            // Now close the stream
            outputStream.Close();
        }