Beispiel #1
0
 public CreateTableContext(
     IDynamicAssemblyBuilder dynamicAssemblyBuilder,
     CreateTableCommand tableCommand)
 {
     _dynamicAssemblyBuilder = dynamicAssemblyBuilder;
     _tableCommand           = tableCommand;
 }
Beispiel #2
0
        protected override string DoGenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder)
        {
#pragma warning disable CS0612, CS0618
            return($"{typeof(DiContainerBuilderConfiguration).FullName}.{nameof(DiContainerBuilderConfiguration.DiContainerStatic)}.{nameof(IDiContainer.Resolve)}<{ValueTypeInfo.TypeCSharpFullName}>()");

#pragma warning restore CS0612, CS0618
        }
        public string GenerateModuleClassCode(IDynamicAssemblyBuilder dynamicAssemblyBuilder, IAssemblyLocator assemblyLocator, string moduleClassNamespace, string moduleClassName,
                                              IEnumerable <BindingConfigurationForFile> moduleServiceConfigurationElements)
        {
            // Lets add this assembly, since we are referencing DiHelper in auto-generated code.
            dynamicAssemblyBuilder.AddReferencedAssembly(typeof(NinjectDiManager));
            dynamicAssemblyBuilder.AddReferencedAssembly(typeof(NinjectModule));

            var moduleClassContents = new StringBuilder();

            moduleClassContents.AppendLine("using System.Linq;");

            moduleClassContents.AppendLine($"namespace {moduleClassNamespace}");
            moduleClassContents.AppendLine("{");

            moduleClassContents.AppendLine($"public class {moduleClassName} : {typeof(NinjectModule).FullName}");
            moduleClassContents.AppendLine("{");

            DiManagerImplementationHelper.AddCodeForOnDiContainerReadyMethod(moduleClassContents);
            // Add Load() method
            moduleClassContents.AppendLine("public override void Load()");
            moduleClassContents.AppendLine("{");

            foreach (var service in moduleServiceConfigurationElements)
            {
                AddServiceBindings(moduleClassContents, service, dynamicAssemblyBuilder);
            }

            moduleClassContents.AppendLine("}");
            // End Load() method

            moduleClassContents.AppendLine("}");
            moduleClassContents.AppendLine("}");
            return(moduleClassContents.ToString());
        }
Beispiel #4
0
        protected override string DoGenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder)
        {
            var cSharpCode = new StringBuilder();

            cSharpCode.Append("new ");
            switch (CollectionType)
            {
            case CollectionType.Array:
                cSharpCode.Append($"{ItemTypeInfo.TypeCSharpFullName}[{_valueInitializerElements.Count}] {{");
                cSharpCode.Append(string.Join(",", _valueInitializerElements.Select(x => x.GenerateValueCSharp(dynamicAssemblyBuilder))));
                cSharpCode.Append("}");
                break;

            case CollectionType.Enumerable:
            case CollectionType.ReadOnlyList:
            case CollectionType.List:

                cSharpCode.Append($"System.Collections.Generic.List<{ItemTypeInfo.TypeCSharpFullName}>({_valueInitializerElements.Count}) {{");
                cSharpCode.Append(string.Join(",", _valueInitializerElements.Select(x => x.GenerateValueCSharp(dynamicAssemblyBuilder))));
                cSharpCode.Append("}");
                break;
            }

            return(cSharpCode.ToString());
        }
 public void GenerateCSharp(ICustomAutoGeneratedServiceInfo customAutoGeneratedServiceInfo,
                            IDynamicAssemblyBuilder dynamicAssemblyBuilder,
                            string generatedClassNamespace, string generatedClassName)
 {
     GenerateCSharpCode(dynamicAssemblyBuilder.StartDynamicallyGeneratedClass(generatedClassName,
                                                                              new[]
     {
         customAutoGeneratedServiceInfo.ImplementedInterface.GetTypeNameInCSharpClass()
     }, generatedClassNamespace));
 }
        public string GenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder)
        {
            if (!_addCodeGenerateValueCSharpWasCalled)
            {
                _addCodeGenerateValueCSharpWasCalled = true;
                AddCodeOnGenerateValueCSharp(dynamicAssemblyBuilder);
            }

            return(DoGenerateValueCSharp(dynamicAssemblyBuilder));
        }
Beispiel #7
0
 public SchemaUpdateService(
     IDynamicAssemblyBuilder dynamicAssemblyBuilder,
     ISessionFactoryHolder sessionFactoryHolder,
     ShellSettings shellSettings,
     ISessionLocator sessionLocator,
     IEnumerable<ICommandInterpreter> commandInterpreters,
     IReportsCoordinator reportsCoordinator) {
     _dynamicAssemblyBuilder = dynamicAssemblyBuilder;
     _sessionFactoryHolder = sessionFactoryHolder;
     var interpreter = new DefaultDataMigrationInterpreter(shellSettings, sessionLocator, commandInterpreters, sessionFactoryHolder, reportsCoordinator);
     _schemaBuilder = new SchemaBuilder(interpreter, "", s => s.Replace(".", "_"));
 }
        public override void GenerateAutoImplementedServiceClassCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder, string dynamicImplementationsNamespace, out string generatedClassFullName)
        {
            //if (ReferencedAssembliesElement != null)
            //    foreach (var assemblyReference in ReferencedAssembliesElement.ReferencedAssemblies)
            //        dynamicAssemblyBuilder.AddReferencedAssembly(assemblyReference.Assembly.AbsolutePath);

            var className = $"{ImplementedInterfaceTypeInfo.Type.Name}_{GlobalsCoreAmbientContext.Context.GenerateUniqueId()}";

            generatedClassFullName = $"{dynamicImplementationsNamespace}.{className}";

            AutoServiceCodeGenerator.CustomAutoServiceCodeGenerator.GenerateCSharp(_customAutoGeneratedServiceInfo,
                                                                                   dynamicAssemblyBuilder, dynamicImplementationsNamespace, className);
        }
