Ejemplo n.º 1
0
 /// <summary>
 /// Check is return type is void for non async and Task for async methods.
 /// </summary>
 /// <param name="method">The method to verify.</param>
 /// <returns>True if the method has a void/task return type..</returns>
 internal static bool IsVoidOrTaskReturnType(this MethodInfo method)
 {
     return(ReflectHelper.MatchReturnType(method, typeof(Task)) ||
            (ReflectHelper.MatchReturnType(method, typeof(void)) && method.GetAsyncTypeName() == null));
 }
Ejemplo n.º 2
0
 public EndsWithGenerator()
 {
     SupportedMethods = new[] { ReflectHelper.GetMethodDefinition <string>(x => x.EndsWith(null)) };
 }
Ejemplo n.º 3
0
 /// <inheritdoc/>
 public Attribute[] GetAllAttributes(bool inherit)
 {
     return(ReflectHelper.GetCustomAttributes(this.TestMethod, inherit) as Attribute[]);
 }
Ejemplo n.º 4
0
 //6.0 TODO: Expose as ISessionImplementor.FutureBatch and replace method usages with property
 internal static IQueryBatch GetFutureBatch(this ISessionImplementor session)
 {
     return(ReflectHelper.CastOrThrow <AbstractSessionImpl>(session, "future batch").FutureBatch);
 }
Ejemplo n.º 5
0
 public ContainsGenerator()
 {
     SupportedMethods = new[] { ReflectHelper.GetMethodDefinition <string>(x => x.Contains(null)) };
 }
Ejemplo n.º 6
0
 public MyLinqToHqlGeneratorsRegistry()
 {
     RegisterGenerator(ReflectHelper.GetMethodDefinition(() => BooleanLinqExtensions.FreeText(null, null)),
                       new FreetextGenerator());
 }
Ejemplo n.º 7
0
        public static ILinqToHqlGeneratorsRegistry CreateGeneratorsRegistry(IDictionary <string, string> properties)
        {
            string registry;

            if (properties.TryGetValue(Environment.LinqToHqlGeneratorsRegistry, out registry))
            {
                try
                {
                    log.Info("Initializing LinqToHqlGeneratorsRegistry: {0}", registry);
                    return((ILinqToHqlGeneratorsRegistry)Environment.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(registry)));
                }
                catch (Exception e)
                {
                    log.Fatal(e, "Could not instantiate LinqToHqlGeneratorsRegistry");
                    throw new HibernateException("Could not instantiate LinqToHqlGeneratorsRegistry: " + registry, e);
                }
            }
            return(new DefaultLinqToHqlGeneratorsRegistry());
        }
Ejemplo n.º 8
0
		public void OnDeserialization(object sender)
		{
			constructor = ReflectHelper.GetDefaultConstructor(mappedClass);
		}
