public override void DoSecondPass(IDictionary <string, PersistentClass> persistentClasses)
        {
            if (value is ManyToOne)
            {
                ManyToOne       manyToOne = (ManyToOne)value;
                PersistentClass @ref;
                persistentClasses.TryGetValue(manyToOne.ReferencedEntityName, out @ref);
                if (@ref == null)
                {
                    throw new AnnotationException(
                              "@OneToOne or @ManyToOne on "
                              + StringHelper.Qualify(entityClassName, path)
                              + " references an unknown entity: "
                              + manyToOne.ReferencedEntityName);
                }
                BinderHelper.CreateSyntheticPropertyReference(columns, @ref, null, manyToOne, false, mappings);
                TableBinder.BindFk(@ref, null, columns, manyToOne, unique, mappings);

                //HbmBinder does this only when property-ref != null, but IMO, it makes sense event if it is null
                if (!manyToOne.IsIgnoreNotFound)
                {
                    manyToOne.CreatePropertyRefConstraints(persistentClasses);
                }
            }
            else if (value is OneToOne)
            {
                value.CreateForeignKey();
            }
            else
            {
                throw new AssertionFailure("FkSecondPass for a wrong value type: " + value.GetType().Name);
            }
        }
Example #2
0
        private static Ejb3Column[] BuildImplicitColumn(IPropertyData inferredData,
                                                        IDictionary <string, Join> secondaryTables,
                                                        IPropertyHolder propertyHolder, Nullability nullability,
                                                        ExtendedMappings mappings)
        {
            Ejb3Column[] columns;
            columns = new Ejb3Column[1];
            Ejb3Column column = new Ejb3Column();

            column.SetImplicit(false);
            //not following the spec but more clean
            if (nullability != Nullability.ForcedNull && inferredData.ClassOrElement.IsPrimitive &&
                !inferredData.Property.GetType().IsArray)         //TODO: IsArray in this way ???
            {
                column.SetNullable(false);
            }
            column.SetLength(DEFAULT_COLUMN_LENGTH);
            column.PropertyName   = BinderHelper.GetRelativePath(propertyHolder, inferredData.PropertyName);
            column.PropertyHolder = propertyHolder;
            column.SetJoins(secondaryTables);
            column.Mappings = mappings;
            column.Bind();
            columns[0] = column;
            return(columns);
        }
Example #3
0
            public object GetValue(NameValueCollection data)
            {
                object value   = null;
                bool   succeed = false;

                if (Binder != null)
                {
                    value = Binder.GetConvert().Parse(data, Info.Name, Binder.Prefix, out succeed);
                    if (!succeed && Binder.Fungible != null)
                    {
                        value = Activator.CreateInstance(Binder.Fungible);
                    }
                    return(value);
                }
                else
                {
                    IConvert convert = BindUtils.GetConvert(Info.PropertyType);
                    if (convert != null)
                    {
                        value = convert.Parse(data, Info.Name, null, out succeed);
                    }
                    else
                    {
                        if (Info.PropertyType.IsValueType)
                        {
                            value = BinderHelper.GetValue(Info.PropertyType, Info.Name);
                        }
                        else
                        {
                            value = GetObject(data);
                        }
                    }
                }
                return(value);
            }
Example #4
0
 private object GetObject(NameValueCollection data)
 {
     if (Info.PropertyType.GetInterface(typeof(IList <>).Name) != null || Info.PropertyType.Name == "IList`1")
     {
         if (Binder == null)
         {
             return(BinderHelper.GetList(Info.PropertyType, data, null));
         }
         else
         {
             return(BinderHelper.GetList(Info.PropertyType, data, Binder.Prefix));
         }
     }
     else
     {
         if (Binder == null)
         {
             return(BinderHelper.GetObject(Info.PropertyType, null));
         }
         else
         {
             return(BinderHelper.GetObject(Info.PropertyType, Binder.Prefix));
         }
     }
 }
        public Expression Bind(PipelineExpression pipeline, PipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable <Expression> arguments)
        {
            var source = pipeline.Source;

            if (arguments.Any())
            {
                source = BinderHelper.BindWhere(
                    pipeline,
                    bindingContext,
                    ExpressionHelper.GetLambda(arguments.Single()));
            }

            var serializer = bindingContext.GetSerializer(node.Type, null);

            var accumulator = new AccumulatorExpression(
                node.Type,
                "__result",
                serializer,
                AccumulatorType.Sum,
                Expression.Constant(1));

            source = new GroupByExpression(
                node.Type,
                source,
                Expression.Constant(1),
                new[] { accumulator });

            return(new PipelineExpression(
                       source,
                       new FieldExpression(accumulator.FieldName, accumulator.Serializer),
                       new CountResultOperator(
                           node.Type,
                           bindingContext.GetSerializer(node.Type, node))));
        }