Beispiel #9
0
        public SchemaUpdateService(
            IDynamicAssemblyBuilder dynamicAssemblyBuilder,
            ISessionFactoryHolder sessionFactoryHolder,
            ShellSettings shellSettings,
            ISessionLocator sessionLocator,
            IEnumerable <ICommandInterpreter> commandInterpreters,
            IReportsCoordinator reportsCoordinator)
        {
            _dynamicAssemblyBuilder = dynamicAssemblyBuilder;
            _sessionFactoryHolder   = sessionFactoryHolder;
            var interpreter = new DefaultDataMigrationInterpreter(shellSettings, sessionLocator, commandInterpreters, sessionFactoryHolder, reportsCoordinator);

            _schemaBuilder = new SchemaBuilder(interpreter, "", s => s.Replace(".", "_"));
        }
        protected override string DoGenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder)
        {
            var cSharpCode = new StringBuilder();

            if (_createInstanceMethodName != null)
            {
                var dynamicImplementationsClass = dynamicAssemblyBuilder.GetDynamicallyGeneratedClass(DynamicCodeGenerationHelpers.DynamicImplementationsClassName);
                cSharpCode.Append($"{dynamicImplementationsClass.ClassFullName}.{_createInstanceMethodName}()");
            }
            else
            {
                AddConstructorCode(dynamicAssemblyBuilder, cSharpCode);
            }

            return(cSharpCode.ToString());
        }
Beispiel #11
0
        public string GenerateValueCSharp(ClassMemberData classMemberData, IDynamicAssemblyBuilder dynamicAssemblyBuilder)
        {
            var valueCSharpStrBldr = new StringBuilder();

            if (classMemberData.IsInjectedClassMember)
            {
                var dynamicallyGeneratedClass = dynamicAssemblyBuilder.GetDynamicallyGeneratedClass(DynamicCodeGenerationHelpers.ClassMembersClassName);

                if (!_injectedTypesToVariableNameCSharpFile.TryGetValue(classMemberData.ClassInfo.Type, out var variableName))
                {
                    variableName = $"{classMemberData.ClassInfo.Type.Name}_{GlobalsCoreAmbientContext.Context.GenerateUniqueId()}";

                    _injectedTypesToVariableNameCSharpFile[classMemberData.ClassInfo.Type] = variableName;

                    var variableInitializationCode = new StringBuilder();

                    variableInitializationCode.AppendFormat("public static {0} {1}=", classMemberData.ClassInfo.TypeCSharpFullName, variableName);

#pragma warning disable CS0612, CS0618
                    variableInitializationCode.Append($"{typeof(DiContainerBuilderConfiguration).FullName}.{nameof(DiContainerBuilderConfiguration.DiContainerStatic)}.{nameof(IDiContainer.Resolve)}");
#pragma warning restore CS0612, CS0618

                    variableInitializationCode.Append($"<{classMemberData.ClassInfo.TypeCSharpFullName}>();");

                    dynamicallyGeneratedClass.AddCodeLine(variableInitializationCode.ToString());
                }

                valueCSharpStrBldr.Append($"{dynamicallyGeneratedClass.ClassFullName}.{variableName}");
            }
            else
            {
                valueCSharpStrBldr.Append($"{classMemberData.ClassInfo.TypeCSharpFullName}");
            }

            // Add class member name
            valueCSharpStrBldr.Append($".{classMemberData.ClassMemberInfo.Name}");

            if (classMemberData.ClassMemberCategory == ClassMemberCategory.Method)
            {
                valueCSharpStrBldr.Append("(");
                valueCSharpStrBldr.Append(string.Join(",", classMemberData.Parameters.Select(x => x.GenerateValueCSharp(dynamicAssemblyBuilder))));
                valueCSharpStrBldr.Append(")");
            }


            return(valueCSharpStrBldr.ToString());
        }
Beispiel #12
0
 public RelationshipService(
     IRepository<RelationshipRecord> relationshipRepository,
     IRepository<OneToManyRelationshipRecord> oneToManyRepository,
     IRepository<ManyToManyRelationshipRecord> manyToManyRepository,
     IContentDefinitionManager contentDefinitionManager,
     IDynamicAssemblyBuilder dynamicAssemblyBuilder,
     ISchemaUpdateService schemaUpdateService,
     IContentManager contentManager,
     IContentMetadataService contentMetadataService) {
     _relationshipRepository = relationshipRepository;
     _oneToManyRepository = oneToManyRepository;
     _manyToManyRepository = manyToManyRepository;
     _contentDefinitionManager = contentDefinitionManager;
     _dynamicAssemblyBuilder = dynamicAssemblyBuilder;
     _schemaUpdateService = schemaUpdateService;
     _contentManager = contentManager;
     _contentMetadataService = contentMetadataService;
 }