Ejemplo n.º 9
0
        public MathGenerator()
        {
            SupportedMethods = new[]
            {
                ReflectHelper.GetMethodDefinition(() => Math.Sin(default(double))),
                ReflectHelper.GetMethodDefinition(() => Math.Cos(default(double))),
                ReflectHelper.GetMethodDefinition(() => Math.Tan(default(double))),

                ReflectHelper.GetMethodDefinition(() => Math.Sinh(default(double))),
                ReflectHelper.GetMethodDefinition(() => Math.Cosh(default(double))),
                ReflectHelper.GetMethodDefinition(() => Math.Tanh(default(double))),

                ReflectHelper.GetMethodDefinition(() => Math.Asin(default(double))),
                ReflectHelper.GetMethodDefinition(() => Math.Acos(default(double))),
                ReflectHelper.GetMethodDefinition(() => Math.Atan(default(double))),
                ReflectHelper.GetMethodDefinition(() => Math.Atan2(default(double), default(double))),

                ReflectHelper.GetMethodDefinition(() => Math.Sqrt(default(double))),

                ReflectHelper.GetMethodDefinition(() => Math.Abs(default(decimal))),
                ReflectHelper.GetMethodDefinition(() => Math.Abs(default(double))),
                ReflectHelper.GetMethodDefinition(() => Math.Abs(default(float))),
                ReflectHelper.GetMethodDefinition(() => Math.Abs(default(long))),
                ReflectHelper.GetMethodDefinition(() => Math.Abs(default(int))),
                ReflectHelper.GetMethodDefinition(() => Math.Abs(default(short))),
                ReflectHelper.GetMethodDefinition(() => Math.Abs(default(sbyte))),

                ReflectHelper.GetMethodDefinition(() => Math.Sign(default(decimal))),
                ReflectHelper.GetMethodDefinition(() => Math.Sign(default(double))),
                ReflectHelper.GetMethodDefinition(() => Math.Sign(default(float))),
                ReflectHelper.GetMethodDefinition(() => Math.Sign(default(long))),
                ReflectHelper.GetMethodDefinition(() => Math.Sign(default(int))),
                ReflectHelper.GetMethodDefinition(() => Math.Sign(default(short))),
                ReflectHelper.GetMethodDefinition(() => Math.Sign(default(sbyte))),

                ReflectHelper.GetMethodDefinition(() => Math.Floor(default(decimal))),
                ReflectHelper.GetMethodDefinition(() => Math.Floor(default(double))),
                ReflectHelper.GetMethodDefinition(() => decimal.Floor(default(decimal))),

                ReflectHelper.GetMethodDefinition(() => Math.Ceiling(default(decimal))),
                ReflectHelper.GetMethodDefinition(() => Math.Ceiling(default(double))),
                ReflectHelper.GetMethodDefinition(() => decimal.Ceiling(default(decimal))),

                ReflectHelper.GetMethodDefinition(() => Math.Pow(default(double), default(double))),

#if NETCOREAPP2_0
                ReflectHelper.GetMethodDefinition(() => MathF.Sin(default(float))),
                ReflectHelper.GetMethodDefinition(() => MathF.Cos(default(float))),
                ReflectHelper.GetMethodDefinition(() => MathF.Tan(default(float))),

                ReflectHelper.GetMethodDefinition(() => MathF.Sinh(default(float))),
                ReflectHelper.GetMethodDefinition(() => MathF.Cosh(default(float))),
                ReflectHelper.GetMethodDefinition(() => MathF.Tanh(default(float))),

                ReflectHelper.GetMethodDefinition(() => MathF.Asin(default(float))),
                ReflectHelper.GetMethodDefinition(() => MathF.Acos(default(float))),
                ReflectHelper.GetMethodDefinition(() => MathF.Atan(default(float))),
                ReflectHelper.GetMethodDefinition(() => MathF.Atan2(default(float), default(float))),

                ReflectHelper.GetMethodDefinition(() => MathF.Sqrt(default(float))),

                ReflectHelper.GetMethodDefinition(() => MathF.Abs(default(float))),

                ReflectHelper.GetMethodDefinition(() => MathF.Sign(default(float))),

                ReflectHelper.GetMethodDefinition(() => MathF.Floor(default(float))),

                ReflectHelper.GetMethodDefinition(() => MathF.Ceiling(default(float))),

                ReflectHelper.GetMethodDefinition(() => MathF.Pow(default(float), default(float))),
#endif
            };
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TestMethodRunner"/> class.
        /// </summary>
        /// <param name="testMethodInfo">
        /// The test method info.
        /// </param>
        /// <param name="testMethod">
        /// The test method.
        /// </param>
        /// <param name="testContext">
        /// The test context.
        /// </param>
        /// <param name="captureDebugTraces">
        /// The capture debug traces.
        /// </param>
        /// <param name="reflectHelper">
        /// The reflect Helper object.
        /// </param>
        public TestMethodRunner(TestMethodInfo testMethodInfo, TestMethod testMethod, ITestContext testContext, bool captureDebugTraces, ReflectHelper reflectHelper)
        {
            Debug.Assert(testMethodInfo != null, "testMethodInfo should not be null");
            Debug.Assert(testMethod != null, "testMethod should not be null");
            Debug.Assert(testContext != null, "testContext should not be null");

            this.testMethodInfo     = testMethodInfo;
            this.test               = testMethod;
            this.testContext        = testContext;
            this.captureDebugTraces = captureDebugTraces;
            this.reflectHelper      = reflectHelper;
        }
Ejemplo n.º 11
0
        protected override void InitList()
        {
            if (this.ServicePath == null || this.ServicePath == string.Empty)
            {
                this.ServicePath = "com.Sconit.Web.CodeMasterMgrProxy";
            }

            if (this.ServiceMethod == null || this.ServiceMethod == string.Empty)
            {
                this.ServiceMethod = "GetCachedCodeMaster";
            }

            if (this.Code == null || this.Code == string.Empty)
            {
                throw new TechnicalException("Code not specified.");
            }
            else
            {
                this.ServiceParameter = "string:" + this.Code;
            }

            this.DescField  = "Description";
            this.ValueField = "Value";

            IList <CodeMaster> list = ReflectHelper.InvokeServiceMethod(this.ServicePath, this.ServiceMethod, this.ServiceParameter) as IList <CodeMaster>;


            //IEnumerable<CodeMaster> i = list.OrderBy(codeMaster => codeMaster.Seq);
            this.Items.Clear();

            if (this.IncludeBlankOption)
            {
                //因为list是CachedList,不能直接往里面插值,所以做了个倒手。:(
                CodeMaster codeMstr = new CodeMaster();
                codeMstr.Code        = this.BlankOptionValue;
                codeMstr.Description = this.BlankOptionDesc;

                IList <CodeMaster> newList = list;
                list = new List <CodeMaster>();
                list.Add(codeMstr);
                if (newList != null && newList.Count > 0)
                {
                    foreach (CodeMaster codeMaster in newList)
                    {
                        list.Add(codeMaster);
                    }
                }
            }

            this.DataSource     = list;
            this.DataTextField  = this.DescField;
            this.DataValueField = this.ValueField;
            base.DataBind();
            #region 默认值
            if (this.DefaultSelectedValue == null && list != null)
            {
                foreach (CodeMaster codeMaster in list)
                {
                    if (codeMaster.IsDefault)
                    {
                        this.DefaultSelectedValue = codeMaster.Value;
                        break;
                    }
                }
            }
            if (this.DefaultSelectedValue != null)
            {
                this.SelectedValue = this.DefaultSelectedValue;
            }
            #endregion
        }
Ejemplo n.º 12
0
 public StartsWithGenerator()
 {
     SupportedMethods = new[] { ReflectHelper.GetMethodDefinition <string>(x => x.StartsWith(null)), MethodWithComparer };
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Given a query alias and an identifying suffix, render the property select fragment.
 /// </summary>
 //6.0 TODO: Merge into IQueryable
 public static string PropertySelectFragment(this IQueryable query, string alias, string suffix, ICollection <string> fetchProperties)
 {
     return(ReflectHelper.CastOrThrow <AbstractEntityPersister>(query, "individual lazy property fetches")
            .PropertySelectFragment(alias, suffix, fetchProperties));
 }
Ejemplo n.º 14
0
        /// <summary>
        /// For async methods compiler generates different type and method.
        /// Gets the compiler generated type name for given async test method.
        /// </summary>
        /// <param name="method">The method to verify.</param>
        /// <returns>Compiler generated type name for given async test method..</returns>
        internal static string GetAsyncTypeName(this MethodInfo method)
        {
            var asyncStateMachineAttribute = ReflectHelper.GetCustomAttributes(method, typeof(AsyncStateMachineAttribute), false).FirstOrDefault() as AsyncStateMachineAttribute;

            return(asyncStateMachineAttribute?.StateMachineType?.FullName);
        }
Ejemplo n.º 15
0
        public static void Main(string[] args)
        {
            try
            {
                var cfg = new Configuration();

                //string propFile = null;

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].StartsWith("--", StringComparison.Ordinal))
                    {
                        //if (args[i].StartsWith("--properties="))
                        //{
                        //  propFile = args[i].Substring(13);
                        //}
                        //else
                        if (args[i].StartsWith("--config=", StringComparison.Ordinal))
                        {
                            cfg.Configure(args[i].Substring(9));
                        }
                        else if (args[i].StartsWith("--naming=", StringComparison.Ordinal))
                        {
                            cfg.SetNamingStrategy(
                                (INamingStrategy)
                                Cfg.Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(args[i].Substring(9))));
                        }
                    }
                    else
                    {
                        cfg.AddFile(args[i]);
                    }
                }

                /* NH: No props file for .NET
                 * if ( propFile != null ) {
                 *      Properties props = new Properties();
                 *      props.putAll( cfg.getProperties() );
                 *      props.load( new FileInputStream( propFile ) );
                 *      cfg.setProperties( props );
                 * }
                 */
                new SchemaValidator(cfg).Validate();
            }
            catch (Exception e)
            {
                log.Error(e, "Error running schema update");
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 16
0
        public Settings BuildSettings(IDictionary <string, string> properties)
        {
            Settings settings = new Settings();

            Dialect.Dialect dialect;
            try
            {
                dialect = Dialect.Dialect.GetDialect(properties);
                Dictionary <string, string> temp = new Dictionary <string, string>();

                foreach (KeyValuePair <string, string> de in dialect.DefaultProperties)
                {
                    temp[de.Key] = de.Value;
                }
                foreach (KeyValuePair <string, string> de in properties)
                {
                    temp[de.Key] = de.Value;
                }
                properties = temp;
            }
            catch (HibernateException he)
            {
                log.Warn(he, "No dialect set - using GenericDialect: {0}", he.Message);
                dialect = new GenericDialect();
            }
            settings.Dialect = dialect;

            settings.LinqToHqlGeneratorsRegistry = LinqToHqlGeneratorsRegistryFactory.CreateGeneratorsRegistry(properties);
            // 6.0 TODO: default to false instead of true, and adjust documentation in xsd, xml comment on Environment
            // and Setting properties, and doc\reference.
            settings.LinqToHqlLegacyPreEvaluation = PropertiesHelper.GetBoolean(
                Environment.LinqToHqlLegacyPreEvaluation,
                properties,
                true);
            settings.LinqToHqlFallbackOnPreEvaluation = PropertiesHelper.GetBoolean(
                Environment.LinqToHqlFallbackOnPreEvaluation,
                properties);

            #region SQL Exception converter

            ISQLExceptionConverter sqlExceptionConverter;
            try
            {
                sqlExceptionConverter = SQLExceptionConverterFactory.BuildSQLExceptionConverter(dialect, properties);
            }
            catch (HibernateException he)
            {
                log.Warn(he, "Error building SQLExceptionConverter; using minimal converter");
                sqlExceptionConverter = SQLExceptionConverterFactory.BuildMinimalSQLExceptionConverter();
            }
            settings.SqlExceptionConverter = sqlExceptionConverter;

            #endregion

            bool comments = PropertiesHelper.GetBoolean(Environment.UseSqlComments, properties);
            log.Info("Generate SQL with comments: {0}", EnabledDisabled(comments));
            settings.IsCommentsEnabled = comments;

            int maxFetchDepth = PropertiesHelper.GetInt32(Environment.MaxFetchDepth, properties, -1);
            if (maxFetchDepth != -1)
            {
                log.Info("Maximum outer join fetch depth: {0}", maxFetchDepth);
            }

            IConnectionProvider connectionProvider = ConnectionProviderFactory.NewConnectionProvider(properties);
            ITransactionFactory transactionFactory = CreateTransactionFactory(properties);
            // TransactionManagerLookup transactionManagerLookup = TransactionManagerLookupFactory.GetTransactionManagerLookup( properties );

            // Not ported: useGetGeneratedKeys, useScrollableResultSets

            bool useMinimalPuts = PropertiesHelper.GetBoolean(Environment.UseMinimalPuts, properties, false);
            log.Info("Optimize cache for minimal puts: {0}", useMinimalPuts);

            string releaseModeName = PropertiesHelper.GetString(Environment.ReleaseConnections, properties, "auto");
            log.Info("Connection release mode: {0}", releaseModeName);
            ConnectionReleaseMode releaseMode;
            if ("auto".Equals(releaseModeName))
            {
                releaseMode = ConnectionReleaseMode.AfterTransaction;                 //transactionFactory.DefaultReleaseMode;
            }
            else
            {
                releaseMode = ConnectionReleaseModeParser.Convert(releaseModeName);
            }
            settings.ConnectionReleaseMode = releaseMode;

            string defaultSchema  = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null);
            string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null);
            if (defaultSchema != null)
            {
                log.Info("Default schema: {0}", defaultSchema);
            }
            if (defaultCatalog != null)
            {
                log.Info("Default catalog: {0}", defaultCatalog);
            }
            settings.DefaultSchemaName  = defaultSchema;
            settings.DefaultCatalogName = defaultCatalog;

            int batchFetchSize = PropertiesHelper.GetInt32(Environment.DefaultBatchFetchSize, properties, 1);
            log.Info("Default batch fetch size: {0}", batchFetchSize);
            settings.DefaultBatchFetchSize = batchFetchSize;

            //Statistics and logging:

            bool showSql = PropertiesHelper.GetBoolean(Environment.ShowSql, properties, false);
            if (showSql)
            {
                log.Info("echoing all SQL to stdout");
            }
            bool formatSql = PropertiesHelper.GetBoolean(Environment.FormatSql, properties);

            bool useStatistics = PropertiesHelper.GetBoolean(Environment.GenerateStatistics, properties);
            log.Info("Statistics: {0}", EnabledDisabled(useStatistics));
            settings.IsStatisticsEnabled = useStatistics;

            bool useIdentifierRollback = PropertiesHelper.GetBoolean(Environment.UseIdentifierRollBack, properties);
            log.Info("Deleted entity synthetic identifier rollback: {0}", EnabledDisabled(useIdentifierRollback));
            settings.IsIdentifierRollbackEnabled = useIdentifierRollback;

            // queries:

            settings.QueryTranslatorFactory = CreateQueryTranslatorFactory(properties);

            settings.LinqQueryProviderType = CreateLinqQueryProviderType(properties);

            IDictionary <string, string> querySubstitutions = PropertiesHelper.ToDictionary(Environment.QuerySubstitutions,
                                                                                            " ,=;:\n\t\r\f", properties);
            if (log.IsInfoEnabled())
            {
                log.Info("Query language substitutions: {0}", CollectionPrinter.ToString((IDictionary)querySubstitutions));
            }

            #region Hbm2DDL
            string autoSchemaExport = PropertiesHelper.GetString(Environment.Hbm2ddlAuto, properties, null);
            if (SchemaAutoAction.Update == autoSchemaExport)
            {
                settings.IsAutoUpdateSchema = true;
            }
            else if (SchemaAutoAction.Create == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
            }
            else if (SchemaAutoAction.Recreate == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
                settings.IsAutoDropSchema   = true;
            }
            else if (SchemaAutoAction.Validate == autoSchemaExport)
            {
                settings.IsAutoValidateSchema = true;
            }

            string autoKeyWordsImport = PropertiesHelper.GetString(Environment.Hbm2ddlKeyWords, properties, "not-defined");
            if (autoKeyWordsImport == Hbm2DDLKeyWords.None)
            {
                settings.IsKeywordsImportEnabled = false;
                settings.IsAutoQuoteEnabled      = false;
            }
            else if (autoKeyWordsImport == Hbm2DDLKeyWords.Keywords)
            {
                settings.IsKeywordsImportEnabled = true;
            }
            else if (autoKeyWordsImport == Hbm2DDLKeyWords.AutoQuote)
            {
                settings.IsKeywordsImportEnabled = true;
                settings.IsAutoQuoteEnabled      = true;
            }
            else if (autoKeyWordsImport == "not-defined")
            {
                settings.IsKeywordsImportEnabled = true;
                settings.IsAutoQuoteEnabled      = false;
            }

            settings.ThrowOnSchemaUpdate = PropertiesHelper.GetBoolean(Environment.Hbm2ddlThrowOnUpdate, properties, false);

            #endregion

            bool useSecondLevelCache = PropertiesHelper.GetBoolean(Environment.UseSecondLevelCache, properties, true);
            bool useQueryCache       = PropertiesHelper.GetBoolean(Environment.UseQueryCache, properties);

            if (useSecondLevelCache || useQueryCache)
            {
                // The cache provider is needed when we either have second-level cache enabled
                // or query cache enabled.  Note that useSecondLevelCache is enabled by default
                settings.CacheProvider = CreateCacheProvider(properties);
            }
            else
            {
                settings.CacheProvider = new NoCacheProvider();
            }

            string cacheRegionPrefix = PropertiesHelper.GetString(Environment.CacheRegionPrefix, properties, null);
            if (string.IsNullOrEmpty(cacheRegionPrefix))
            {
                cacheRegionPrefix = null;
            }
            if (cacheRegionPrefix != null)
            {
                log.Info("Cache region prefix: {0}", cacheRegionPrefix);
            }

            if (useQueryCache)
            {
                string queryCacheFactoryClassName = PropertiesHelper.GetString(Environment.QueryCacheFactory, properties,
                                                                               typeof(StandardQueryCacheFactory).FullName);
                log.Info("query cache factory: {0}", queryCacheFactoryClassName);
                try
                {
                    settings.QueryCacheFactory =
                        (IQueryCacheFactory)
                        Environment.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(queryCacheFactoryClassName));
                }
                catch (Exception cnfe)
                {
                    throw new HibernateException("could not instantiate IQueryCacheFactory: " + queryCacheFactoryClassName, cnfe);
                }
            }

            string sessionFactoryName = PropertiesHelper.GetString(Environment.SessionFactoryName, properties, null);

            //ADO.NET and connection settings:

            settings.AdoBatchSize = PropertiesHelper.GetInt32(Environment.BatchSize, properties, 0);
            bool orderInserts = PropertiesHelper.GetBoolean(Environment.OrderInserts, properties, (settings.AdoBatchSize > 0));
            log.Info("Order SQL inserts for batching: {0}", EnabledDisabled(orderInserts));
            settings.IsOrderInsertsEnabled = orderInserts;

            bool orderUpdates = PropertiesHelper.GetBoolean(Environment.OrderUpdates, properties, false);
            log.Info("Order SQL updates for batching: {0}", EnabledDisabled(orderUpdates));
            settings.IsOrderUpdatesEnabled = orderUpdates;

            bool wrapResultSets = PropertiesHelper.GetBoolean(Environment.WrapResultSets, properties, false);
            log.Debug("Wrap result sets: {0}", EnabledDisabled(wrapResultSets));
            settings.IsWrapResultSetsEnabled = wrapResultSets;

            bool batchVersionedData = PropertiesHelper.GetBoolean(Environment.BatchVersionedData, properties, false);
            log.Debug("Batch versioned data: {0}", EnabledDisabled(batchVersionedData));
            settings.IsBatchVersionedDataEnabled = batchVersionedData;

            settings.BatcherFactory = CreateBatcherFactory(properties, settings.AdoBatchSize, connectionProvider);

            string         isolationString = PropertiesHelper.GetString(Environment.Isolation, properties, String.Empty);
            IsolationLevel isolation       = IsolationLevel.Unspecified;
            if (isolationString.Length > 0)
            {
                try
                {
                    isolation = (IsolationLevel)Enum.Parse(typeof(IsolationLevel), isolationString);
                    log.Info("Using Isolation Level: {0}", isolation);
                }
                catch (ArgumentException ae)
                {
                    log.Error(ae, "error configuring IsolationLevel {0}", isolationString);
                    throw new HibernateException(
                              "The isolation level of " + isolationString + " is not a valid IsolationLevel.  Please "
                              + "use one of the Member Names from the IsolationLevel.", ae);
                }
            }

            //NH-3619
            FlushMode defaultFlushMode = (FlushMode)Enum.Parse(typeof(FlushMode), PropertiesHelper.GetString(Environment.DefaultFlushMode, properties, FlushMode.Auto.ToString()), false);
            log.Info("Default flush mode: {0}", defaultFlushMode);
            settings.DefaultFlushMode = defaultFlushMode;