Example #6
0
        public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
        {
            if (value == null)
            {
                bsonWriter.WriteNull();
                return;
            }
            var metaObject  = ((IDynamicMetaObjectProvider)value).GetMetaObject(Expression.Constant(value));
            var memberNames = metaObject.GetDynamicMemberNames().ToList();

            if (memberNames.Count == 0)
            {
                bsonWriter.WriteNull();
                return;
            }

            bsonWriter.WriteStartDocument();
            foreach (var memberName in memberNames)
            {
                bsonWriter.WriteName(memberName);
                var memberValue = BinderHelper.GetMemberValue(value, memberName);
                if (memberValue == null)
                {
                    bsonWriter.WriteNull();
                }
                else
                {
                    var serializer = BsonSerializer.LookupSerializer(memberValue.GetType());
                    serializer.Serialize(bsonWriter, nominalType, memberValue, options);
                }
            }
            bsonWriter.WriteEndDocument();
        }
Example #7
0
        private static IEnumerable <Assembly> GetReferencedAssemblyNames(DXCompileParameter parameter)
        {
            // 확장 모듈에서 생성된 객체인경우 어셈블리 가져옴

            List <Assembly> assemblies = parameter.Screens.Select(s => s.GetType().Assembly).ToList();

            foreach (PBinderHost comp in parameter.Components)
            {
                foreach (IBinderHost host in BinderHelper.FindHostNodes(comp))
                {
                    if (host is PFunction func)
                    {
                        assemblies.Add(func.FunctionInfo.DeclaringType.Assembly);
                    }
                    else if (host is PTrigger trigger)
                    {
                        assemblies.Add(trigger.EventInfo.DeclaringType.Assembly);
                    }
                }
            }

            return(assemblies
                   .Where(ass => !ass.GetName().Name.AnyEquals("DeXign.Core"))
                   .Distinct());
        }
Example #8
0
        public SimpleValue FillSimpleValue(SimpleValue simpleValue)
        {
            string  type    = BinderHelper.IsDefault(explicitType) ? returnedClassName : explicitType;
            TypeDef typeDef = mappings.GetTypeDef(type);

            if (typeDef != null)
            {
                type = typeDef.TypeClass;
                simpleValue.TypeParameters = typeDef.Parameters;
            }
            if (typeParameters != null && typeParameters.Count != 0)
            {
                //explicit type params takes precedence over type def params
                simpleValue.TypeParameters = typeParameters;
            }
            simpleValue.TypeName = type;
            if (persistentClassName != null)
            {
                simpleValue.SetTypeUsingReflection(persistentClassName, propertyName, "");
            }
            foreach (Ejb3Column column in columns)
            {
                column.linkWithValue(simpleValue);
            }
            return(simpleValue);
        }
        /// <summary>
        ///     Get a application from the service collection.
        ///     This method builds the <see cref="ServiceProvider" /> collection. Because of this behavior, the options must be registered in the
        ///     <see cref="IServiceCollection" /> prior to calling this method.
        /// </summary>
        /// <param name="services"></param>
        /// <param name="settingsSection"></param>
        /// <typeparam name="TOptions"></typeparam>
        /// <returns></returns>
        public static TOptions GetOptions <TOptions>(this IServiceCollection services, string settingsSection)
            where TOptions : class, new()
        {
            using ServiceProvider serviceProvider = services.BuildServiceProvider();
            var configuration = serviceProvider.GetService <IConfiguration>();

            return(BinderHelper.BindOptions <TOptions>(configuration.GetSection(settingsSection)));
        }