Beispiel #13
0
 public RelationshipService(
     IRepository <RelationshipRecord> relationshipRepository,
     IRepository <OneToManyRelationshipRecord> oneToManyRepository,
     IRepository <ManyToManyRelationshipRecord> manyToManyRepository,
     IContentDefinitionManager contentDefinitionManager,
     IDynamicAssemblyBuilder dynamicAssemblyBuilder,
     ISchemaUpdateService schemaUpdateService,
     IContentManager contentManager,
     IContentMetadataService contentMetadataService)
 {
     _relationshipRepository   = relationshipRepository;
     _oneToManyRepository      = oneToManyRepository;
     _manyToManyRepository     = manyToManyRepository;
     _contentDefinitionManager = contentDefinitionManager;
     _dynamicAssemblyBuilder   = dynamicAssemblyBuilder;
     _schemaUpdateService      = schemaUpdateService;
     _contentManager           = contentManager;
     _contentMetadataService   = contentMetadataService;
 }
    public void GenerateCSharp(ICustomAutoGeneratedServiceInfo customAutoGeneratedServiceInfo,
                               IDynamicAssemblyBuilder dynamicAssemblyBuilder,
                               string generatedClassNamespace, string generatedClassName)
    {
        dynamicAssemblyBuilder.AddReferencedAssembly(
            Path.Combine(Helpers.GetTestFilesFolderPath(),
                         @"DynamicallyLoadedDlls\TestProjects.DynamicallyLoadedAssembly1.dll"));

        dynamicAssemblyBuilder.AddReferencedAssembly(
            typeof(SharedServices.Interfaces.IInterface1));

        var classInfo = dynamicAssemblyBuilder.StartDynamicallyGeneratedClass(
            generatedClassName, generatedClassNamespace);

        var methodInfo = classInfo.StartMethod("GetValue", typeof(int),
                                               Array.Empty <IMethodParameterInfo>(),
                                               AccessLevel.Public, false, false);

        methodInfo.AddCodeLine("=> 10;");
    }
        protected override void AddCodeOnGenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder)
        {
            List <IInjectedPropertyElement> injectedProperties;

            if (InjectedProperties == null)
            {
                injectedProperties = new List <IInjectedPropertyElement>();
            }
            else
            {
                injectedProperties = new List <IInjectedPropertyElement>(InjectedProperties.AllProperties);
            }

            if (injectedProperties.Count > 0)
            {
                var dynamicImplementationsClass = dynamicAssemblyBuilder.GetDynamicallyGeneratedClass(DynamicCodeGenerationHelpers.DynamicImplementationsClassName);

                var createInstanceMethodData = dynamicImplementationsClass.StartMethod("CreateInstance", ValueTypeInfo.Type, new IMethodParameterInfo[0], AccessLevel.Public, true, true);
                _createInstanceMethodName = createInstanceMethodData.MethodName;

                createInstanceMethodData.AddCodeLine("{");

                createInstanceMethodData.AddCode("var instance=");

                var cSharpCode = new StringBuilder();
                AddConstructorCode(dynamicAssemblyBuilder, cSharpCode);
                createInstanceMethodData.AddCode(cSharpCode.ToString());

                createInstanceMethodData.AddCodeLine(";");

                foreach (var injectedProperty in injectedProperties)
                {
                    createInstanceMethodData.AddCodeLine($"instance.{injectedProperty.Name}={injectedProperty.GenerateValueCSharp(dynamicAssemblyBuilder)};");
                }

                createInstanceMethodData.AddCodeLine("return instance;");

                createInstanceMethodData.AddCodeLine("}");
            }
        }