#pragma warning disable CS0618 // Type or member is obsolete
            var defaultEntityMode = PropertiesHelper.GetString(Environment.DefaultEntityMode, properties, null);
            if (!string.IsNullOrEmpty(defaultEntityMode))
            {
                log.Warn("Default entity-mode setting is deprecated.");
            }
#pragma warning restore CS0618 // Type or member is obsolete

            bool namedQueryChecking = PropertiesHelper.GetBoolean(Environment.QueryStartupChecking, properties, true);
            log.Info("Named query checking : {0}", EnabledDisabled(namedQueryChecking));
            settings.IsNamedQueryStartupCheckingEnabled = namedQueryChecking;

            // Not ported - settings.StatementFetchSize = statementFetchSize;
            // Not ported - ScrollableResultSetsEnabled
            // Not ported - GetGeneratedKeysEnabled
            settings.SqlStatementLogger = new SqlStatementLogger(showSql, formatSql);

            settings.ConnectionProvider = connectionProvider;
            settings.QuerySubstitutions = querySubstitutions;
            settings.TransactionFactory = transactionFactory;
            // Not ported - TransactionManagerLookup
            settings.SessionFactoryName        = sessionFactoryName;
            settings.AutoJoinTransaction       = PropertiesHelper.GetBoolean(Environment.AutoJoinTransaction, properties, true);
            settings.MaximumFetchDepth         = maxFetchDepth;
            settings.IsQueryCacheEnabled       = useQueryCache;
            settings.IsSecondLevelCacheEnabled = useSecondLevelCache;
            settings.CacheRegionPrefix         = cacheRegionPrefix;
            settings.IsMinimalPutsEnabled      = useMinimalPuts;
            // Not ported - JdbcBatchVersionedData

            settings.QueryModelRewriterFactory = CreateQueryModelRewriterFactory(properties);
            settings.PreTransformerRegistrar   = CreatePreTransformerRegistrar(properties);

            // Avoid dependency on re-linq assembly when PreTransformerRegistrar is null
            if (settings.PreTransformerRegistrar != null)
            {
                settings.LinqPreTransformer = NhRelinqQueryParser.CreatePreTransformer(settings.PreTransformerRegistrar);
            }

            // NHibernate-specific:
            settings.IsolationLevel = isolation;

            bool trackSessionId = PropertiesHelper.GetBoolean(Environment.TrackSessionId, properties, true);
            log.Debug("Track session id: " + EnabledDisabled(trackSessionId));
            settings.TrackSessionId = trackSessionId;

            var multiTenancyStrategy = PropertiesHelper.GetEnum(Environment.MultiTenancy, properties, MultiTenancyStrategy.None);
            settings.MultiTenancyStrategy = multiTenancyStrategy;
            if (multiTenancyStrategy != MultiTenancyStrategy.None)
            {
                log.Debug("multi-tenancy strategy : " + multiTenancyStrategy);
                settings.MultiTenancyConnectionProvider = CreateMultiTenancyConnectionProvider(properties);
            }

            return(settings);
        }
