/// <summary> /// Constructor /// </summary> /// <param name="context">The code generation context</param> public CustomViewModel(CodeGenerationContext context) { this.Context = context; // we typically name our custom binding handlers like this this.CustomBindingHandlerName = "yourBindingHandler"; // not sure on this one, we'll set it as a global dependency by default, if for nothing other than convenience this.IncludeAsGlobalDependency = true; // normally we dont generate unit tests for a custom binding handler, only if we're being thorough this.GenerateUnitTests = false; // we normally don't have less files for a custom binding handler, so set this to off as default this.GenerateLessFile = false; // if we do want a less file, we'll probably want that imported this.ImportLessFile = true; this.CreateInitCallback = true; this.CreateUpdateCallback = false; this.MasterLessFilePath = @"src\css\all-components.less"; this.UnitTestModuleLocation = @"src\test\all-tests.ts"; this.RootPathForBindingHandler = @"src\bindingHandlers\"; this.UnitTestCreationLocation = @"src\test\bindingHandlers\"; this.PathForAmdDependency = @"src/app/startup.ts"; }
protected PropertiesToCopyExpressionBinder(CodeGenerationContext codeGenerationContext, Type type, Expression zone, Expression theCopy) { this.codeGenerationContext = codeGenerationContext; this.type = type; this.zone = zone; this.theCopy = theCopy; }
private CSharpGatewayExpressionBinder(CodeGenerationContext codeGenerationContext) { this.CodeGenerationContext = codeGenerationContext; this.httpClientType = FickleType.Define(this.CodeGenerationContext.Options.ServiceClientTypeName ?? "HttpClient"); this.httpStreamSerializerType = FickleType.Define("IHttpStreamSerializer"); }
internal static IEnumerable<IVsPackageMetadata> GetInstalledPackages(CodeGenerationContext context) { var packageInstallerServices = context.ServiceProvider .GetService<IComponentModel, SComponentModel>().GetService<IVsPackageInstallerServices>(); return packageInstallerServices.GetInstalledPackages(context.ActiveProject); }
private static bool IsApplicableProject(CodeGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (ProjectLanguage.CSharp == context.ActiveProject.GetCodeLanguage()) { FrameworkName targetFramework = null; // GetTargetFramework() may: // 1) Throw an exception if TargetFramework string is not valid during the internal parsing. // 2) Return null if the active project is not null but the TargetFrameworkMoniker is null. // // Both of them fall into the case in which the mvc scaffolding does not support the target framework. try { targetFramework = context.ActiveProject.GetTargetFramework(); } catch { return false; } if (targetFramework != null && targetFramework.Identifier == ".NETFramework" && targetFramework.Version >= new Version(4, 5)) { return true; } } return false; }
/// <summary> /// Constructor for the custom code generator /// </summary> /// <param name="context">Context of the current code generation operation based on how scaffolder was invoked(such as selected project/folder) </param> /// <param name="information">Code generation information that is defined in the factory class.</param> public CustomCodeGenerator( CodeGenerationContext context, CodeGeneratorInformation information) : base(context, information) { _viewModel = new CustomViewModel(Context); }
/// <summary> /// Constructor for the custom code generator /// </summary> /// <param name="context">Context of the current code generation operation based on how scaffolder was invoked(such as selected project/folder) </param> /// <param name="information">Code generation information that is defined in the factory class.</param> public FieldGenerator( CodeGenerationContext context, CodeGeneratorInformation information) : base(context, information) { _viewModel = new FieldViewModel(); }
/// <summary> /// Constructor for the custom code generator /// </summary> /// <param name="context">Context of the current code generation operation based on how scaffolder was invoked(such as selected project/folder) </param> /// <param name="information">Code generation information that is defined in the factory class.</param> public ElementGenerator( CodeGenerationContext context, CodeGeneratorInformation information) : base(context, information) { _viewModel = new ElementViewModel(); }
public static Expression Build(TypeDefinitionExpression expression, CodeGenerationContext context) { var builder = new PropertiesToDictionaryExpressionBinder(expression.Type, context); builder.Visit(expression); return builder.propertySetterExpressions.ToStatementisedGroupedExpression(GroupedExpressionsExpressionStyle.Wide); }
public static Expression Bind(CodeGenerationContext codeGenerationContext, TypeDefinitionExpression expression, ParameterExpression zone, ParameterExpression theCopy) { var builder = new PropertiesToCopyExpressionBinder(codeGenerationContext, expression.Type, zone, theCopy); builder.Visit(expression); return builder.statements.ToStatementisedGroupedExpression(); }
public static Type GetWrappedResponseType(CodeGenerationContext context, Type type) { if (TypeSystem.IsPrimitiveType(type) || type is FickleListType) { return context.ServiceModel.GetServiceType(GetValueResponseWrapperTypeName(type)); } return type; }
/// <summary> /// Provides a way to check if the custom scaffolder is valid under this context /// </summary> /// <param name="codeGenerationContext">The code generation context</param> /// <returns>True if valid, False otherwise</returns> public override bool IsSupported(CodeGenerationContext codeGenerationContext) { if (codeGenerationContext.ActiveProject.CodeModel.Language != EnvDTE.CodeModelLanguageConstants.vsCMLanguageCSharp) { return false; } return true; }
protected ScaffolderModel(CodeGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } Context = context; ServiceProvider = context.ServiceProvider; }
public FrameworkDependencyStatus EnsureDependencyInstalled(CodeGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } ODataDependencyInstaller dependencyInstaller = new ODataDependencyInstaller(context, VisualStudioIntegration); return dependencyInstaller.Install(); }
/// <summary> /// Constructor /// </summary> /// <param name="context">The code generation context</param> public CustomViewModel(CodeGenerationContext context) { Context = context; ICodeTypeService codeTypeService = (ICodeTypeService)Context.ServiceProvider.GetService(typeof(ICodeTypeService)); this.ModelTypes = codeTypeService.GetAllCodeTypes(Context.ActiveProject) //.Where(codeType => codeType.IsValidWebProjectEntityType()) .Where(codeType => codeType.IsDerivedType("System.Web.Http.ApiController")) .Select(codeType => new ModelType(codeType)); }
protected override void GenerateGateway(CodeGenerationContext codeGenerationContext, TypeDefinitionExpression expression) { using (var writer = this.GetTextWriterForFile(expression.Type.Name + ".java")) { var classFileExpression = GatewayExpressionBinder.Bind(codeGenerationContext, expression); var codeGenerator = new JavaCodeGenerator(writer); codeGenerator.Generate(classFileExpression); } }
protected override void GenerateEnum(CodeGenerationContext codeGenerationContext, TypeDefinitionExpression expression) { using (var writer = this.GetTextWriterForFile(expression.Type.Name + ".h")) { var enumFileExpression = EnumHeaderExpressionBinder.Bind(codeGenerationContext, expression); var codeGenerator = new ObjectiveCodeGenerator(writer); codeGenerator.Generate(enumFileExpression); } }
protected InteractiveScaffolder(CodeGenerationContext context, CodeGeneratorInformation information) : base(context, information) { if (context == null) { throw new ArgumentNullException("context"); } Framework = context.Items.GetProperty <TFramework>(typeof(TFramework)); Repository = context.Items.GetProperty <INuGetRepository>(typeof(INuGetRepository)); VisualStudioIntegration = context.Items.GetProperty <IVisualStudioIntegration>(typeof(IVisualStudioIntegration)); }
// We support CSharp WAPs targetting at least .Net Framework 4.5 or above. // We DON'T currently support VB public override bool IsSupported(CodeGenerationContext codeGenerationContext) { if (ProjectLanguage.CSharp.Equals(codeGenerationContext.ActiveProject.GetCodeLanguage())) { FrameworkName targetFramework = codeGenerationContext.ActiveProject.GetTargetFramework(); return((targetFramework != null) && String.Equals(".NetFramework", targetFramework.Identifier, StringComparison.OrdinalIgnoreCase) && targetFramework.Version >= new Version(4, 5)); } return(false); }
public ControllerWithEntityScaffolderModel(CodeGenerationContext context) : base(context) { ServiceTypes = ServiceProvider.GetService <ICodeTypeService>().GetAllCodeTypes(ActiveProject) .Where(codeType => codeType.IsInterfaceType()) .Select(ct => new ModelType(ct)); ViewModelTypes = ServiceProvider.GetService <ICodeTypeService>().GetAllCodeTypes(ActiveProject) .Where(codeType => codeType.IsValidWebProjectEntityType()) .Select(ct => new ModelType(ct)); this.IsServiceClassSupported = true; this.IsViewModelSupported = true; }
// We support CSharp WAPs targetting at least .Net Framework 4.5 or above. // We DON'T currently support VB public override bool IsSupported(CodeGenerationContext codeGenerationContext) { if (ProjectLanguage.CSharp.Equals(codeGenerationContext.ActiveProject.GetCodeLanguage()) ) { FrameworkName targetFramework = codeGenerationContext.ActiveProject.GetTargetFramework(); return (targetFramework != null) && String.Equals(".NetFramework", targetFramework.Identifier, StringComparison.OrdinalIgnoreCase) && targetFramework.Version >= new Version(4, 5); } return false; }
/// <summary> /// Constructor for the custom code generator /// </summary> /// <param name="context">Context of the current code generation operation based on how scaffolder was invoked(such as selected project/folder) </param> /// <param name="information">Code generation information that is defined in the factory class.</param> public CustomCodeGenerator( CodeGenerationContext context, CodeGeneratorInformation information) : base(context, information) { try { _viewModel = new CustomViewModel(Context); } catch (Exception exc) { } }
public virtual string MakeAddAParameter(CodeGenerationContext ctx) { StringBuilder code = new StringBuilder(); code.AppendLine("private void AddAParameter(IDbCommand Cmd, string DbType, string DbName, object Value, int Length)\n{"); code.AppendLine("var dbType = (SqlDbType)System.Enum.Parse(typeof(SqlDbType), DbType);"); code.AppendLine("var myParam = new SqlParameter(DbName, dbType, Length);"); code.AppendLine("myParam.Value = Value != null ? Value : DBNull.Value;"); code.AppendLine("Cmd.Parameters.Add( myParam);"); code.AppendLine("}"); return(code.ToString()); }
public SPCodeGeneratorViewModel(CodeGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } _context = context; //_useMasterPage = true; _GenerateViews = true; _ReferenceScriptLibraries = true; _LayoutPageSelected = true; }
private CodeGenerationContext PopulateContext(MutableTypeCodeGenerator generator, int currentState) { var context = new CodeGenerationContext( _mutableType, _typeBuilderMock.Object, _debugInfoGeneratorMock.Object, _emittableOperandProviderMock.Object); PrivateInvoke.SetNonPublicField(generator, "_context", context); PrivateInvoke.SetNonPublicField(generator, "_state", currentState); return(context); }
/// <summary> /// Returns true if the version of "Microsoft.AspNet.WebApi.OData" package (OData V3 package) /// is less than 5.2.0. Otherwise, returns true. Used for generating code differently for those cases. /// </summary> public bool IsODataLegacy(CodeGenerationContext context) { string odataPackageVersionString = Repository.GetPackageVersion(context, NuGetPackages.ODataNuGetPackageId); Contract.Assert(odataPackageVersionString != null); Version odataPackageVersion; bool result = SemanticVersionParser.TryParse(odataPackageVersionString, out odataPackageVersion); Contract.Assert(result); return(odataPackageVersion < new Version(5, 2, 0)); }
private static bool DisplayScaffolders(CodeGenerationContext context, string projectReferenceName, Version minVersion, Version maxExcludedVersion) { if (IsApplicableProject(context)) { var referenceDetails = IsValidProjectReference(context, projectReferenceName, minVersion, maxExcludedVersion); // We want to show when the reference exists and is of supported version // or when the reference does not exist. return referenceDetails != ReferenceDetails.ReferenceVersionNotSupported; } return false; }
private static bool DisplayScaffolders(CodeGenerationContext context, string projectReferenceName, Version minVersion, Version maxExcludedVersion) { if (IsApplicableProject(context)) { var referenceDetails = IsValidProjectReference(context, projectReferenceName, minVersion, maxExcludedVersion); // We want to show when the reference exists and is of supported version // or when the reference does not exist. return(referenceDetails != ReferenceDetails.ReferenceVersionNotSupported); } return(false); }
public NuGetPackage GetPackage(CodeGenerationContext context, string id) { if (context == null) { throw new ArgumentNullException("context"); } if (id == null) { throw new ArgumentNullException("id"); } string packageVersion = this.GetPackageVersion(context, id); return(new NuGetPackage(id, packageVersion, NuGetRepository._repository)); }
public override bool IsSupported(CodeGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (context.ActiveProject.CodeModel.Language != EnvDTE.CodeModelLanguageConstants.vsCMLanguageCSharp) { return(false); } return(Framework.IsSupported(context)); }
/// <summary> /// This function determines the Package version file name based on the project references. /// Package version file is the data file that contains the matching versions for nuget packages. /// </summary> /// <param name="context">>The <see cref="CodeGenerationContext"/> provided by core scaffolding.</param> /// <returns>The package version file name to be loaded.</returns> private static string GetPackageReferenceFileName(CodeGenerationContext context) { IEnumerable <IVsPackageMetadata> installedPackages = GetInstalledPackages(context); string packageFileName = GetPackageVersionsFileName(_latestKnownPackageVersion); GetPackageFileNameForPackage(context, installedPackages, packageId: NuGetPackages.WebApiNuGetPackageId, assemblyReferenceName: AssemblyVersions.WebApiAssemblyName, minSupportedAssemblyReferenceVersion: AssemblyVersions.WebApiAssemblyMinVersion, packageFileName: ref packageFileName); return(packageFileName); }
public CodeExpression GetCondition(CodeGenerationContext ctx, CodeMemberMethod method) { if (Scope == ValueScope.Segment) { return(new CodePropertyReferenceExpression(ctx.MappedObject, _value)); } if (Scope == ValueScope.Global) { return(new CodePropertyReferenceExpression(ctx.ResultObject, _value)); } return(new CodeSnippetExpression(Preprocess(ctx, _value))); }
internal static async Task TestAddNamespaceAsync( string initial, string expected, string name = "N", IList <ISymbol> imports = null, IList <INamespaceOrTypeSymbol> members = null, CodeGenerationContext context = null) { using var testContext = await TestContext.CreateAsync(initial, expected); var @namespace = CodeGenerationSymbolFactory.CreateNamespaceSymbol(name, imports, members); testContext.Result = await testContext.Service.AddNamespaceAsync(testContext.Solution, (INamespaceSymbol)testContext.GetDestination(), @namespace, context ?? CodeGenerationContext.Default, CancellationToken.None); }
public JObject GetData(string dataContract, CodeGenerationContext context) { if (string.IsNullOrEmpty(nameof(dataContract))) { throw new ArgumentException(nameof(dataContract)); } if (!DataContracts.Any(dc => dc.Equals(dataContract, StringComparison.OrdinalIgnoreCase))) { throw new InvalidOperationException($"Data Contract not supported: '{dataContract}'"); } return(GetDataForContract(dataContract, context)); }
public void Can_create_CodeGenerationContext_for_nested_package() { var context = CodeGenerationContext.Create(TestUtils.CreatePackagePath("control_msgs")); context.Should().NotBeNull(); context.Packages.Should().NotContainNulls(); context.Packages.Should().ContainSingle(); var package = context.Packages.First().PackageInfo; package.Name.Should().Be("control_msgs"); package.IsMetaPackage.Should().BeFalse(); package.PackageDirectory.FullName.Should().Be(Path.GetFullPath(TestUtils.CreatePackagePath("control_msgs", "control_msgs"))); }
public bool IsDependencyInstalled(CodeGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } bool isODataRestierAssemblyReferenced = ProjectReferences.IsAssemblyReferenced(context.ActiveProject, AssemblyVersions.ODataRestierAssemblyName); context.Items[ContextKeys.IsODataRestierAssemblyReferencedKey] = isODataRestierAssemblyReferenced; bool isEntityFrameworkAssemblyReferenced = ProjectReferences.IsAssemblyReferenced(context.ActiveProject, AssemblyVersions.EntityFrameworkAssemblyName); context.Items[ContextKeys.IsEntityFrameworkAssemblyReferencedKey] = isEntityFrameworkAssemblyReferenced; return isODataRestierAssemblyReferenced && isEntityFrameworkAssemblyReferenced; }
public void SetUp() { _expressionPreparerMock = MockRepository.GenerateStrictMock <IExpressionPreparer>(); _ilGeneratorFactoryStub = MockRepository.GenerateStub <IILGeneratorFactory>(); _emitter = new MemberEmitter(_expressionPreparerMock, _ilGeneratorFactoryStub); _typeBuilderMock = MockRepository.GenerateStrictMock <ITypeBuilder>(); _emittableOperandProviderMock = MockRepository.GenerateStrictMock <IEmittableOperandProvider>(); _context = CodeGenerationContextObjectMother.GetSomeContext( typeBuilder: _typeBuilderMock, emittableOperandProvider: _emittableOperandProviderMock); _fakeBody = ExpressionTreeObjectMother.GetSomeExpression(); }
public async Task <Document> AddSourceToAsync(Document document, Compilation symbolCompilation, ISymbol symbol, CancellationToken cancellationToken) { if (document == null) { throw new ArgumentNullException(nameof(document)); } var newSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var rootNamespace = newSemanticModel.GetEnclosingNamespace(0, cancellationToken); var context = new CodeGenerationContext( contextLocation: newSemanticModel.SyntaxTree.GetLocation(new TextSpan()), generateMethodBodies: false, generateDocumentationComments: true, mergeAttributes: false, autoInsertionLocation: false); // Add the interface of the symbol to the top of the root namespace document = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( document.Project.Solution, rootNamespace, CreateCodeGenerationSymbol(document, symbol), context, cancellationToken).ConfigureAwait(false); document = await AddNullableRegionsAsync(document, cancellationToken).ConfigureAwait(false); var docCommentFormattingService = document.GetLanguageService <IDocumentationCommentFormattingService>(); var docWithDocComments = await ConvertDocCommentsToRegularCommentsAsync(document, docCommentFormattingService, cancellationToken).ConfigureAwait(false); var docWithAssemblyInfo = await AddAssemblyInfoRegionAsync(docWithDocComments, symbolCompilation, symbol.GetOriginalUnreducedDefinition(), cancellationToken).ConfigureAwait(false); var node = await docWithAssemblyInfo.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var options = await SyntaxFormattingOptions.FromDocumentAsync(docWithAssemblyInfo, cancellationToken).ConfigureAwait(false); var formattedDoc = await Formatter.FormatAsync( docWithAssemblyInfo, SpecializedCollections.SingletonEnumerable(node.FullSpan), options, GetFormattingRules(docWithAssemblyInfo), cancellationToken).ConfigureAwait(false); var reducers = GetReducers(); return(await Simplifier.ReduceAsync(formattedDoc, reducers, null, cancellationToken).ConfigureAwait(false)); }
protected DependencyInstaller(CodeGenerationContext context, IVisualStudioIntegration visualStudioIntegration) { if (context == null) { throw new ArgumentNullException("context"); } if (visualStudioIntegration == null) { throw new ArgumentNullException("visualStudioIntegration"); } this.Context = context; this.VisualStudioIntegration = visualStudioIntegration; this.ActionsService = context.ServiceProvider.GetService <ICodeGeneratorActionsService>(); this.FilesLocatorService = context.ServiceProvider.GetService <ICodeGeneratorFilesLocator>(); this.AppStartFileNames = new Dictionary <string, string>(); }
protected override void GenerateEnum(CodeGenerationContext codeGenerationContext, TypeDefinitionExpression expression) { if (this.mappedTypes.ContainsKey(expression.Type.Name)) { return; } using (var writer = this.GetTextWriterForFile(expression.Type.Name + ".cs")) { var enumFileExpression = CSharpEnumExpressionBinder.Bind(codeGenerationContext, expression); var codeGenerator = new CSharpCodeGenerator(writer, this.mappedTypes); codeGenerator.Generate(enumFileExpression); } }
public async Task TestDefaultTypeMemberAccessibility2() { var codeGenOptionNoBody = new CodeGenerationContext(generateMethodBodies: false); var generationSource = "public class [|C|] { private void B(){} public void C(){} }"; var initial = "public interface [|I|] { void A(); }"; var expected = @"public interface I { void A(); void B(); void C(); }"; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers : true, context : codeGenOptionNoBody); initial = "Public Interface [|I|] \n Sub A() \n End Interface"; expected = @"Public Interface I Sub A() Sub B() Sub C() End Interface"; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers : true, context : codeGenOptionNoBody); initial = "Public Class [|C|] \n Sub A() \n End Sub \n End Class"; expected = @"Public Class C Sub A() End Sub Public Sub C() End Sub Private Sub B() End Sub End Class"; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers : true); initial = "Public Module [|M|] \n Sub A() \n End Sub \n End Module"; expected = @"Public Module M Sub A() End Sub Public Sub C() End Sub Private Sub B() End Sub End Module"; await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers : true); }
public bool IsDependencyInstalled(CodeGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } bool isODataRestierAssemblyReferenced = ProjectReferences.IsAssemblyReferenced(context.ActiveProject, AssemblyVersions.ODataRestierAssemblyName); context.Items[ContextKeys.IsODataRestierAssemblyReferencedKey] = isODataRestierAssemblyReferenced; bool isEntityFrameworkAssemblyReferenced = ProjectReferences.IsAssemblyReferenced(context.ActiveProject, AssemblyVersions.EntityFrameworkAssemblyName); context.Items[ContextKeys.IsEntityFrameworkAssemblyReferencedKey] = isEntityFrameworkAssemblyReferenced; return(isODataRestierAssemblyReferenced && isEntityFrameworkAssemblyReferenced); }
/// <summary> /// Constructor /// </summary> /// <param name="context">The code generation context</param> public CustomViewModel(CodeGenerationContext context) { Context = context; this.DynamicallyLoaded = true; this.RegisterComponent = true; this.GenerateUnitTests = true; this.ComponentName = "new-component"; this.ComponentLocation = @"src\components\"; this.ComponentRegistrationLocation = @"src\app\startup.ts"; this.UnitTestModuleLocation = @"src\test\all-tests.ts"; this.UnitTestCreationLocation = @"src\test\components\"; this.GenerateLessFile = true; this.GenerateStrippedDownComponent = false; this.ImportLessFile = true; this.MasterLessFile = @"src\css\all-components.less"; this.PathToGulpFile = @"gulpfile.js"; }
public SaveCodeGenerationContextAssembly( DefinitionContext definitionContext, Assembly assembly, string defaultNamespace, string location, string fileName) { this.Assembly = assembly; this.Location = location; this.FileName = fileName; this.DefaultNamespace = defaultNamespace; this._definitionContext = definitionContext; this._definitions = new List <TypeDefinition>(); this._structDefinitions = new List <TypeDefinition>(); this._containerDefinitions = new List <ContainerDefinition>(); this._codeGenerationContext = new CodeGenerationContext(); }
public MvcViewScaffolderModel(CodeGenerationContext context) : base(context) { // These are the defaults for these settings, they may be overridden by saved settings IsLayoutPageSelected = true; IsPartialViewSelected = false; IsReferenceScriptLibrariesSelected = true; // For Views and Controllers, the Area name can be inferred from where in the tree the // scaffolder was launched. This will also work in the case that the 'Add View' context // menu item is invoked, because the folder containing the controller will be the ActiveProjectItem AreaName = GetAreaNameFromSelection(context.ActiveProjectItem); ViewTemplates = Enumerable.Empty <ViewTemplate>(); ModelTypes = ServiceProvider.GetService <ICodeTypeService>().GetAllCodeTypes(ActiveProject) .Where(codeType => codeType.IsValidWebProjectEntityType()) .Select(ct => new ModelType(ct)); DataContextTypes = ServiceProvider.GetService <ICodeTypeService>().GetAllCodeTypes(ActiveProject) .Where(codeType => codeType.IsValidDbContextType()) .Select(ct => new ModelType(ct)); // This is true for the view scaffolder - the controller scaffolder model sets this to // false by default. This will be removed when we split the controller model (which currently // inherits from this class). IsModelClassSupported = true; // When invoked from the 'Add View' context menu in the editor, we can pre-populate the output // path and view name based on the controller and action that invoked it. string value; if (context.Items.TryGetProperty <string>(DefaultViewNameKey, out value)) { ViewName = value; } else { ViewName = GetGeneratedName(MvcProjectUtil.ViewName, ViewFileExtension); } if (context.Items.TryGetProperty <string>(ControllerFolderNameKey, out value) && value != null) { SelectionRelativePath = Path.Combine(AreaRelativePath, CommonFolderNames.Views, value); } }
public WebFormsCodeGeneratorViewModel(CodeGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } _context = context; _useMasterPage = true; _overwrite = false; _generateController = true; _generateApiController = true; _generateStorageContext = true; _generateViews = true; _generateScripts = true; }
public static bool IsBundleConfigPresent(CodeGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } Project activeProject = context.ActiveProject; string defaultNamespace = ProjectExtensions.GetDefaultNamespace(activeProject); if (context.ServiceProvider.GetService <ICodeTypeService>().GetCodeType(activeProject, string.Concat(defaultNamespace, ".BundleConfig")) != null) { return(true); } string str = string.Concat("BundleConfig.", ProjectExtensions.GetCodeLanguage(activeProject).CodeFileExtension); return(File.Exists(Path.Combine(ProjectExtensions.GetFullPath(activeProject), "App_Start", str))); }
public string GetPackageVersion(CodeGenerationContext context, string id) { string str; if (context == null) { throw new ArgumentNullException("context"); } if (id == null) { throw new ArgumentNullException("id"); } IDictionary <string, string> packageVersions = PackageVersions.GetPackageVersions(context); packageVersions.TryGetValue(id, out str); return(str); }
public MvcViewScaffolderModel(CodeGenerationContext context) : base(context) { // These are the defaults for these settings, they may be overridden by saved settings IsLayoutPageSelected = true; IsPartialViewSelected = false; IsReferenceScriptLibrariesSelected = true; // For Views and Controllers, the Area name can be inferred from where in the tree the // scaffolder was launched. This will also work in the case that the 'Add View' context // menu item is invoked, because the folder containing the controller will be the ActiveProjectItem AreaName = GetAreaNameFromSelection(context.ActiveProjectItem); ViewTemplates = Enumerable.Empty<ViewTemplate>(); ModelTypes = ServiceProvider.GetService<ICodeTypeService>().GetAllCodeTypes(ActiveProject) .Where(codeType => codeType.IsValidWebProjectEntityType()) .Select(ct => new ModelType(ct)); DataContextTypes = ServiceProvider.GetService<ICodeTypeService>().GetAllCodeTypes(ActiveProject) .Where(codeType => codeType.IsValidDbContextType()) .Select(ct => new ModelType(ct)); // This is true for the view scaffolder - the controller scaffolder model sets this to // false by default. This will be removed when we split the controller model (which currently // inherits from this class). IsModelClassSupported = true; // When invoked from the 'Add View' context menu in the editor, we can pre-populate the output // path and view name based on the controller and action that invoked it. string value; if (context.Items.TryGetProperty<string>(DefaultViewNameKey, out value)) { ViewName = value; } else { ViewName = GetGeneratedName(MvcProjectUtil.ViewName, ViewFileExtension); } if (context.Items.TryGetProperty<string>(ControllerFolderNameKey, out value) && value != null) { SelectionRelativePath = Path.Combine(AreaRelativePath, CommonFolderNames.Views, value); } }
internal static async Task TestAddFieldAsync( string initial, string expected, Func <SemanticModel, ITypeSymbol> type = null, string name = "F", Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default, CodeGenerationContext context = null, bool hasConstantValue = false, object constantValue = null, bool addToCompilationUnit = false) { using var testContext = await TestContext.CreateAsync(initial, expected); var typeSymbol = type != null?type(testContext.SemanticModel) : null; var field = CodeGenerationSymbolFactory.CreateFieldSymbol( attributes: default,
public void RecordControllerTelemetryOptions(CodeGenerationContext context, ControllerScaffolderModel model) { if (context == null) { throw new ArgumentNullException("context"); } if (model == null) { throw new ArgumentNullException("model"); } WebApiControllerScaffolderOptions webApiControllerScaffolderOption = WebApiControllerScaffolderOptions.CreatedController; if (model.IsAsyncSelected) { webApiControllerScaffolderOption |= WebApiControllerScaffolderOptions.IsAsyncSelected; } context.AddTelemetryData("WebApiControllerScaffolderOptions", (uint)webApiControllerScaffolderOption); }
void DoGenerateInvocation( CodeGenerationContext context, CandidateInvocation candidate, CancellationToken cancellationToken) { var(methodSymbol, candidateInvocation, node) = candidate; if (methodSymbol == null || candidateInvocation == null) { context = context.UpdateFromCompilationContext(); (methodSymbol, candidateInvocation, node) = syntaxHelpers.ConvertToInvocation( node, context.Compilation.GetSemanticModel(node.SyntaxTree), cancellationToken); if (methodSymbol == null || candidateInvocation == null) { return; } } DoGenerateInvocation(context, methodSymbol, candidateInvocation, cancellationToken); }
/// <summary> /// This function verifies if a file by the name BundleConfig resides in the file system under the App_Start folder /// or if a class by the name BundleConfig is present in the default namespace. /// </summary> /// <param name="context">The <see cref="CodeGenerationContext"/> provided by the core scaffolder.</param> /// <returns><see langword="true" /> if a file by the name BundleConfig is present under the App_Start folder or /// if a class by the name BundleConfig is present in the default namespace; otherwise, <see langword="false" />.</returns> public static bool IsBundleConfigPresent(CodeGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } Project activeProject = context.ActiveProject; string defaultNamespace = activeProject.GetDefaultNamespace(); ICodeTypeService codeTypeService = context.ServiceProvider.GetService<ICodeTypeService>(); CodeType matchingConfigFile = codeTypeService.GetCodeType(activeProject, defaultNamespace + "." + CommonFilenames.BundleConfig); if (matchingConfigFile != null) { return true; } string configFileNameWithExtension = CommonFilenames.BundleConfig + "." + activeProject.GetCodeLanguage().CodeFileExtension; return File.Exists(Path.Combine(activeProject.GetFullPath(), CommonFolderNames.AppStart, configFileNameWithExtension)); }
public NuGetPackage GetPackage(CodeGenerationContext context, string id) { if (context == null) { throw new ArgumentNullException("context"); } if (id == null) { throw new ArgumentNullException("id"); } // There's no error handling here because these errors are of the 'your install is broken' // variety. string version = GetPackageVersion(context, id); Contract.Assert(!String.IsNullOrEmpty(version)); return new NuGetPackage(id, version, Repository); }
/// <summary> /// This function returns the package version corresponding to the specified package id. /// </summary> /// <param name="context">The <see cref="CodeGenerationContext"/> provided by core scaffolding.</param> /// <param name="id">The package id.</param> /// <returns>The package version if the package id is present in the package versions file, else returns null.</returns> public string GetPackageVersion(CodeGenerationContext context, string id) { if (context == null) { throw new ArgumentNullException("context"); } if (id == null) { throw new ArgumentNullException("id"); } IDictionary<string, string> packageVersions = PackageVersions.GetPackageVersions(context); string value; packageVersions.TryGetValue(id, out value); return value; }
protected override void GenerateClass(CodeGenerationContext codeGenerationContext, TypeDefinitionExpression expression) { using (var writer = this.GetTextWriterForFile(expression.Type.Name + ".h")) { var headerFileExpression = ClassHeaderExpressionBinder.Bind(codeGenerationContext, expression); var codeGenerator = new ObjectiveCodeGenerator(writer); codeGenerator.Generate(headerFileExpression); } using (var writer = this.GetTextWriterForFile(expression.Type.Name + ".m")) { var classFileExpression = ClassSourceExpressionBinder.Bind(codeGenerationContext, expression); var codeGenerator = new ObjectiveCodeGenerator(writer); codeGenerator.Generate(classFileExpression); } }
public bool IsDependencyInstalled(CodeGenerationContext context) { bool isODataAssemblyReferenced = ProjectReferences.IsAssemblyReferenced(context.ActiveProject, AssemblyVersions.ODataAssemblyName); // It is possible that this function could be called multiple times to check the status of dependency installation. // Hence, updating the value of any previously stored state with the most recent status of the referenced assembly. context.Items[ContextKeys.IsODataAssemblyReferencedKey] = isODataAssemblyReferenced; if (context == null) { throw new ArgumentNullException("context"); } bool isWebApiAssemblyReferenced = ProjectReferences.IsAssemblyReferenced(context.ActiveProject, AssemblyVersions.WebApiAssemblyName); // It is possible that this function could be called multiple times to check the status of dependency installation. // Hence, updating the value of any previously stored state with the most recent status of the referenced assembly. context.Items[ContextKeys.IsWebApiAssemblyReferencedKey] = isWebApiAssemblyReferenced; return isWebApiAssemblyReferenced && isODataAssemblyReferenced; }
protected DependencyInstaller(CodeGenerationContext context, IVisualStudioIntegration visualStudioIntegration) { if (context == null) { throw new ArgumentNullException("context"); } if (visualStudioIntegration == null) { throw new ArgumentNullException("visualStudioIntegration"); } Context = context; VisualStudioIntegration = visualStudioIntegration; ActionsService = context.ServiceProvider.GetService<ICodeGeneratorActionsService>(); FilesLocatorService = context.ServiceProvider.GetService<ICodeGeneratorFilesLocator>(); AppStartFileNames = new Dictionary<string, string>(); }
public ConfigScaffolderModel(CodeGenerationContext context) : base(context) { DataContextTypes = ServiceProvider.GetService<ICodeTypeService>().GetAllCodeTypes(ActiveProject) .Where(codeType => codeType.IsValidDbContextType()) .Select(ct => new ModelType(ct)); ConfigTypes = ServiceProvider.GetService<ICodeTypeService>().GetAllCodeTypes(ActiveProject) .Where(codeType => codeType.IsValidConfigType()) .Select(ct => new ModelType(ct)); if (DataContextTypes.FirstOrDefault() == null) { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, Resources.InvalidResource, "context class")); } if (ConfigTypes.FirstOrDefault() == null) { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, Resources.InvalidResource, "config class")); } }