Beispiel #16
0
        /// <summary>
        /// Dynamically generated class data.
        /// </summary>
        /// <param name="dynamicAssemblyBuilder">An instance of <see cref="IDynamicAssemblyBuilder"/></param>
        /// <param name="className">Name of the class.</param>
        /// <param name="classNamespace">The class namespace. If the value is null, the default namespace will be used.</param>
        /// <param name="baseClassesAndInterfaces">List of full base class or interface names.</param>
        public DynamicallyGeneratedClass([NotNull] IDynamicAssemblyBuilder dynamicAssemblyBuilder,
                                         [NotNull] string className, [NotNull] string classNamespace,
                                         [NotNull, ItemNotNull] IEnumerable <string> baseClassesAndInterfaces)
        {
            _dynamicAssemblyBuilder = dynamicAssemblyBuilder;

            ClassName      = className;
            ClassNamespace = classNamespace;
            ClassFullName  = $"{ClassNamespace}.{ClassName}";

            _sharpCode.AppendLine($"namespace {ClassNamespace}");
            _sharpCode.AppendLine("{");
            _sharpCode.AppendLine($"public class {ClassName}");

            if (baseClassesAndInterfaces.Any())
            {
                _sharpCode.Append(": ");
                _sharpCode.AppendLine(string.Join(",", baseClassesAndInterfaces));
            }

            _sharpCode.AppendLine("{");
        }
 public RelationshipService(
     IRepository<RelationshipRecord> relationshipRepository,
     IRepository<OneToManyRelationshipRecord> oneToManyRepository,
     IRepository<ManyToManyRelationshipRecord> manyToManyRepository,
     IRepository<ContentPartDefinitionRecord> contentPartRepository,
     IContentDefinitionManager contentDefinitionManager,
     IContentDefinitionService contentDefinitionService,
     IDynamicAssemblyBuilder dynamicAssemblyBuilder,
     ISchemaUpdateService schemaUpdateService,
     IContentManager contentManager,
     IFieldEvents fieldEvents) {
     _relationshipRepository = relationshipRepository;
     _oneToManyRepository = oneToManyRepository;
     _manyToManyRepository = manyToManyRepository;
     _contentPartRepository = contentPartRepository;
     _contentDefinitionManager = contentDefinitionManager;
     _contentDefinitionService = contentDefinitionService;
     _dynamicAssemblyBuilder = dynamicAssemblyBuilder;
     _schemaUpdateService = schemaUpdateService;
     _contentManager = contentManager;
     _fieldEvents = fieldEvents;
 }
        private void AddConstructorCode([NotNull] IDynamicAssemblyBuilder dynamicAssemblyBuilder,
                                        [NotNull] StringBuilder cSharpCode)
        {
            cSharpCode.Append($"new {ValueTypeInfo.TypeCSharpFullName}(");

            if (Parameters != null)
            {
                var parameterIndex = 0;
                foreach (var parameterElement in Parameters.AllParameters)
                {
                    if (parameterIndex > 0)
                    {
                        cSharpCode.Append(", ");
                    }

                    cSharpCode.Append(parameterElement.GenerateValueCSharp(dynamicAssemblyBuilder));
                    ++parameterIndex;
                }
            }

            cSharpCode.Append(")");
        }
        private void AddMethodBodyForImplementedMethod([NotNull] IDynamicAssemblyBuilder dynamicAssemblyBuilder,
                                                       [NotNull] IAutoGeneratedServiceMethodElement autoGeneratedServiceMethodElement,
                                                       [NotNull] StringBuilder classStrBldr,
                                                       [NotNull] StringBuilder classMembersStrBldr)
        {
            IDeserializedValue getDeserializedValue(IValueInitializer valueInitializer)
            {
                if (valueInitializer is IDeserializedValue deserializedValue)
                {
                    return(deserializedValue);
                }

                if (valueInitializer is IValueInitializerElementDecorator valueInitializerElementDecorator)
                {
                    return(valueInitializerElementDecorator.DecoratedValueInitializerElement as IDeserializedValue);
                }

                return(null);
            }

            void addReturnedValueCSharp(IAutoGeneratedMemberReturnValuesSelectorElement autoGeneratedMemberReturnValuesSelector)
            {
                // For now only one return value is supported
                var returnedValueElement = autoGeneratedMemberReturnValuesSelector.ReturnedValueElements[0];

                var isDeserializedValueInitializer = getDeserializedValue(returnedValueElement) != null;

                if (autoGeneratedServiceMethodElement.ReuseReturnedValue || isDeserializedValueInitializer)
                {
                    var returnedVariableName = $"_{autoGeneratedServiceMethodElement.ImplementedMehodInfo.Name}_Returned_{GlobalsCoreAmbientContext.Context.GenerateUniqueId()}";
                    classMembersStrBldr.Append($"private {autoGeneratedServiceMethodElement.ValueTypeInfo.TypeCSharpFullName} {returnedVariableName}");

                    if (isDeserializedValueInitializer ||
                        // If ReuseReturnedValue is true, we always pre-store the returned value, if the value type is a struct,
                        // since we cannot compare the value with null
                        returnedValueElement.ValueTypeInfo.Type.IsValueType)
                    {
                        classMembersStrBldr.Append($"={returnedValueElement.GenerateValueCSharp(dynamicAssemblyBuilder)}");
                    }
                    else
                    {
                        // If we didn't already set the value of variable in stored the variable, lets check for null first.
                        classStrBldr.AppendLine($"if ({returnedVariableName} == null)");
                        classStrBldr.AppendLine($"{returnedVariableName} = {returnedValueElement.GenerateValueCSharp(dynamicAssemblyBuilder)};");
                    }

                    classMembersStrBldr.AppendLine(";");

                    classStrBldr.AppendLine($"return {returnedVariableName};");
                }
                else
                {
                    classStrBldr.AppendLine($"return {returnedValueElement.GenerateValueCSharp(dynamicAssemblyBuilder)};");
                }
            }

            void addParameterValueCSharp(ParameterInfo parameterInfo, IValueInitializer valueInitializer)
            {
                var deserializedValue = getDeserializedValue(valueInitializer);

                if (deserializedValue != null)
                {
                    var variableName = $"_{autoGeneratedServiceMethodElement.ImplementedMehodInfo.Name}_{GlobalsCoreAmbientContext.Context.GenerateUniqueId()}";

                    classMembersStrBldr.Append($"private {parameterInfo.ParameterType.GetTypeNameInCSharpClass()} {variableName}=");
                    classMembersStrBldr.Append(valueInitializer.GenerateValueCSharp(dynamicAssemblyBuilder));
                    classMembersStrBldr.AppendLine(";");

                    classStrBldr.Append(variableName);
                }
                else
                {
                    if (parameterInfo.ParameterType != valueInitializer.ValueTypeInfo.Type)
                    {
                        classStrBldr.Append($"({parameterInfo.ParameterType.GetTypeNameInCSharpClass()})");
                    }

                    classStrBldr.Append(valueInitializer.GenerateValueCSharp(dynamicAssemblyBuilder));
                }
            }

            classStrBldr.AppendLine();
            classStrBldr.AppendLine("{");

            var methodParameters = autoGeneratedServiceMethodElement.ImplementedMehodInfo.GetParameters();

            foreach (var returnedValueSelectorsForIfCase in autoGeneratedServiceMethodElement.ReturnedValueSelectorsForIfCase)
            {
                classStrBldr.Append("if(");
                for (var i = 0; i < returnedValueSelectorsForIfCase.ParameterValueInitializers.Count; ++i)
                {
                    if (i > 0)
                    {
                        classStrBldr.Append(" && ");
                    }

                    var parameterValueInitializer = returnedValueSelectorsForIfCase.ParameterValueInitializers[i];
                    var parameterInfo             = methodParameters[parameterValueInitializer.ParameterIndex];

                    if (returnedValueSelectorsForIfCase.ParameterValueInitializers.Count > 1)
                    {
                        classStrBldr.Append("(");
                    }

                    if (!parameterInfo.ParameterType.IsValueType)
                    {
                        classStrBldr.Append($"{parameterInfo.Name}!=null && ");
                    }

                    classStrBldr.Append($"{parameterInfo.Name}");

                    if (IsEqualsOperatorUsedInIfStatment(parameterInfo.ParameterType))
                    {
                        classStrBldr.Append("==");

                        addParameterValueCSharp(parameterInfo, parameterValueInitializer.ValueInitializer);
                    }
                    else
                    {
                        classStrBldr.Append(".Equals(");
                        addParameterValueCSharp(parameterInfo, parameterValueInitializer.ValueInitializer);
                        classStrBldr.Append(")");
                    }

                    if (returnedValueSelectorsForIfCase.ParameterValueInitializers.Count > 1)
                    {
                        classStrBldr.Append(")");
                    }
                }

                classStrBldr.AppendLine(")");
                classStrBldr.AppendLine("{");

                addReturnedValueCSharp(returnedValueSelectorsForIfCase);
                classStrBldr.AppendLine("}");
            }

            if (autoGeneratedServiceMethodElement.ReturnedValueSelectorsForDefaultCase != null)
            {
                addReturnedValueCSharp(autoGeneratedServiceMethodElement.ReturnedValueSelectorsForDefaultCase);
            }
            else
            {
                // We should never get here, however lets consider this case, in case we make the default element optional.
                classStrBldr.AppendLine($"return default({autoGeneratedServiceMethodElement.ImplementedMehodInfo.ReturnType.GetTypeNameInCSharpClass()})");
            }

            classStrBldr.AppendLine("}");
        }
        public string GenerateValueCSharp(IConfigurationFileElement requestingConfigurationFileElement, ITypeInfo valueTypeInfo, string valueAsString, IDynamicAssemblyBuilder dynamicAssemblyBuilder)
        {
            var deserializer = _typeBasedSimpleSerializerAggregator.GetSerializerForType(valueTypeInfo.Type);

            if (deserializer is IValueToCSharpCodeConverter valueToCSharpCodeConverter && deserializer.TryDeserialize(valueAsString, out var deserializedvalue))
            {
                return(valueToCSharpCodeConverter.GenerateCSharpCode(deserializedvalue));
            }

#pragma warning disable CS0612, CS0618
            return($"{typeof(DiContainerBuilderConfiguration).FullName}.{nameof(DiContainerBuilderConfiguration.SerializerAggregatorStatic)}.{nameof(DiContainerBuilderConfiguration.SerializerAggregatorStatic.Deserialize)}<{valueTypeInfo.TypeCSharpFullName}>(@\"{valueAsString}\")");

#pragma warning restore CS0612, CS0618
        }
