Esempio n. 1
0
        private int ExecuteCore(
            RazorConfiguration configuration,
            string projectDirectory,
            string tagHelperManifest,
            SourceItem[] sourceItems)
        {
            tagHelperManifest = Path.Combine(projectDirectory, tagHelperManifest);

            var tagHelpers = GetTagHelpers(tagHelperManifest);

            var compositeFileSystem = new CompositeRazorProjectFileSystem(new[]
            {
                GetVirtualRazorProjectSystem(sourceItems),
                RazorProjectFileSystem.Create(projectDirectory),
            });

            var success = true;

            var engine = RazorProjectEngine.Create(configuration, compositeFileSystem, b =>
            {
                b.Features.Add(new StaticTagHelperFeature()
                {
                    TagHelpers = tagHelpers,
                });
                b.Features.Add(new DefaultTypeNameFeature());

                if (GenerateDeclaration.HasValue())
                {
                    b.Features.Add(new SetSuppressPrimaryMethodBodyOptionFeature());
                    b.Features.Add(new SuppressChecksumOptionsFeature());
                }

                if (RootNamespace.HasValue())
                {
                    b.SetRootNamespace(RootNamespace.Value());
                }

                if (CSharpLanguageVersion.HasValue())
                {
                    // Only set the C# language version if one was specified, otherwise it defaults to whatever
                    // value was set in the corresponding RazorConfiguration's extensions.

                    var rawLanguageVersion = CSharpLanguageVersion.Value();
                    if (LanguageVersionFacts.TryParse(rawLanguageVersion, out var csharpLanguageVersion))
                    {
                        b.SetCSharpLanguageVersion(csharpLanguageVersion);
                    }
                    else
                    {
                        success = false;
                        Error.WriteLine($"Unknown C# language version {rawLanguageVersion}.");
                    }
                }
            });

            var results = GenerateCode(engine, sourceItems);
            var isGeneratingDeclaration = GenerateDeclaration.HasValue();

            foreach (var result in results)
            {
                var errorCount = result.CSharpDocument.Diagnostics.Count;
                for (var i = 0; i < errorCount; i++)
                {
                    var error = result.CSharpDocument.Diagnostics[i];
                    if (error.Severity == RazorDiagnosticSeverity.Error)
                    {
                        success = false;
                    }

                    if (i < 100)
                    {
                        Error.WriteLine(error.ToString());

                        // Only show the first 100 errors to prevent massive string allocations.
                        if (i == 99)
                        {
                            Error.WriteLine($"And {errorCount - i + 1} more warnings/errors.");
                        }
                    }
                }

                if (success)
                {
                    // Only output the file if we generated it without errors.
                    var outputFilePath = result.InputItem.OutputPath;
                    var generatedCode  = result.CSharpDocument.GeneratedCode;
                    if (isGeneratingDeclaration)
                    {
                        // When emiting declarations, only write if it the contents are different.
                        // This allows build incrementalism to kick in when the declaration remains unchanged between builds.
                        if (File.Exists(outputFilePath) &&
                            string.Equals(File.ReadAllText(outputFilePath), generatedCode, StringComparison.Ordinal))
                        {
                            continue;
                        }
                    }

                    File.WriteAllText(outputFilePath, result.CSharpDocument.GeneratedCode);
                }
            }

            return(success ? ExitCodeSuccess : ExitCodeFailureRazorError);
        }