Ejemplo n.º 17
0
 protected EntityType(System.Type persistentClass, string uniqueKeyPropertyName)
 {
     this.associatedClass       = persistentClass;
     this.niceEquals            = !ReflectHelper.OverridesEquals(persistentClass);
     this.uniqueKeyPropertyName = uniqueKeyPropertyName;
 }
 /// <summary>
 /// Extract the <see cref="MethodInfo"/> from a given expression.
 /// </summary>
 /// <typeparam name="TSource">The declaring-type of the method.</typeparam>
 /// <param name="method">The method.</param>
 /// <returns>The <see cref="MethodInfo"/> of the method.</returns>
 public static MethodInfo GetMethod <TSource>(Expression <Action <TSource> > method)
 {
     return(ReflectHelper.GetMethod(method));
 }
Ejemplo n.º 19
0
 public static void QueryCacheFactory <TFactory>(this ICacheConfigurationProperties config) where TFactory : IQueryCacheFactory
 {
     ReflectHelper
     .CastOrThrow <CacheConfigurationProperties>(config, "Setting the query cache factory with Loquacious")
     .QueryCacheFactory <TFactory>();
 }
 /// <summary>
 /// Extract the <see cref="MethodInfo"/> from a given expression.
 /// </summary>
 /// <param name="method">The method.</param>
 /// <returns>The <see cref="MethodInfo"/> of the method.</returns>
 public static MethodInfo GetMethod(Expression <System.Action> method)
 {
     return(ReflectHelper.GetMethod(method));
 }