Beispiel #21
0
 /// <summary>
 ///     Generates a code that returns an instance of a value of type specified by property <see cref="ValueType" />.
 /// </summary>
 /// <param name="dynamicAssemblyBuilder">The dynamic assembly builder.</param>
 /// <returns></returns>
 public string GenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder)
 {
     return(_settingElement.GenerateValueCSharp(dynamicAssemblyBuilder));
 }
 protected abstract string DoGenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder);
 protected virtual void AddCodeOnGenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder)
 {
 }
        private void AddServiceBindings([NotNull] StringBuilder moduleClassContents, [NotNull] BindingConfigurationForFile serviceElement, [NotNull] IDynamicAssemblyBuilder dynamicAssemblyBuilder)
        {
            if (serviceElement.RegisterIfNotRegistered)
            {
                moduleClassContents.AppendLine($"if (!Kernel.GetBindings(typeof({serviceElement.ServiceType.GetTypeNameInCSharpClass()})).Any())");
                moduleClassContents.AppendLine("{");
            }

            foreach (var serviceImplementation in serviceElement.Implementations)
            {
                moduleClassContents.Append($"Bind<{serviceElement.ServiceType.GetTypeNameInCSharpClass()}>()");

                ITypeBasedBindingImplementationConfigurationForFile typeBasedBindingImplementationConfigurationForFile = null;
                if (serviceImplementation is ITypeBasedBindingImplementationConfigurationForFile)
                {
                    typeBasedBindingImplementationConfigurationForFile = (ITypeBasedBindingImplementationConfigurationForFile)serviceImplementation;

                    if (typeBasedBindingImplementationConfigurationForFile.Parameters == null)
                    {
                        if (serviceElement.IsSelfBoundService)
                        {
                            moduleClassContents.Append(".ToSelf()");
                        }
                        else
                        {
                            moduleClassContents.Append($".To<{typeBasedBindingImplementationConfigurationForFile.ImplementationType.GetTypeNameInCSharpClass()}>()");
                        }
                    }
                    else
                    {
                        moduleClassContents.Append($".ToMethod(context => new {typeBasedBindingImplementationConfigurationForFile.ImplementationType.GetTypeNameInCSharpClass()}(");

                        for (var i = 0; i < typeBasedBindingImplementationConfigurationForFile.Parameters.Length; ++i)
                        {
                            if (i > 0)
                            {
                                moduleClassContents.Append(", ");
                            }

                            var parameter = typeBasedBindingImplementationConfigurationForFile.Parameters[i];

                            moduleClassContents.Append(parameter.GenerateValueCSharp(
                                                           //(serviceType) => $"({serviceType.FullName})context.Kernel.GetService(typeof({serviceType.FullName}))",
                                                           dynamicAssemblyBuilder));
                        }

                        moduleClassContents.Append("))");
                    }
                }
                else if (serviceImplementation is ValueBasedBindingImplementationConfigurationForFile valueBasedBindingImplementationConfigurationForFile)
                {
                    moduleClassContents.Append($".ToMethod(context => {valueBasedBindingImplementationConfigurationForFile.ValueInitializer.GenerateValueCSharp(dynamicAssemblyBuilder)})");
                }
                else if (serviceImplementation is IServiceToProxyBindingImplementationConfigurationForFile serviceToProxyBindingImplementationConfigurationForFile)
                {
                    moduleClassContents.AppendFormat(".ToMethod(context => ({0})context.Kernel.GetService(typeof({0})))",
                                                     serviceImplementation.ImplementationType.GetTypeNameInCSharpClass());
                }

                // Add WhenInjected code as in example below
                switch (serviceImplementation.ConditionalInjectionType)
                {
                case ConditionalInjectionType.None:
                    // No conditional injection.
                    break;

                case ConditionalInjectionType.WhenInjectedInto:
                    moduleClassContents.Append($".WhenInjectedInto<{serviceImplementation.WhenInjectedIntoType.GetTypeNameInCSharpClass()}>()");
                    break;

                case ConditionalInjectionType.WhenInjectedExactlyInto:
                    moduleClassContents.Append($".WhenInjectedExactlyInto<{serviceImplementation.WhenInjectedIntoType.GetTypeNameInCSharpClass()}>()");
                    break;

                default:
                    throw new UnsupportedEnumValueException(serviceImplementation.ConditionalInjectionType);
                }

                // Add resolution
                moduleClassContents.Append(".");
                switch (serviceImplementation.ResolutionScope)
                {
                case DiResolutionScope.Singleton:
                    moduleClassContents.Append("InSingletonScope()");
                    break;

                case DiResolutionScope.Transient:
                    moduleClassContents.Append("InTransientScope()");
                    break;

                case DiResolutionScope.ScopeLifetime:
                    moduleClassContents.Append("InScope(context => _diContainer.CurrentLifeTimeScope)");
                    break;

                // Thread scope is not supported by Autofac, and therefore not used in Ninject as well.
                //case DiResolutionScope.Thread:
                //    moduleClassContents.Append("InThreadScope()");
                //    break;
                default:
                    throw new UnsupportedResolutionScopeException(serviceImplementation);
                }

                // Add injected properties
                if (typeBasedBindingImplementationConfigurationForFile != null)
                {
                    if (typeBasedBindingImplementationConfigurationForFile.InjectedProperties?.Any() ?? false)
                    {
                        moduleClassContents.AppendLine($".OnActivation<{typeBasedBindingImplementationConfigurationForFile.ImplementationType.GetTypeNameInCSharpClass()}>(activatedObject =>");
                        moduleClassContents.AppendLine("{");

                        foreach (var injectedProperty in typeBasedBindingImplementationConfigurationForFile.InjectedProperties)
                        {
                            moduleClassContents.Append($"activatedObject.{injectedProperty.Name}=");

                            moduleClassContents.Append(injectedProperty.GenerateValueCSharp(//(serviceType) => $"_diContainer.Resolve<{serviceType.FullName}>()",
                                                           dynamicAssemblyBuilder));

                            moduleClassContents.Append(";");

                            moduleClassContents.AppendLine();
                        }

                        moduleClassContents.Append("})");
                    }
                }

                moduleClassContents.AppendLine(";");
            }

            if (serviceElement.RegisterIfNotRegistered)
            {
                moduleClassContents.AppendLine("}");
            }
        }