Example #10
0
        private void SetFKNameIfDefined(Join join)
        {
            TableAttribute matchingTable = FindMatchingComplimentTableAnnotation(join);

            if (matchingTable != null && !BinderHelper.IsDefault(matchingTable.ForeignKey.Name))
            {
                ((SimpleValue)join.Key).ForeignKeyName = matchingTable.ForeignKey.Name;
            }
        }
        public Expression Bind(PipelineExpression pipeline, EmbeddedPipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable <Expression> arguments)
        {
            var source = BinderHelper.BindWhere(
                pipeline,
                bindingContext,
                ExpressionHelper.GetLambda(arguments.Single()));

            return(new PipelineExpression(
                       source,
                       pipeline.Projector));
        }
Example #12
0
        private static Ejb3Column[] BuildColumnFromAnnotation(ColumnAttribute[] anns, Nullability nullability,
                                                              IPropertyHolder propertyHolder, IPropertyData inferredData,
                                                              IDictionary <string, Join> secondaryTables,
                                                              ExtendedMappings mappings)
        {
            ColumnAttribute[] actualCols     = anns;
            ColumnAttribute[] overriddenCols = propertyHolder.GetOverriddenColumn(StringHelper.Qualify(propertyHolder.Path, inferredData.PropertyName));

            if (overriddenCols != null)
            {
                //check for overridden first
                if (anns != null && overriddenCols.Length != anns.Length)
                {
                    throw new AnnotationException("AttributeOverride.column() should override all columns for now");
                }

                actualCols = overriddenCols.Length == 0 ? null : overriddenCols;
                log.DebugFormat("Column(s) overridden for property {0}", inferredData.PropertyName);
            }

            if (actualCols == null)
            {
                return(BuildImplicitColumn(inferredData, secondaryTables, propertyHolder, nullability, mappings));
            }

            int length = actualCols.Length;

            Ejb3Column[] columns = new Ejb3Column[length];
            for (int index = 0; index < length; index++)
            {
                ColumnAttribute col     = actualCols[index];
                String          sqlType = col.ColumnDefinition.Equals("") ? null : col.ColumnDefinition;
                Ejb3Column      column  = new Ejb3Column();
                column.SetImplicit(false);
                column.SetSqlType(sqlType);
                column.SetLength(col.Length);
                column.SetPrecision(col.Precision);
                column.SetScale(col.Scale);
                column.SetLogicalColumnName(col.Name);
                column.PropertyName = BinderHelper.GetRelativePath(propertyHolder, inferredData.PropertyName);
                column.SetNullable(col.Nullable); //TODO force to not null if available? This is a (bad) user choice.
                column.SetUnique(col.Unique);
                column.SetInsertable(col.Insertable);
                column.SetUpdatable(col.Updatable);
                column.SetSecondaryTableName(col.Table);
                column.PropertyHolder = propertyHolder;
                column.SetJoins(secondaryTables);
                column.Mappings = mappings;
                column.Bind();
                columns[index] = column;
            }
            return(columns);
        }
Example #13
0
        public Expression Bind(PipelineExpression pipeline, EmbeddedPipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable <Expression> arguments)
        {
            var source = BinderHelper.BindSelect(
                pipeline,
                bindingContext,
                ExpressionHelper.GetLambda(arguments.Single()));

            var serializer = bindingContext.GetSerializer(source.Selector.Type, source.Selector);

            return(new PipelineExpression(
                       source,
                       new DocumentExpression(serializer)));
        }
Example #14
0
        private void SetNodeOpacity(BindOptions option, double opacity)
        {
            this.Opacity = opacity;

            foreach (var node in BinderHelper.FindHostNodes(this.Model, option))
            {
                var element = node.GetView <FrameworkElement>();

                if (element != null)
                {
                    element.Opacity = opacity;
                }
            }
        }