Esempio n. 2
0
        //^ requires peFileReader.IsAssembly ==> moduleIdentity.ContainingAssembly != null;
        //^ requires peFileReader.IsAssembly ==> containingAssembly == null;
        //^ requires !(moduleIdentity.Location != null && moduleIdentity.Location.Length != 0);
        /*^
        #pragma warning disable 2666, 2669, 2677, 2674
        ^*/
        internal PEFileToObjectModel(
            PeReader peReader,
            PEFileReader peFileReader,
            ModuleIdentity moduleIdentity,
            Assembly/*?*/ containingAssembly,
            byte pointerSize
            )
        {
            this.pointerSize = pointerSize;
              this.ModuleReader = peReader;
              this.PEFileReader = peFileReader;
              this.NameTable = peReader.metadataReaderHost.NameTable;
              this.InternFactory = peReader.metadataReaderHost.InternFactory;
              this.StringIndexToNameTable = new Hashtable<IName>();
              this.StringIndexToUnmangledNameTable = new Hashtable<IName>();
              this.typeCache = new TypeCache(this);
              uint moduleNameOffset = peFileReader.ModuleTable.GetName(1);
              IName moduleName = this.GetNameFromOffset(moduleNameOffset);
              AssemblyIdentity/*?*/ assemblyIdentity = moduleIdentity as AssemblyIdentity;
              if (peFileReader.IsAssembly) {
            //^ assert assemblyIdentity != null;
            AssemblyRow assemblyRow = peFileReader.AssemblyTable[1];
            IName assemblyName = this.GetNameFromOffset(assemblyRow.Name);
            byte[] publicKeyArray = TypeCache.EmptyByteArray;
            if (assemblyRow.PublicKey != 0) {
              publicKeyArray = peFileReader.BlobStream[assemblyRow.PublicKey];
            }
            uint internedModuleId = (uint)peReader.metadataReaderHost.InternFactory.GetAssemblyInternedKey(assemblyIdentity);
            Assembly assem = new Assembly(this, moduleName, peFileReader.COR20Header.COR20Flags, internedModuleId, assemblyIdentity, assemblyName, assemblyRow.Flags, publicKeyArray);
            this.ContainingAssembly = assem;
            this.Module = assem;
              } else {
            uint internedModuleId = (uint)peReader.metadataReaderHost.InternFactory.GetModuleInternedKey(moduleIdentity);
            this.ContainingAssembly = containingAssembly;
            this.Module = new Module(this, moduleName, peFileReader.COR20Header.COR20Flags, internedModuleId, moduleIdentity);
              }

              this.LoadAssemblyReferences();
              this.LoadModuleReferences();
              this.RootModuleNamespace = new RootNamespace(this);
              this.NamespaceINameHashtable = new Hashtable<Namespace>();
              this.LoadNamespaces();
              this.NamespaceReferenceINameHashtable = new DoubleHashtable<NamespaceReference>();
              this.NamespaceTypeTokenTable = new DoubleHashtable(peFileReader.TypeDefTable.NumberOfRows + peFileReader.ExportedTypeTable.NumberOfRows);
              this.NestedTypeTokenTable = new DoubleHashtable(peFileReader.NestedClassTable.NumberOfRows + peFileReader.ExportedTypeTable.NumberOfRows);
              this.PreLoadTypeDefTableLookup();
              this.ModuleTypeDefArray = new TypeBase/*?*/[peFileReader.TypeDefTable.NumberOfRows + 1];
              this.ModuleTypeDefLoadState = new LoadState[peFileReader.TypeDefTable.NumberOfRows + 1];
              this.ModuleTypeDefLoadState[0] = LoadState.Loaded;

              this.ExportedTypeArray = new ExportedTypeAliasBase/*?*/[peFileReader.ExportedTypeTable.NumberOfRows + 1];
              this.ExportedTypeLoadState = new LoadState[peFileReader.ExportedTypeTable.NumberOfRows + 1];
              this.ExportedTypeLoadState[0] = LoadState.Loaded;

              this.ModuleGenericParamArray = new GenericParameter[peFileReader.GenericParamTable.NumberOfRows + 1];
              if (peFileReader.MethodSpecTable.NumberOfRows > 0) {
            this.ModuleMethodSpecHashtable = new DoubleHashtable<IGenericMethodInstanceReference>(peFileReader.MethodSpecTable.NumberOfRows + 1);
              }

              this.ModuleTypeRefReferenceArray = new IMetadataReaderNamedTypeReference[peFileReader.TypeRefTable.NumberOfRows + 1];
              this.ModuleTypeRefReferenceLoadState = new LoadState[peFileReader.TypeRefTable.NumberOfRows + 1];
              this.ModuleTypeRefReferenceLoadState[0] = LoadState.Loaded;
              if (peFileReader.TypeSpecTable.NumberOfRows > 0) {
            this.ModuleTypeSpecHashtable = new DoubleHashtable<TypeSpecReference>(peFileReader.TypeSpecTable.NumberOfRows + 1);
              }

              this.ModuleFieldArray = new FieldDefinition[peFileReader.FieldTable.NumberOfRows + 1];
              this.ModuleMethodArray = new IMethodDefinition[peFileReader.MethodTable.NumberOfRows + 1];
              this.ModuleEventArray = new EventDefinition[peFileReader.EventTable.NumberOfRows + 1];
              this.ModulePropertyArray = new PropertyDefinition[peFileReader.PropertyTable.NumberOfRows + 1];

              this.ModuleMemberReferenceArray = new MemberReference/*?*/[peFileReader.MemberRefTable.NumberOfRows + 1];

              this.CustomAttributeArray = new ICustomAttribute/*?*/[peFileReader.CustomAttributeTable.NumberOfRows + 1];

              this.DeclSecurityArray = new ISecurityAttribute/*?*/[peFileReader.DeclSecurityTable.NumberOfRows + 1];

              this._Module_ = this.Create_Module_Type();
        }