Beispiel #25
0
    /// <inheritdoc />
    public void GenerateCSharp(ICustomAutoGeneratedServiceInfo customAutoGeneratedServiceInfo, IDynamicAssemblyBuilder dynamicAssemblyBuilder, string generatedClassNamespace, string generatedClassName)
    {
        // Use IDynamicAssemblyBuilder.AddReferencedAssembly(string assemblyPath) or
        // IDynamicAssemblyBuilder.AddReferencedAssembly(Type typeInAssembly) to add assemblies that will be
        // referenced by auto-generated assembly if types in these assemblies are used in auto-generated code.
        dynamicAssemblyBuilder.AddReferencedAssembly(Path.Combine(Helpers.GetTestFilesFolderPath(), @"DynamicallyLoadedDlls\TestProjects.DynamicallyLoadedAssembly1.dll"));
        dynamicAssemblyBuilder.AddReferencedAssembly(typeof(IInterface1));

        // By now Validate(ICustomAutoGeneratedServiceInfo customAutoGeneratedServiceInfo) already validated
        // that a single method with attribute is present in interface.
        var methodInfo = customAutoGeneratedServiceInfo.ImplementedInterface.GetMethods().First();

        var attribute = (SimpleMethodMetadataAttribute)methodInfo.GetCustomAttributes().FirstOrDefault(x => x is SimpleMethodMetadataAttribute);

        var dynamicClass = dynamicAssemblyBuilder.StartDynamicallyGeneratedClass(generatedClassName,
                                                                                 new[]
        {
            customAutoGeneratedServiceInfo.ImplementedInterface.GetTypeNameInCSharpClass()
        },
                                                                                 generatedClassNamespace);

        var methodData = dynamicClass.StartInterfaceImplementationMethod(methodInfo, false);

        methodData.AddCodeLine("{");

        methodData.AddCodeLine("var testReferencedAssembly = new DynamicallyLoadedAssembly1.Dog(40);");

        methodData.AddCodeLine($"return {attribute.ReturnedValue};");
        methodData.AddCodeLine("}");
    }