Example #15
0
        private void Binder_Binded(object sender, IBinder e)
        {
            var expression = BinderHelper.GetPairBinder(this.Binder, e);

            var output = (expression.Output as PBinder).GetView <BindThumb>();
            var input  = (expression.Input as PBinder).GetView <BindThumb>();

            if (output == null || input == null)
            {
                return;
            }

            // Propagate
            output.PropagateBind(output, input);
        }
Example #16
0
        public WPFCodeBuilder(DXCompileParameter parameter, CSharpGenerator generator)
        {
            this.Parameter       = parameter;
            this.NativeGenerator = generator;

            sdkNamespaces =
                parameter.Components
                .SelectMany(c => BinderHelper.FindHostNodes(c))
                .Where(host => host is PFunction)
                .Select(host => (host as PFunction).FunctionInfo.DeclaringType.Namespace)
                .Distinct()
                .ToList();

            definedNamespaces = new List <string>();
            logicCodes        = new List <string>();
        }
Example #17
0
        public Expression Bind(PipelineExpression pipeline, EmbeddedPipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable <Expression> arguments)
        {
            var source = pipeline.Source;

            if (arguments.Any())
            {
                source = BinderHelper.BindSelect(
                    pipeline,
                    bindingContext,
                    ExpressionHelper.GetLambda(arguments.Single()));
            }

            return(new PipelineExpression(
                       source,
                       pipeline.Projector,
                       new MinResultOperator(node.Type)));
        }
        public Expression Bind(PipelineExpression pipeline, PipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable <Expression> arguments)
        {
            var source = pipeline.Source;

            if (arguments.Any())
            {
                source = BinderHelper.BindWhere(
                    pipeline,
                    bindingContext,
                    ExpressionHelper.GetLambda(arguments.Single()));
            }

            source = new TakeExpression(source, Expression.Constant(1));

            return(new PipelineExpression(
                       source,
                       pipeline.Projector,
                       new AnyResultOperator()));
        }
Example #19
0
        public Expression Bind(PipelineExpression pipeline, EmbeddedPipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable <Expression> arguments)
        {
            var source = pipeline.Source;

            if (arguments.Any())
            {
                source = BinderHelper.BindSelect(
                    pipeline,
                    bindingContext,
                    ExpressionHelper.GetLambda(arguments.Single()));
            }

            return(new PipelineExpression(
                       source,
                       pipeline.Projector,
                       new StandardDeviationResultOperator(
                           node.Type,
                           bindingContext.GetSerializer(node.Type, node),
                           node.Method.Name == nameof(MongoEnumerable.StandardDeviationSample))));
        }
        public Expression Bind(PipelineExpression pipeline, EmbeddedPipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable <Expression> arguments)
        {
            var source = pipeline.Source;

            if (arguments.Any())
            {
                source = BinderHelper.BindWhere(
                    pipeline,
                    bindingContext,
                    ExpressionHelper.GetLambda(arguments.Single()));
            }

            return(new PipelineExpression(
                       source,
                       pipeline.Projector,
                       new FirstResultOperator(
                           node.Type,
                           pipeline.Projector.Serializer,
                           node.Method.Name == nameof(Enumerable.FirstOrDefault))));
        }