Ejemplo n.º 21
0
        public MathGenerator()
        {
            SupportedMethods = new[]
            {
                ReflectHelper.FastGetMethod(Math.Sin, default(double)),
                ReflectHelper.FastGetMethod(Math.Cos, default(double)),
                ReflectHelper.FastGetMethod(Math.Tan, default(double)),

                ReflectHelper.FastGetMethod(Math.Sinh, default(double)),
                ReflectHelper.FastGetMethod(Math.Cosh, default(double)),
                ReflectHelper.FastGetMethod(Math.Tanh, default(double)),

                ReflectHelper.FastGetMethod(Math.Asin, default(double)),
                ReflectHelper.FastGetMethod(Math.Acos, default(double)),
                ReflectHelper.FastGetMethod(Math.Atan, default(double)),
                ReflectHelper.FastGetMethod(Math.Atan2, default(double), default(double)),

                ReflectHelper.FastGetMethod(Math.Sqrt, default(double)),

                ReflectHelper.FastGetMethod(Math.Abs, default(decimal)),
                ReflectHelper.FastGetMethod(Math.Abs, default(double)),
                ReflectHelper.FastGetMethod(Math.Abs, default(float)),
                ReflectHelper.FastGetMethod(Math.Abs, default(long)),
                ReflectHelper.FastGetMethod(Math.Abs, default(int)),
                ReflectHelper.FastGetMethod(Math.Abs, default(short)),
                ReflectHelper.FastGetMethod(Math.Abs, default(sbyte)),

                ReflectHelper.FastGetMethod(Math.Sign, default(decimal)),
                ReflectHelper.FastGetMethod(Math.Sign, default(double)),
                ReflectHelper.FastGetMethod(Math.Sign, default(float)),
                ReflectHelper.FastGetMethod(Math.Sign, default(long)),
                ReflectHelper.FastGetMethod(Math.Sign, default(int)),
                ReflectHelper.FastGetMethod(Math.Sign, default(short)),
                ReflectHelper.FastGetMethod(Math.Sign, default(sbyte)),

                ReflectHelper.FastGetMethod(Math.Floor, default(decimal)),
                ReflectHelper.FastGetMethod(Math.Floor, default(double)),
                ReflectHelper.FastGetMethod(decimal.Floor, default(decimal)),

                ReflectHelper.FastGetMethod(Math.Ceiling, default(decimal)),
                ReflectHelper.FastGetMethod(Math.Ceiling, default(double)),
                ReflectHelper.FastGetMethod(decimal.Ceiling, default(decimal)),

                ReflectHelper.FastGetMethod(Math.Pow, default(double), default(double)),

#if NETCOREAPP2_0
                ReflectHelper.FastGetMethod(MathF.Sin, default(float)),
                ReflectHelper.FastGetMethod(MathF.Cos, default(float)),
                ReflectHelper.FastGetMethod(MathF.Tan, default(float)),

                ReflectHelper.FastGetMethod(MathF.Sinh, default(float)),
                ReflectHelper.FastGetMethod(MathF.Cosh, default(float)),
                ReflectHelper.FastGetMethod(MathF.Tanh, default(float)),

                ReflectHelper.FastGetMethod(MathF.Asin, default(float)),
                ReflectHelper.FastGetMethod(MathF.Acos, default(float)),
                ReflectHelper.FastGetMethod(MathF.Atan, default(float)),
                ReflectHelper.FastGetMethod(MathF.Atan2, default(float), default(float)),

                ReflectHelper.FastGetMethod(MathF.Sqrt, default(float)),

                ReflectHelper.FastGetMethod(MathF.Abs, default(float)),

                ReflectHelper.FastGetMethod(MathF.Sign, default(float)),

                ReflectHelper.FastGetMethod(MathF.Floor, default(float)),

                ReflectHelper.FastGetMethod(MathF.Ceiling, default(float)),

                ReflectHelper.FastGetMethod(MathF.Pow, default(float), default(float)),
#endif
            };
        }
 /// <summary>
 /// Gets the field or property to be accessed.
 /// </summary>
 /// <typeparam name="TSource">The declaring-type of the property.</typeparam>
 /// <typeparam name="TResult">The type of the property.</typeparam>
 /// <param name="property">The expression representing the property getter.</param>
 /// <returns>The <see cref="MemberInfo"/> of the property.</returns>
 public static MemberInfo GetProperty <TSource, TResult>(Expression <Func <TSource, TResult> > property)
 {
     return(ReflectHelper.GetProperty(property));
 }