Esempio n. 3
0
 public static IEnumerable <ExternStruct> AllExternStructs(RootNamespace root) => AllStructs <ExternStruct>(root);
        private int ExecuteCore(
            RazorConfiguration configuration,
            string projectDirectory,
            string tagHelperManifest,
            SourceItem[] sourceItems)
        {
            tagHelperManifest = Path.Combine(projectDirectory, tagHelperManifest);

            var tagHelpers = GetTagHelpers(tagHelperManifest);

            var compositeFileSystem = new CompositeRazorProjectFileSystem(new[]
            {
                GetVirtualRazorProjectSystem(sourceItems),
                RazorProjectFileSystem.Create(projectDirectory),
            });

            var engine = RazorProjectEngine.Create(configuration, compositeFileSystem, b =>
            {
                b.Features.Add(new StaticTagHelperFeature()
                {
                    TagHelpers = tagHelpers,
                });
                b.Features.Add(new DefaultTypeNameFeature());

                if (GenerateDeclaration.HasValue())
                {
                    b.Features.Add(new SetSuppressPrimaryMethodBodyOptionFeature());
                }

                if (RootNamespace.HasValue())
                {
                    b.SetRootNamespace(RootNamespace.Value());
                }
            });

            var results = GenerateCode(engine, sourceItems);

            var success = true;

            foreach (var result in results)
            {
                var errorCount = result.CSharpDocument.Diagnostics.Count;
                if (errorCount > 0)
                {
                    success = false;

                    for (var i = 0; i < errorCount; i++)
                    {
                        var error = result.CSharpDocument.Diagnostics[i];
                        Error.WriteLine(error.ToString());

                        // Only show the first 100 errors to prevent massive string allocations.
                        if (i == 99)
                        {
                            Error.WriteLine($"And {errorCount - i + 1} more errors.");
                            break;
                        }
                    }
                }
                else
                {
                    // Only output the file if we generated it without errors.
                    var outputFilePath = result.InputItem.OutputPath;
                    File.WriteAllText(outputFilePath, result.CSharpDocument.GeneratedCode);
                }
            }

            return(success ? ExitCodeSuccess : ExitCodeFailureRazorError);
        }