Example #21
0
        // CreateScope (Recursive)
        internal static string CreateScope(DXMapper <CSharpCodeMapAttribute> mapper, CodeComponent <CSharpCodeMapAttribute>[] scopeComponents, NameContainer localVariableContainer, bool isCodeBlock = false)
        {
            var scopeBuilder = new IndentStringBuilder();
            var stack        = new Stack <CodeComponent <CSharpCodeMapAttribute> >(scopeComponents.Reverse());

            if (!isCodeBlock)
            {
                scopeBuilder.AppendLine();
                scopeBuilder.AppendLine("{");
            }

            while (stack.Count > 0)
            {
                var cc = stack.Pop();

                var mappingResult = mapper.Build(cc.Element, cc.Attribute.MappingCode);
                var sourceBuilder = new IndentStringBuilder(mappingResult.Source);

                if (cc.Element is PBinderHost host)
                {
                    foreach (DXToken token in mappingResult.Errors)
                    {
                        switch (token.Token)
                        {
                        case "Scope":
                        {
                            if (!token.IsIndexed)
                            {
                                continue;
                            }

                            int index = int.Parse(token.Parameters[0]) - 1;

                            if (host is PFunction)
                            {
                                index++;
                            }

                            var scopeBinder    = host[BindOptions.Output].ElementAt(index) as PBinder;
                            var scopeZeroHosts = scopeBinder.Items.Select(b => b.GetBinderHost());

                            var childScopeComponents = BinderHelper.FindZeroLevelNodes(scopeZeroHosts, withRoot: true)
                                                       .Distinct()
                                                       .Select(childHost => new CodeComponent <CSharpCodeMapAttribute>(
                                                                   childHost, childHost.GetAttribute <CSharpCodeMapAttribute>()))
                                                       .ToArray();

                            sourceBuilder.Replace(
                                token.OriginalSource,
                                CreateScope(mapper, childScopeComponents, localVariableContainer));

                            break;
                        }

                        case "Line":
                        {
                            if (!token.IsIndexed)
                            {
                                continue;
                            }

                            int index = int.Parse(token.Parameters[0]) - 1;

                            var paramBinder = host[BindOptions.Parameter].ElementAt(index) as PBinder;

                            ProcessBinderValue(mapper, sourceBuilder, token, paramBinder);
                            break;
                        }

                        default:
                            break;
                        }
                    }
                }

                scopeBuilder.AppendBlock(sourceBuilder.ToString(), 1);
                scopeBuilder.AppendLine();
            }

            if (!isCodeBlock)
            {
                scopeBuilder.AppendLine("}");
            }

            return(scopeBuilder.ToString());
        }