Ejemplo n.º 23
0
        private void BuildFilterCachingStrategy(IDictionary <string, string> properties)
        {
            string impl = GetProperty(properties, Environment.FilterCachingStrategy);

            if (string.IsNullOrEmpty(impl) || impl.ToUpperInvariant().Equals("MRU"))
            {
                filterCachingStrategy = new MruFilterCachingStrategy();
            }
            else
            {
                try
                {
                    filterCachingStrategy = (IFilterCachingStrategy)Activator.CreateInstance(ReflectHelper.ClassForName(impl));
                }
                catch (InvalidCastException)
                {
                    throw new SearchException("Class does not implement IFilterCachingStrategy: " + impl);
                }
                catch (Exception ex)
                {
                    throw new SearchException("Failed to instantiate IFilterCachingStrategy with type " + impl, ex);
                }
            }

            filterCachingStrategy.Initialize(properties);
        }
Ejemplo n.º 24
0
        public static void Main(string[] args)
        {
            try
            {
                var cfg = new Configuration();

                bool script = true;
                // If true then execute db updates, otherwise just generate and display updates
                bool doUpdate = true;
                //String propFile = null;

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].StartsWith("--"))
                    {
                        if (args[i].Equals("--quiet"))
                        {
                            script = false;
                        }
                        else if (args[i].StartsWith("--properties="))
                        {
                            throw new NotSupportedException("No properties file for .NET, use app.config instead");
                            //propFile = args[i].Substring( 13 );
                        }
                        else if (args[i].StartsWith("--config="))
                        {
                            cfg.Configure(args[i].Substring(9));
                        }
                        else if (args[i].StartsWith("--text"))
                        {
                            doUpdate = false;
                        }
                        else if (args[i].StartsWith("--naming="))
                        {
                            cfg.SetNamingStrategy(
                                (INamingStrategy)
                                Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(args[i].Substring(9))));
                        }
                    }
                    else
                    {
                        cfg.AddFile(args[i]);
                    }
                }

                /* NH: No props file for .NET
                 * if ( propFile != null ) {
                 *      Hashtable props = new Hashtable();
                 *      props.putAll( cfg.Properties );
                 *      props.load( new FileInputStream( propFile ) );
                 *      cfg.SetProperties( props );
                 * }*/

                new SchemaUpdate(cfg).Execute(script, doUpdate);
            }
            catch (Exception e)
            {
                log.Error("Error running schema update", e);
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 25
0
 public LengthGenerator()
 {
     SupportedProperties = new[] { ReflectHelper.GetProperty((string x) => x.Length) };
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Configures the driver for the ConnectionProvider.
        /// </summary>
        /// <param name="settings">An <see cref="IDictionary"/> that contains the settings for the Driver.</param>
        /// <exception cref="HibernateException">
        /// Thrown when the <see cref="Environment.ConnectionDriver"/> could not be
        /// found in the <c>settings</c> parameter or there is a problem with creating
        /// the <see cref="IDriver"/>.
        /// </exception>
        protected virtual void ConfigureDriver(IDictionary <string, string> settings)
        {
            string driverClass;

            if (!settings.TryGetValue(Environment.ConnectionDriver, out driverClass))
            {
                throw new HibernateException("The " + Environment.ConnectionDriver +
                                             " must be specified in the NHibernate configuration section.");
            }
            else
            {
                try
                {
                    driver =
                        (IDriver)Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(driverClass));
                    driver.Configure(settings);
                }
                catch (Exception e)
                {
                    throw new HibernateException("Could not create the driver from " + driverClass + ".", e);
                }
            }
        }
Ejemplo n.º 27
0
 public TAttributeType[] GetAttributes <TAttributeType>(bool inherit)
     where TAttributeType : Attribute
 => ReflectHelper.GetAttributes <TAttributeType>(this.TestMethod, inherit)
 ?? EmptyHolder <TAttributeType> .Array;
Ejemplo n.º 28
0
 //6.0 TODO: Merge to IUnionSubclassAttributesMapper
 public static void Extends(this IUnionSubclassAttributesMapper mapper, string entityOrClassName)
 {
     ReflectHelper.CastOrThrow <UnionSubclassMapper>(mapper, "Extends(entityOrClassName)").Extends(entityOrClassName);
 }
Ejemplo n.º 29
0
        public Settings BuildSettings(IDictionary <string, string> properties)
        {
            Settings settings = new Settings();

            Dialect.Dialect dialect;
            try
            {
                dialect = Dialect.Dialect.GetDialect(properties);
                Dictionary <string, string> temp = new Dictionary <string, string>();

                foreach (KeyValuePair <string, string> de in dialect.DefaultProperties)
                {
                    temp[de.Key] = de.Value;
                }
                foreach (KeyValuePair <string, string> de in properties)
                {
                    temp[de.Key] = de.Value;
                }
                properties = temp;
            }
            catch (HibernateException he)
            {
                log.Warn("No dialect set - using GenericDialect: " + he.Message);
                dialect = new GenericDialect();
            }
            settings.Dialect = dialect;

            settings.LinqToHqlGeneratorsRegistry = LinqToHqlGeneratorsRegistryFactory.CreateGeneratorsRegistry(properties);

            #region SQL Exception converter

            ISQLExceptionConverter sqlExceptionConverter;
            try
            {
                sqlExceptionConverter = SQLExceptionConverterFactory.BuildSQLExceptionConverter(dialect, properties);
            }
            catch (HibernateException)
            {
                log.Warn("Error building SQLExceptionConverter; using minimal converter");
                sqlExceptionConverter = SQLExceptionConverterFactory.BuildMinimalSQLExceptionConverter();
            }
            settings.SqlExceptionConverter = sqlExceptionConverter;

            #endregion

            bool comments = PropertiesHelper.GetBoolean(Environment.UseSqlComments, properties);
            log.Info("Generate SQL with comments: " + EnabledDisabled(comments));
            settings.IsCommentsEnabled = comments;

            int maxFetchDepth = PropertiesHelper.GetInt32(Environment.MaxFetchDepth, properties, -1);
            if (maxFetchDepth != -1)
            {
                log.Info("Maximum outer join fetch depth: " + maxFetchDepth);
            }

            IConnectionProvider connectionProvider = ConnectionProviderFactory.NewConnectionProvider(properties);
            ITransactionFactory transactionFactory = CreateTransactionFactory(properties);
            // TransactionManagerLookup transactionManagerLookup = TransactionManagerLookupFactory.GetTransactionManagerLookup( properties );

            // Not ported: useGetGeneratedKeys, useScrollableResultSets

            bool useMinimalPuts = PropertiesHelper.GetBoolean(Environment.UseMinimalPuts, properties, false);
            log.Info("Optimize cache for minimal puts: " + useMinimalPuts);

            string releaseModeName = PropertiesHelper.GetString(Environment.ReleaseConnections, properties, "auto");
            log.Info("Connection release mode: " + releaseModeName);
            ConnectionReleaseMode releaseMode;
            if ("auto".Equals(releaseModeName))
            {
                releaseMode = ConnectionReleaseMode.AfterTransaction;                 //transactionFactory.DefaultReleaseMode;
            }
            else
            {
                releaseMode = ConnectionReleaseModeParser.Convert(releaseModeName);
            }
            settings.ConnectionReleaseMode = releaseMode;

            string defaultSchema  = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null);
            string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null);
            if (defaultSchema != null)
            {
                log.Info("Default schema: " + defaultSchema);
            }
            if (defaultCatalog != null)
            {
                log.Info("Default catalog: " + defaultCatalog);
            }
            settings.DefaultSchemaName  = defaultSchema;
            settings.DefaultCatalogName = defaultCatalog;

            int batchFetchSize = PropertiesHelper.GetInt32(Environment.DefaultBatchFetchSize, properties, 1);
            log.Info("Default batch fetch size: " + batchFetchSize);
            settings.DefaultBatchFetchSize = batchFetchSize;

            //Statistics and logging:

            bool showSql = PropertiesHelper.GetBoolean(Environment.ShowSql, properties, false);
            if (showSql)
            {
                log.Info("echoing all SQL to stdout");
            }
            bool formatSql = PropertiesHelper.GetBoolean(Environment.FormatSql, properties);

            bool useStatistics = PropertiesHelper.GetBoolean(Environment.GenerateStatistics, properties);
            log.Info("Statistics: " + EnabledDisabled(useStatistics));
            settings.IsStatisticsEnabled = useStatistics;

            bool useIdentifierRollback = PropertiesHelper.GetBoolean(Environment.UseIdentifierRollBack, properties);
            log.Info("Deleted entity synthetic identifier rollback: " + EnabledDisabled(useIdentifierRollback));
            settings.IsIdentifierRollbackEnabled = useIdentifierRollback;

            // queries:

            settings.QueryTranslatorFactory = CreateQueryTranslatorFactory(properties);

            IDictionary <string, string> querySubstitutions = PropertiesHelper.ToDictionary(Environment.QuerySubstitutions,
                                                                                            " ,=;:\n\t\r\f", properties);
            if (log.IsInfoEnabled)
            {
                log.Info("Query language substitutions: " + CollectionPrinter.ToString((IDictionary)querySubstitutions));
            }

            #region Hbm2DDL
            string autoSchemaExport = PropertiesHelper.GetString(Environment.Hbm2ddlAuto, properties, null);
            if (SchemaAutoAction.Update == autoSchemaExport)
            {
                settings.IsAutoUpdateSchema = true;
            }
            else if (SchemaAutoAction.Create == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
            }
            else if (SchemaAutoAction.Recreate == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
                settings.IsAutoDropSchema   = true;
            }
            else if (SchemaAutoAction.Validate == autoSchemaExport)
            {
                settings.IsAutoValidateSchema = true;
            }

            string autoKeyWordsImport = PropertiesHelper.GetString(Environment.Hbm2ddlKeyWords, properties, "not-defined");
            autoKeyWordsImport = autoKeyWordsImport.ToLowerInvariant();
            if (autoKeyWordsImport == Hbm2DDLKeyWords.None)
            {
                settings.IsKeywordsImportEnabled = false;
                settings.IsAutoQuoteEnabled      = false;
            }
            else if (autoKeyWordsImport == Hbm2DDLKeyWords.Keywords)
            {
                settings.IsKeywordsImportEnabled = true;
            }
            else if (autoKeyWordsImport == Hbm2DDLKeyWords.AutoQuote)
            {
                settings.IsKeywordsImportEnabled = true;
                settings.IsAutoQuoteEnabled      = true;
            }
            else if (autoKeyWordsImport == "not-defined")
            {
                settings.IsKeywordsImportEnabled = true;
                settings.IsAutoQuoteEnabled      = false;
            }

            #endregion

            bool useSecondLevelCache = PropertiesHelper.GetBoolean(Environment.UseSecondLevelCache, properties, true);
            bool useQueryCache       = PropertiesHelper.GetBoolean(Environment.UseQueryCache, properties);

            if (useSecondLevelCache || useQueryCache)
            {
                // The cache provider is needed when we either have second-level cache enabled
                // or query cache enabled.  Note that useSecondLevelCache is enabled by default
                settings.CacheProvider = CreateCacheProvider(properties);
            }
            else
            {
                settings.CacheProvider = new NoCacheProvider();
            }

            string cacheRegionPrefix = PropertiesHelper.GetString(Environment.CacheRegionPrefix, properties, null);
            if (string.IsNullOrEmpty(cacheRegionPrefix))
            {
                cacheRegionPrefix = null;
            }
            if (cacheRegionPrefix != null)
            {
                log.Info("Cache region prefix: " + cacheRegionPrefix);
            }


            if (useQueryCache)
            {
                string queryCacheFactoryClassName = PropertiesHelper.GetString(Environment.QueryCacheFactory, properties,
                                                                               typeof(StandardQueryCacheFactory).FullName);
                log.Info("query cache factory: " + queryCacheFactoryClassName);
                try
                {
                    settings.QueryCacheFactory =
                        (IQueryCacheFactory)
                        Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(queryCacheFactoryClassName));
                }
                catch (Exception cnfe)
                {
                    throw new HibernateException("could not instantiate IQueryCacheFactory: " + queryCacheFactoryClassName, cnfe);
                }
            }

            string sessionFactoryName = PropertiesHelper.GetString(Environment.SessionFactoryName, properties, null);

            //ADO.NET and connection settings:

            // TODO: Environment.BatchVersionedData
            settings.AdoBatchSize = PropertiesHelper.GetInt32(Environment.BatchSize, properties, 0);
            bool wrapResultSets = PropertiesHelper.GetBoolean(Environment.WrapResultSets, properties, false);
            log.Debug("Wrap result sets: " + EnabledDisabled(wrapResultSets));
            settings.IsWrapResultSetsEnabled = wrapResultSets;
            settings.BatcherFactory          = CreateBatcherFactory(properties, settings.AdoBatchSize, connectionProvider);

            string         isolationString = PropertiesHelper.GetString(Environment.Isolation, properties, String.Empty);
            IsolationLevel isolation       = IsolationLevel.Unspecified;
            if (isolationString.Length > 0)
            {
                try
                {
                    isolation = (IsolationLevel)Enum.Parse(typeof(IsolationLevel), isolationString);
                    log.Info("Using Isolation Level: " + isolation);
                }
                catch (ArgumentException ae)
                {
                    log.Error("error configuring IsolationLevel " + isolationString, ae);
                    throw new HibernateException(
                              "The isolation level of " + isolationString + " is not a valid IsolationLevel.  Please "
                              + "use one of the Member Names from the IsolationLevel.", ae);
                }
            }

            EntityMode defaultEntityMode =
                EntityModeHelper.Parse(PropertiesHelper.GetString(Environment.DefaultEntityMode, properties, "poco"));
            log.Info("Default entity-mode: " + defaultEntityMode);
            settings.DefaultEntityMode = defaultEntityMode;

            bool namedQueryChecking = PropertiesHelper.GetBoolean(Environment.QueryStartupChecking, properties, true);
            log.Info("Named query checking : " + EnabledDisabled(namedQueryChecking));
            settings.IsNamedQueryStartupCheckingEnabled = namedQueryChecking;

            // Not ported - settings.StatementFetchSize = statementFetchSize;
            // Not ported - ScrollableResultSetsEnabled
            // Not ported - GetGeneratedKeysEnabled
            settings.SqlStatementLogger = new SqlStatementLogger(showSql, formatSql);

            settings.ConnectionProvider = connectionProvider;
            settings.QuerySubstitutions = querySubstitutions;
            settings.TransactionFactory = transactionFactory;
            // Not ported - TransactionManagerLookup
            settings.SessionFactoryName        = sessionFactoryName;
            settings.MaximumFetchDepth         = maxFetchDepth;
            settings.IsQueryCacheEnabled       = useQueryCache;
            settings.IsSecondLevelCacheEnabled = useSecondLevelCache;
            settings.CacheRegionPrefix         = cacheRegionPrefix;
            settings.IsMinimalPutsEnabled      = useMinimalPuts;
            // Not ported - JdbcBatchVersionedData

            // NHibernate-specific:
            settings.IsolationLevel = isolation;

            return(settings);
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UnitTestRunner"/> class.
 /// </summary>
 /// <param name="captureDebugTraces"> Specifies whether debug traces should be captured or not.  </param>
 /// <param name="reflectHelper"> The reflect Helper. </param>
 internal UnitTestRunner(bool captureDebugTraces, ReflectHelper reflectHelper)
 {
     this.typeCache          = new TypeCache(reflectHelper);
     this.captureDebugTraces = captureDebugTraces;
 }