Esempio n. 5
0
        /// <summary>
        /// Create the method body
        /// </summary>
        /// <param name="sbWork">StringBuilder to append method</param>
        /// <param name="classNamespace">class name</param>
        /// <param name="methodName">method name</param>
        /// <param name="method">Ajax item method</param>
        /// <param name="parameters">List of parameters</param>
        /// <param name="ajaxClass"> Ajax class item</param>
        /// <param name="useTraditionalParameterForm"> Use traditional parameters, like function(parm1,parm2,parm3) instead function(options), calling myFunc({data:'data'});</param>
        /// <returns></returns>
        public override void CreateMethodBody(ref System.Text.StringBuilder sbWork, string classNamespace, string methodName, AjaxMethodItem method, IList <Entities.Parameter> parameters, AjaxClassItem ajaxClass, bool useTraditionalParameterForm = false)
        {
            var functionBody = new StringBuilder("function(");

            if (useTraditionalParameterForm)
            {
                for (var index = 0; index < parameters.Count; index++)
                {
                    if (index != 0)
                    {
                        functionBody.Append(",");
                    }
                    var parameter = parameters[index];
                    functionBody.Append(parameter.Name);
                }
                functionBody.Append((parameters.Count > 0 ?",":"") + "callbackSuccess,callbackError,callbackComplete,uploadProgress");
            }
            else
            {
                functionBody.Append("options");
            }

            functionBody.Append("){" + GetNewLineTab(1));


            functionBody.Append(GetNewLineTab(1));
            functionBody.Append("var mtnOptions = (typeof options === 'undefined' || options == null)?{}:options;");
            functionBody.Append(GetNewLineTab(1));
            functionBody.Append("mtnOptions.data = mtnOptions.data || {};");
            functionBody.Append(GetNewLineTab(1));
            if (useTraditionalParameterForm)
            {
                functionBody.Append(GetNewLineTab(1));
                functionBody.
                Append("mtnOptions.callbackSuccess = callbackSuccess;").Append(GetNewLineTab(1)).
                Append("mtnOptions.callbackError = callbackError;").Append(GetNewLineTab(1)).
                Append("mtnOptions.callbackComplete = callbackComplete;").Append(GetNewLineTab(1)).
                Append("mtnOptions.uploadProgress = uploadProgress;");
                functionBody.Append(GetNewLineTab(1));

                if (parameters.Count > 0)
                {
                    functionBody.Append("mtnOptions.data = {");

                    for (var index = 0; index < parameters.Count; index++)
                    {
                        var parameter = parameters[index];
                        functionBody.Append(GetNewLineTab(2));
                        functionBody.Append((index != 0 ? "," : ""))
                        .Append(parameter.Name).Append(":").Append(parameter.Name);
                    }


                    functionBody.Append(GetNewLineTab(1));
                    functionBody.Append("};");
                }
                functionBody.Append(GetNewLineTab(1));
            }

            for (var index = 0; index < parameters.Count; index++)
            {
                var parameter = parameters[index];


#if !UseSystemExtensions
                if (Mtn.Library.Extensions.SystemExtensions.IsPrimitiveMtn(parameter.Type) || parameter.Type.FullName.ToLower().Contains("httppostedfile"))
                {
                    continue;
                }
#else
                if (parameter.Type.IsPrimitiveMtn() || parameter.Type.FullName.ToLower().Contains("httppostedfile"))
                {
                    continue;
                }
#endif
                functionBody.Append(GetNewLineTab(1));
                functionBody.AppendFormat("mtnOptions.data.{0} = JSON.stringify(mtnOptions.data.{0});", parameter.Name);
                functionBody.Append(GetNewLineTab(1));
            }

            functionBody.AppendFormat("mtnOptions.data.__MtnClassHash = '{0}';", ajaxClass.Key);
            functionBody.Append(GetNewLineTab(1));
            functionBody.AppendFormat("mtnOptions.data.__MtnMethodHash = '{0}';", method.Key);
            functionBody.Append(GetNewLineTab(1));
            switch (Mode)
            {
            case WebModeType.AjaxHandler:
                functionBody.Append("mtnOptions.url='")
                .Append(HostUrl).Append("/")
                .Append(classNamespace.ToLowerInvariant()).Append(".").Append(methodName)
                .Append(".").Append(Utils.Parameter.AjaxExtension)
                .Append("';");
                break;

            case WebModeType.MvcController:
                functionBody.Append("mtnOptions.url='")
                .Append(HostUrl).Append("/{MtnMvcRoute}")
                .Append(classNamespace.Replace(".", Utils.Parameter.SeoCharacter).ToLowerInvariant()).Append("/").Append(methodName.ToLowerInvariant())
                .Append("/';");
                break;

            default:
                functionBody.Append("mtnOptions.url='")
                .Append(HostUrl).Append("/{MtnMvcRoute}")
                .Append(classNamespace.Replace(".", Utils.Parameter.SeoCharacter).ToLowerInvariant()).Append("/").Append(methodName.ToLowerInvariant())
                .Append("/';");
                break;
            }
            functionBody.Append(GetNewLineTab(1));

            functionBody.AppendFormat("mtnOptions.responseType = '{0}';", method.AjaxMethod.ResponseType.ToString().ToLowerInvariant());
            functionBody.Append(GetNewLineTab(1));
            string ajaxTmpl = "";
            switch (method.AjaxMethod.RequestType)
            {
            case RequestType.Post:
                ajaxTmpl = AjaxPostFunctionTemplate;
                break;

            case RequestType.Get:
                ajaxTmpl = AjaxGetFunctionTemplate;
                break;
            }
            switch (method.AjaxMethod.ResponseType)
            {
            case ResponseType.Json:
                break;

            case ResponseType.Xml:
                break;

            case ResponseType.Text:
                break;

            case ResponseType.JsonP:
                ajaxTmpl = AjaxJsonPFunctionTemplate;
                break;

            case ResponseType.Html:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            ajaxTmpl = String.Format(ajaxTmpl, HasFileUpload(parameters).ToString().ToLower());
            functionBody.AppendLine(ajaxTmpl);

            functionBody.AppendLine("};");
            if (RootNamespace.IsNullOrWhiteSpaceMtn())
            {
                sbWork.AppendFormat("{0}.{1} = {2}", classNamespace, methodName, functionBody.ToString());
            }
            else
            {
                sbWork.AppendFormat("{0}.{1}.{2}  = {3}", RootNamespace, classNamespace, methodName, functionBody.ToString());
            }
            sbWork.AppendLine();
        }
Esempio n. 6
0
 static CustomColors()
 {
     Root = new RootNamespace();
 }
Esempio n. 7
0
 public ImportedModuleDefinition ImportModule(Module module, RootNamespace targetNamespace)
 {
     throw new NotSupportedException();
 }
Esempio n. 8
0
 public void ImportAssembly(Assembly assembly, RootNamespace targetNamespace)
 {
     throw new NotSupportedException();
 }