Example #22
0
        public void BindEntity()
        {
            persistentClass.IsAbstract = annotatedClass.IsAbstract;
            persistentClass.ClassName  = annotatedClass.Name;
            persistentClass.NodeName   = name;
            //TODO:review this
            //persistentClass.setDynamic(false); //no longer needed with the Entity name refactoring?
            persistentClass.EntityName = (annotatedClass.Name);
            BindDiscriminatorValue();

            persistentClass.IsLazy = lazy;
            if (proxyClass != null)
            {
                persistentClass.ProxyInterfaceName = proxyClass.Name;
            }
            persistentClass.DynamicInsert = dynamicInsert;
            persistentClass.DynamicUpdate = dynamicUpdate;

            if (persistentClass is RootClass)
            {
                RootClass rootClass = (RootClass)persistentClass;
                bool      mutable   = true;
                //priority on @Immutable, then @Entity.mutable()
                if (annotatedClass.IsAttributePresent <ImmutableAttribute>())
                {
                    mutable = false;
                }
                else
                {
                    var entityAnn = annotatedClass.GetAttribute <EntityAttribute>();
                    if (entityAnn != null)
                    {
                        mutable = entityAnn.IsMutable;
                    }
                }
                rootClass.IsMutable = mutable;
                rootClass.IsExplicitPolymorphism = ExplicitPolymorphismConverter.Convert(polymorphismType);
                if (StringHelper.IsNotEmpty(where))
                {
                    rootClass.Where = where;
                }

                if (cacheConcurrentStrategy != null)
                {
                    rootClass.CacheConcurrencyStrategy = cacheConcurrentStrategy;
                    rootClass.CacheRegionName          = cacheRegion;
                    //TODO: LazyPropertiesCacheable
                    //rootClass.LazyPropertiesCacheable =  cacheLazyProperty ;
                }
                rootClass.IsForceDiscriminator = annotatedClass.IsAttributePresent <ForceDiscriminatorAttribute>();
            }
            else
            {
                if (explicitHibernateEntityAnnotation)
                {
                    log.WarnFormat("[NHibernate.Annotations.Entity] used on a non root entity: ignored for {0}", annotatedClass.Name);
                }
                if (annotatedClass.IsAttributePresent <ImmutableAttribute>())
                {
                    log.WarnFormat("[Immutable] used on a non root entity: ignored for {0}", annotatedClass.Name);
                }
            }
            persistentClass.OptimisticLockMode = OptimisticLockModeConverter.Convert(optimisticLockType);
            persistentClass.SelectBeforeUpdate = selectBeforeUpdate;

            //set persister if needed
            //[Persister] has precedence over [Entity.persister]
            var persisterAnn = annotatedClass.GetAttribute <PersisterAttribute>();

            System.Type persister = null;
            if (persisterAnn != null)
            {
                persister = persisterAnn.Implementation;
            }
            else
            {
                var entityAnn = annotatedClass.GetAttribute <EntityAttribute>();
                if (entityAnn != null && !BinderHelper.IsDefault(entityAnn.Persister))
                {
                    try
                    {
                        persister = ReflectHelper.ClassForName(entityAnn.Persister);
                    }
                    catch (TypeLoadException tle)
                    {
                        throw new AnnotationException("Could not find persister class: " + persister, tle);
                    }
                }
            }
            if (persister != null)
            {
                persistentClass.EntityPersisterClass = persister;
            }
            persistentClass.BatchSize = batchSize;

            //SQL overriding
            var sqlInsert    = annotatedClass.GetAttribute <SQLInsertAttribute>();
            var sqlUpdate    = annotatedClass.GetAttribute <SQLUpdateAttribute>();
            var sqlDelete    = annotatedClass.GetAttribute <SQLDeleteAttribute>();
            var sqlDeleteAll = annotatedClass.GetAttribute <SQLDeleteAllAttribute>();
            var loader       = annotatedClass.GetAttribute <LoaderAttribute>();

            if (sqlInsert != null)
            {
                persistentClass.SetCustomSQLInsert(sqlInsert.Sql.Trim(), sqlInsert.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlInsert.Check));
            }
            if (sqlUpdate != null)
            {
                persistentClass.SetCustomSQLUpdate(sqlUpdate.Sql.Trim(), sqlUpdate.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlUpdate.Check));
            }
            if (sqlDelete != null)
            {
                persistentClass.SetCustomSQLDelete(sqlDelete.Sql, sqlDelete.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlDelete.Check));
            }
            if (sqlDeleteAll != null)
            {
                persistentClass.SetCustomSQLDelete(sqlDeleteAll.Sql, sqlDeleteAll.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlDeleteAll.Check));
            }
            if (loader != null)
            {
                persistentClass.LoaderName = loader.NamedQuery;
            }

            //tuplizers
            if (annotatedClass.IsAttributePresent <TuplizerAttribute>())
            {
                foreach (TuplizerAttribute tuplizer in annotatedClass.GetAttributes <TuplizerAttribute>())
                {
                    var mode = EntityModeConverter.Convert(tuplizer.EntityMode);
                    persistentClass.AddTuplizer(mode, tuplizer.Implementation.Name);
                }
            }
            if (annotatedClass.IsAttributePresent <TuplizerAttribute>())
            {
                var tuplizer = annotatedClass.GetAttribute <TuplizerAttribute>();
                var mode     = EntityModeConverter.Convert(tuplizer.EntityMode);
                persistentClass.AddTuplizer(mode, tuplizer.Implementation.Name);
            }

            if (!inheritanceState.HasParents)
            {
                var iter = filters.GetEnumerator();
                while (iter.MoveNext())
                {
                    var    filter     = iter.Current;
                    String filterName = filter.Key;
                    String cond       = filter.Value;
                    if (BinderHelper.IsDefault(cond))
                    {
                        FilterDefinition definition = mappings.GetFilterDefinition(filterName);
                        cond = definition == null ? null : definition.DefaultFilterCondition;
                        if (StringHelper.IsEmpty(cond))
                        {
                            throw new AnnotationException("no filter condition found for filter " + filterName + " in " + name);
                        }
                    }
                    persistentClass.AddFilter(filterName, cond);
                }
            }
            else
            {
                if (filters.Count > 0)
                {
                    log.WarnFormat("@Filter not allowed on subclasses (ignored): {0}", persistentClass.EntityName);
                }
            }
            log.DebugFormat("Import with entity name {0}", name);

            try
            {
                mappings.AddImport(persistentClass.EntityName, name);
                String entityName = persistentClass.EntityName;
                if (!entityName.Equals(name))
                {
                    mappings.AddImport(entityName, entityName);
                }
            }
            catch (MappingException me)
            {
                throw new AnnotationException("Use of the same entity name twice: " + name, me);
            }
        }