Beispiel #26
0
 public CreateTableContext(
     IDynamicAssemblyBuilder dynamicAssemblyBuilder,
     CreateTableCommand tableCommand) {
     _dynamicAssemblyBuilder = dynamicAssemblyBuilder;
     _tableCommand = tableCommand;
 }
Beispiel #27
0
 /// <summary>
 ///     Generates a code that returns an instance of a value of type specified by property <see cref="ValueType" />.
 /// </summary>
 /// <param name="dynamicAssemblyBuilder">The dynamic assembly builder.</param>
 /// <returns></returns>
 public string GenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder)
 {
     return(_classMemberValueInitializerHelper.GenerateValueCSharp(ClassMemberData, dynamicAssemblyBuilder));
 }
 protected virtual string DoGenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder)
 {
     return(InterceptValueInitialzerExceptionWithReturnedValue(
                () => DecoratedValueInitializerElement.GenerateValueCSharp(dynamicAssemblyBuilder)));
 }
        private void AddMethodBodyForNonImplementedMethodWithSimilarImplementedMethod([NotNull] IDynamicAssemblyBuilder dynamicAssemblyBuilder,
                                                                                      [NotNull] MethodInfo methodInfo, [NotNull] IAutoGeneratedServiceMethodElement similarAutoGeneratedServiceMethodElement,
                                                                                      [NotNull] StringBuilder classStrBldr)
        {
            var autoimplementedMethodInfo = similarAutoGeneratedServiceMethodElement.ImplementedMehodInfo;

            classStrBldr.Append($"=>(({autoimplementedMethodInfo.DeclaringType.GetTypeNameInCSharpClass()})this).");
            classStrBldr.Append($"{autoimplementedMethodInfo.Name}(");

            var parameters = methodInfo.GetParameters();

            for (var i = 0; i < parameters.Length; ++i)
            {
                if (i > 0)
                {
                    classStrBldr.Append(", ");
                }

                var parameterInfo = parameters[i];

                if (parameterInfo.IsOut)
                {
                    classStrBldr.Append("out ");
                }
                else if (parameterInfo.ParameterType.IsByRef)
                {
                    classStrBldr.Append("ref ");
                }
                else if (parameterInfo.IsIn)
                {
                    classStrBldr.Append("in ");
                }

                classStrBldr.Append(parameterInfo.Name);
            }

            classStrBldr.Append(");");
        }