Example #23
0
 /// <summary>
 ///     Gets an section of the json configuration and binds to an object.
 /// </summary>
 /// <param name="configuration">
 ///     <see cref="IConfiguration" />
 /// </param>
 /// <param name="section">Configuration section name</param>
 /// <typeparam name="TOptions">Resulting object</typeparam>
 /// <returns>Instance of TOptions</returns>
 public static TOptions GetOptions <TOptions>(this IConfiguration configuration, string section)
     where TOptions : class, new()
 {
     return(BinderHelper.BindOptions <TOptions>(configuration.GetSection(section)));
 }
Example #24
0
 /// <summary>
 ///     Gets an section of the json configuration and binds to an object.
 /// </summary>
 /// <param name="configuration">
 ///     <see cref="IConfiguration" />
 /// </param>
 /// <param name="section">Configuration section name</param>
 /// <typeparam name="TOptions">Resulting object</typeparam>
 /// <returns>Instance of TOptions</returns>
 public static TOptions GetOptions <TOptions>(this IConfigurationSection section)
     where TOptions : class, new()
 {
     return(BinderHelper.BindOptions <TOptions>(section));
 }
Example #25
0
        /// <summary>
        /// A non null propertyHolder means than we process the Pk creation without delay
        /// </summary>
        /// <param name="secondaryTable"></param>
        /// <param name="joinTable"></param>
        /// <param name="propertyHolder"></param>
        /// <param name="noDelayInPkColumnCreation"></param>
        /// <returns></returns>
        private Join AddJoin(SecondaryTableAttribute secondaryTable,
                             JoinTableAttribute joinTable,
                             IPropertyHolder propertyHolder,
                             bool noDelayInPkColumnCreation)
        {
            Join join = new Join();

            join.PersistentClass = persistentClass;
            string schema;
            string catalog;
            string table;
            string realTable;

            System.Persistence.UniqueConstraintAttribute[] uniqueConstraintsAnn;
            if (secondaryTable != null)
            {
                schema               = secondaryTable.Schema;
                catalog              = secondaryTable.Catalog;
                table                = secondaryTable.Name;
                realTable            = mappings.NamingStrategy.TableName(table);      //always an explicit table name
                uniqueConstraintsAnn = secondaryTable.UniqueConstraints;
            }
            else if (joinTable != null)
            {
                schema               = joinTable.Schema;
                catalog              = joinTable.Catalog;
                table                = joinTable.Name;
                realTable            = mappings.NamingStrategy.TableName(table);      //always an explicit table name
                uniqueConstraintsAnn = joinTable.UniqueConstraints;
            }
            else
            {
                throw new AssertionFailure("Both JoinTable and SecondaryTable are null");
            }

            var uniqueConstraints = new List <string[]>(uniqueConstraintsAnn == null ? 0 : uniqueConstraintsAnn.Length);

            if (uniqueConstraintsAnn != null && uniqueConstraintsAnn.Length != 0)
            {
                foreach (UniqueConstraintAttribute uc in uniqueConstraintsAnn)
                {
                    uniqueConstraints.Add(uc.ColumnNames);
                }
            }
            Table tableMapping = TableBinder.FillTable(
                schema,
                catalog,
                realTable,
                table, false, uniqueConstraints, null, null, mappings);

            //no check constraints available on joins
            join.Table = tableMapping;

            //somehow keep joins() for later.
            //Has to do the work later because it needs persistentClass id!
            object joinColumns = null;

            //get the appropriate pk columns
            if (secondaryTable != null)
            {
                joinColumns = secondaryTable.PkJoinColumns;
            }
            else if (joinTable != null)
            {
                joinColumns = joinTable.JoinColumns;
            }
            log.InfoFormat("Adding secondary table to entity {0} -> {1}", persistentClass.EntityName, join.Table.Name);

            TableAttribute matchingTable = FindMatchingComplimentTableAnnotation(join);

            if (matchingTable != null)
            {
                join.IsSequentialSelect = FetchMode.Join != matchingTable.Fetch;
                join.IsInverse          = matchingTable.IsInverse;
                join.IsOptional         = matchingTable.IsOptional;
                if (!BinderHelper.IsDefault(matchingTable.SqlInsert.Sql))
                {
                    join.SetCustomSQLInsert(matchingTable.SqlInsert.Sql.Trim(),
                                            matchingTable.SqlInsert.Callable,
                                            ExecuteUpdateResultCheckStyle.Parse(matchingTable.SqlInsert.Check.ToString().ToLower()));
                }
                if (!BinderHelper.IsDefault(matchingTable.SqlUpdate.Sql))
                {
                    join.SetCustomSQLUpdate(matchingTable.SqlUpdate.Sql.Trim(),
                                            matchingTable.SqlUpdate.Callable,
                                            ExecuteUpdateResultCheckStyle.Parse(matchingTable.SqlUpdate.Check.ToString().ToLower())
                                            );
                }
                if (!BinderHelper.IsDefault(matchingTable.SqlDelete.Sql))
                {
                    join.SetCustomSQLDelete(matchingTable.SqlDelete.Sql.Trim(),
                                            matchingTable.SqlDelete.Callable,
                                            ExecuteUpdateResultCheckStyle.Parse(matchingTable.SqlDelete.Check.ToString().ToLower())
                                            );
                }
            }
            else
            {
                //default
                join.IsSequentialSelect = false;
                join.IsInverse          = false;
                join.IsOptional         = false;         //perhaps not quite per-spec, but a Good Thing anyway
            }

            if (noDelayInPkColumnCreation)
            {
                CreatePrimaryColumnsToSecondaryTable(joinColumns, propertyHolder, join);
            }
            else
            {
                secondaryTables.Add(table, join);
                secondaryTableJoins.Add(table, joinColumns);
            }
            return(join);
        }
Example #26
0
        public override IEnumerable <CodeComponent <TAttribute> > GetComponents <TAttribute>()
        {
            if (Items != null)
            {
                foreach (PObject item in Items
                         .SelectMany(host => host.GetExpressions())
                         .Select(e => e.Output.Host)
                         .Distinct())
                {
                    if (!item.HasAttribute <TAttribute>())
                    {
                        continue;
                    }

                    var attr      = item.GetAttribute <TAttribute>();
                    var component = new CodeComponent <TAttribute>(item, attr);
                    var stack     = new Stack <CodeComponent <TAttribute> >(new[] { component });

                    component.ElementType = CodeComponentType.Node;

                    while (stack.Count > 0)
                    {
                        var cc = stack.Pop();

                        if (cc.ElementType == CodeComponentType.Node)
                        {
                            var host      = cc.Element as PBinderHost;
                            var zeroNodes = new List <PBinderHost>();

                            // 호스트와 연결된 모든 노드를 BFS알고리즘을 사용하여 가져오고
                            // 생성된 Output Binder의 갯수가 1개인 것만 노드로 인정함
                            // 갯수가 2개이상인 노드에서 멈춤 (2개이상은 스코프가 분기된다고 가정)
                            zeroNodes.AddRange(
                                BinderHelper.FindZeroLevelNodes(
                                    new[] { host },
                                    childNode =>
                            {
                                return(!(childNode is PTrigger));
                            }));

                            foreach (PBinderHost zeroNode in zeroNodes)
                            {
                                var childComponent = new CodeComponent <TAttribute>(
                                    zeroNode,
                                    zeroNode.GetAttribute <TAttribute>())
                                {
                                    Depth       = cc.Depth + 1,
                                    ElementType = CodeComponentType.Node
                                };

                                cc.Add(childComponent);

                                if (zeroNode[BindOptions.Output].Count() > 1 || zeroNode is PTrigger)
                                {
                                    stack.Push(childComponent);
                                }
                            }
                        }
                    }

                    yield return(component);
                }
            }
        }