Beispiel #30
0
    public void GenerateCSharp(ICustomAutoGeneratedServiceInfo customAutoGeneratedServiceInfo, IDynamicAssemblyBuilder dynamicAssemblyBuilder, string generatedClassNamespace, string generatedClassName)
    {
        if (_simulateGenerateCSharpFailure)
        {
            throw new Exception($"{nameof(GenerateCSharp)} failed.");
        }

        var dynamicallyGeneratedClass = dynamicAssemblyBuilder.StartDynamicallyGeneratedClass(generatedClassName,
                                                                                              new [] { customAutoGeneratedServiceInfo.ImplementedInterface.FullName }, generatedClassNamespace);

        dynamicallyGeneratedClass.AddCode("public override int GetColor() => 10");

        if (!_simulateAssemblyBuildFailure)
        {
            dynamicallyGeneratedClass.AddCode(";");
        }
    }
        public override void GenerateAutoImplementedServiceClassCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder,
                                                                       string dynamicImplementationsNamespace,
                                                                       out string generatedClassFullName)
        {
            // Add assemblies referenced by service
            var className = $"{ImplementedInterfaceTypeInfo.Type.Name}_{GlobalsCoreAmbientContext.Context.GenerateUniqueId()}";

            generatedClassFullName = $"{dynamicImplementationsNamespace}.{className}";

            var classStrBldr = new StringBuilder(5000);
            var classMemberVariablesStrBldr = new StringBuilder(1000);

            classStrBldr.AppendLine();
            classStrBldr.AppendLine("using System;");

            classStrBldr.AppendLine($"namespace {dynamicImplementationsNamespace}");
            classStrBldr.AppendLine("{");
            classStrBldr.AppendLine($"public sealed class {className}: {ImplementedInterfaceTypeInfo.TypeCSharpFullName}");
            classStrBldr.AppendLine("{");

            void ProcessType(Type type, ref bool stopProcessingParam)
            {
                foreach (var methodInfo in type.GetMethods())
                {
                    if ((methodInfo.Attributes & MethodAttributes.SpecialName) > 0)
                    {
                        continue;
                    }

                    var methodSignature = GetMethodSignature(methodInfo);

                    classStrBldr.Append(methodSignature);

                    if (_methodInfoToSimilarOrSameAutoGeneratedServiceMethodElementMap.TryGetValue(methodInfo, out var autoGeneratedServiceMethodElement))
                    {
                        if (autoGeneratedServiceMethodElement.ImplementedMehodInfo == methodInfo)
                        {
                            AddMethodBodyForImplementedMethod(dynamicAssemblyBuilder, autoGeneratedServiceMethodElement,
                                                              classStrBldr, classMemberVariablesStrBldr);
                        }
                        else
                        {
                            AddMethodBodyForNonImplementedMethodWithSimilarImplementedMethod(dynamicAssemblyBuilder, methodInfo,
                                                                                             autoGeneratedServiceMethodElement, classStrBldr);
                        }
                    }
                    else
                    {
                        classStrBldr.AppendLine("{");

                        foreach (var outParameterInfo in methodInfo.GetParameters().Where(x => x.IsOut))
                        {
                            classStrBldr.AppendLine($"{outParameterInfo.Name}=default({outParameterInfo.ParameterType.GetTypeNameInCSharpClass()});");
                        }

                        if (methodInfo.ReturnType != typeof(void))
                        {
                            classStrBldr.Append($"return default({methodInfo.ReturnType.GetTypeNameInCSharpClass()});");
                            classStrBldr.AppendLine();
                        }

                        classStrBldr.AppendLine("}");
                    }

                    classStrBldr.AppendLine();
                }

                foreach (var propertyInfo in type.GetProperties())
                {
                    var propertyHeader = GetPropertyHeader(propertyInfo);

                    void AddGetSet()
                    {
                        classStrBldr.Append(" { get;");

                        if (propertyInfo.SetMethod != null)
                        {
                            classStrBldr.Append(" set;");
                        }

                        classStrBldr.Append("}");
                    }

                    classStrBldr.Append(propertyHeader);

                    if (_propertyInfoToSimilarOrSameAutoGeneratedServicePropertyElementMap.TryGetValue(propertyInfo,
                                                                                                       out var similarOrSameAutoGeneratedServicePropertyElement))
                    {
                        var similarPropertyInfo = similarOrSameAutoGeneratedServicePropertyElement.ImplementedPropertyInfo;
                        if (similarPropertyInfo == propertyInfo)
                        {
                            AddGetSet();
                            classStrBldr.AppendLine($"={similarOrSameAutoGeneratedServicePropertyElement.ReturnValueElement.GenerateValueCSharp(dynamicAssemblyBuilder)};");
                        }
                        else
                        {
                            var privateVariableName = $"_{propertyInfo.DeclaringType.Name}_{propertyInfo.Name}_{GlobalsCoreAmbientContext.Context.GenerateUniqueId()}";

                            // Not, for nullable values and reference types, we can check for null, to set if the value was initialized.
                            // however, to make it simple, and also to avoid calling the other class property every time, in case the other property
                            // value is null, lets use the valueWasSet variable for all cases.
                            var valueWasSetVariableName = $"{privateVariableName}_ValueWasSet";


                            classStrBldr.AppendLine();
                            classStrBldr.AppendLine("{");

                            classStrBldr.AppendLine("get");
                            classStrBldr.AppendLine("{");

                            classStrBldr.AppendLine($"if ({valueWasSetVariableName}) return {privateVariableName};");

                            classStrBldr.Append($"{privateVariableName}=(({similarPropertyInfo.DeclaringType.GetTypeNameInCSharpClass()})this)");
                            classStrBldr.AppendLine($".{similarPropertyInfo.Name};");
                            classStrBldr.AppendLine($"{valueWasSetVariableName}=true;");
                            classStrBldr.AppendLine($"return {privateVariableName};");
                            classStrBldr.AppendLine("}");

                            if (propertyInfo.SetMethod != null)
                            {
                                classStrBldr.AppendLine("set");
                                classStrBldr.AppendLine("{");
                                classStrBldr.AppendLine($"{privateVariableName}=value;");
                                classStrBldr.AppendLine($"{valueWasSetVariableName}=true;");

                                classStrBldr.AppendLine("}");
                            }

                            classStrBldr.AppendLine("}");
                            classStrBldr.AppendLine($"private bool {valueWasSetVariableName};");
                            classStrBldr.AppendLine($"private {propertyInfo.PropertyType.GetTypeNameInCSharpClass()} {privateVariableName};");
                        }
                    }
                    else
                    {
                        AddGetSet();
                        classStrBldr.AppendLine();
                    }
                }
            }

            var stopProcessing = false;

            TypeMemberLookupHelper.ProcessTypeImplementedInterfacesAndBaseTypes(ImplementedInterfaceTypeInfo.Type,
                                                                                ProcessType, ref stopProcessing);

            classStrBldr.Append(classMemberVariablesStrBldr);

            // Close class
            classStrBldr.AppendLine("}");

            // Close namespace
            classStrBldr.AppendLine("}");

            dynamicAssemblyBuilder.AddCSharpFile(classStrBldr.ToString());
        }
 public abstract void GenerateAutoImplementedServiceClassCSharp(
     IDynamicAssemblyBuilder dynamicAssemblyBuilder, string dynamicImplementationsNamespace, out string generatedClassFullName);
Beispiel #33
0
 protected override string DoGenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder)
 {
     return(_classMemberValueInitializerHelper.GenerateValueCSharp(ClassMemberData, dynamicAssemblyBuilder));
 }
Beispiel #34
0
 /// <summary>
 ///     Generates a code that returns an instance of a value of type specified by property <see cref="ValueType" />.
 /// </summary>
 /// <param name="dynamicAssemblyBuilder">The dynamic assembly builder.</param>
 /// <returns></returns>
 public string GenerateValueCSharp(IDynamicAssemblyBuilder dynamicAssemblyBuilder)
 {
     return(_deserializedFromStringValueInitializerHelper.GenerateValueCSharp(_configurationFileElement, ValueTypeInfo, ValueAsString, dynamicAssemblyBuilder));
 }