static async Task StartServerAsync()
        {
            DateTime lastConfigRefresh = DateTime.UtcNow;

            UniverseInfoServers = new MUIS[Settings.Ports.Length];
            for (int i = 0; i < UniverseInfoServers.Length; ++i)
            {
                Logger.Info($"Starting MUIS on port {Settings.Ports[i]}.");
                UniverseInfoServers[i] = new MUIS(Settings.Ports[i]);
                UniverseInfoServers[i].Start();
                Logger.Info($"MUIS started.");
            }

            try
            {
                while (true)
                {
                    // Tick
                    await Task.WhenAll(UniverseInfoServers.Select(x => x.Tick()));

                    // Reload config
                    if ((DateTime.UtcNow - lastConfigRefresh).TotalMilliseconds > Settings.RefreshConfigInterval)
                    {
                        RefreshConfig();
                        lastConfigRefresh = DateTime.UtcNow;
                    }

                    await Task.Delay(100);
                }
            }
            finally
            {
                await Task.WhenAll(UniverseInfoServers.Select(x => x.Stop()));
            }
        }
Beispiel #2
0
        public override void ChannelActive(IChannelHandlerContext ctx)
        {
            IChannelGroup g = Group;

            if (g == null)
            {
                lock (this)
                {
                    if (Group == null)
                    {
                        Group = g = new DefaultChannelGroup(ctx.Executor);
                    }
                }
            }

            // Detect when client disconnects
            ctx.Channel.CloseCompletion.ContinueWith((x) =>
            {
                Logger.Info("Channel Closed");
                OnChannelInactive?.Invoke(ctx.Channel);
            });

            // Add to channels list
            g.Add(ctx.Channel);

            // Send event upstream
            OnChannelActive?.Invoke(ctx.Channel);
        }
Beispiel #3
0
        public void InfoTest1()
        {
            IInternalLogger target = CreateLogger();

            target.SetLevel(LogLevel.Always);
            calls = 0;
            target.Info(message, id);
            Assert.AreEqual(calls, 0);
            calls = 0;
            target.SetLevel(LogLevel.All);
            target.Info(message, ids);
            Assert.AreEqual(calls, 1);

            Assert.AreEqual(lastItem.Category, category);
            Assert.AreEqual(lastItem.Level, LogLevel.Info);
            Assert.IsNull(lastItem.Ex);
            Assert.AreEqual(lastItem.Message, message);
            Assert.IsNotNull(lastItem.Ids);
            Assert.AreEqual(ids, lastItem.Ids);

            calls = 0;
            target.SetLevel(LogLevel.Info);
            target.Info(message, id);
            Assert.AreEqual(calls, 1);
        }
        void StartLoop()
        {
            IntPtr handle = this.loop.Handle;

            try
            {
                this.UpdateLastExecutionTime();
                this.Initialize();
                if (Interlocked.CompareExchange(ref this.executionState, StartedState, NotStartedState) != NotStartedState)
                {
                    throw new InvalidOperationException($"Invalid {nameof(LoopExecutor)} state {this.executionState}");
                }
                this.loopRunStart.Set();
                this.loop.Run(uv_run_mode.UV_RUN_DEFAULT);
            }
            catch (Exception ex)
            {
                this.loopRunStart.Set();
                Logger.Error("Loop {}:{} run default error.", this.thread.Name, handle, ex);
                this.terminationCompletionSource.TrySetException(ex);
            }
            finally
            {
                Logger.Info("Loop {}:{} thread finished.", this.thread.Name, handle);
                this.CleanupAndTerminate();
            }
        }
        // cannot be instantiated
        public static IConnectionProvider NewConnectionProvider(IDictionary <string, string> settings)
        {
            IConnectionProvider connections;
            string providerClass;

            if (settings.TryGetValue(Environment.ConnectionProvider, out providerClass))
            {
                try
                {
                    log.Info("Initializing connection provider: " + providerClass);
                    connections =
                        (IConnectionProvider)
                        Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(providerClass));
                }
                catch (Exception e)
                {
                    log.Fatal("Could not instantiate connection provider", e);
                    throw new HibernateException("Could not instantiate connection provider: " + providerClass, e);
                }
            }
            else if (settings.ContainsKey(Environment.ConnectionString) || settings.ContainsKey(Environment.ConnectionStringName))
            {
                connections = new DriverConnectionProvider();
            }
            else
            {
                log.Info("No connection provider specified, UserSuppliedConnectionProvider will be used.");
                connections = new UserSuppliedConnectionProvider();
            }
            connections.Configure(settings);
            return(connections);
        }
Beispiel #6
0
        public Loop()
        {
            int size = NativeMethods.uv_loop_size().ToInt32();

            this.Handle = Marshal.AllocHGlobal(size);
            try
            {
                int result = NativeMethods.uv_loop_init(this.Handle);
                if (result < 0)
                {
                    throw NativeMethods.CreateError((uv_err_code)result);
                }
            }
            catch
            {
                Marshal.FreeHGlobal(this.Handle);
                throw;
            }

            GCHandle gcHandle = GCHandle.Alloc(this, GCHandleType.Normal);

            ((uv_loop_t *)this.Handle)->data = GCHandle.ToIntPtr(gcHandle);

            if (Logger.InfoEnabled)
            {
                Logger.Info($"Loop {this.Handle} allocated.");
            }
        }
Beispiel #7
0
        protected override void Initialize()
        {
            clazz =
                ReflectHelper.ClassForFullName(
                    TypeNameParser.Parse(meta.name, meta.rootMapping.@namespace, meta.rootMapping.assembly).ToString());
            classAttributes = meta.attributename == null
                                                ? new List <Attribute>(0)
                                                : new List <Attribute>(meta.attributename.Length);

            List <MemberInfo> lmembers = meta.property == null
                                                        ? new List <MemberInfo>(0)
                                                        : new List <MemberInfo>(meta.property.Length);

            if (meta.attributename != null)
            {
                log.Debug("Looking for class attributes");
                foreach (NhvmClassAttributename attributename in meta.attributename)
                {
                    log.Info("Attribute to look for = " + GetText(attributename));
                    Attribute classAttribute = RuleAttributeFactory.CreateAttributeFromClass(clazz, attributename);
                    classAttributes.Add(classAttribute);
                }
            }

            if (meta.property != null)
            {
                foreach (NhvmProperty property in meta.property)
                {
                    MemberInfo currentMember = TypeUtils.GetPropertyOrField(clazz, property.name);

                    if (currentMember == null)
                    {
                        throw new InvalidPropertyNameException(property.name, clazz);
                    }

                    log.Info("Looking for rules for property : " + property.name);
                    lmembers.Add(currentMember);

                    // creation of member attributes
                    foreach (object rule in property.Items)
                    {
                        Attribute thisAttribute = RuleAttributeFactory.CreateAttributeFromRule(rule, meta.rootMapping.assembly,
                                                                                               meta.rootMapping.@namespace);

                        if (thisAttribute != null)
                        {
                            log.Info(string.Format("Adding member {0} to dictionary with attribute {1}", currentMember.Name, thisAttribute));
                            if (!membersAttributesDictionary.ContainsKey(currentMember))
                            {
                                membersAttributesDictionary.Add(currentMember, new List <Attribute>());
                            }

                            membersAttributesDictionary[currentMember].Add(thisAttribute);
                        }
                    }
                }
            }
            members = lmembers.ToArray();
        }
Beispiel #8
0
 /// <inheritdoc />
 public void Clear()
 {
     if (log.IsInfoEnabled)
     {
         log.Info("clearing all objects from system");
     }
     system.Clear();
 }
Beispiel #9
0
        private IByteBuffer EncodeMetaData()
        {
            logger.Info($"Metadata:{Metadata}");
            var           buffer = Unpooled.Buffer();
            List <Object> meta   = new List <object>();

            meta.Add("onMetaData");
            meta.Add(Metadata);
            AMF0.Encode(buffer, meta);
            return(buffer);
        }
        public override void ChannelActive(IChannelHandlerContext ctx)
        {
            // Detect when client disconnects
            ctx.Channel.CloseCompletion.ContinueWith((x) =>
            {
                Logger.Info("Channel Closed");
                OnChannelInactive?.Invoke(ctx.Channel);
            });

            // Send event upstream
            OnChannelActive?.Invoke(ctx.Channel);
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            //
            Initialize();

            Logger.Info($"Starting NAT on port {NATServer.Port}.");
            Task.WaitAll(NATServer.Start());
            Logger.Info($"NAT started.");

            while (NATServer.IsRunning)
            {
                Thread.Sleep(500);
            }
        }
Beispiel #12
0
        public ITableMetadata GetTableMetadata(string name, string schema, string catalog, bool isQuoted)
        {
            string         identifier = Identifier(catalog, schema, name);
            ITableMetadata table;

            tables.TryGetValue(identifier, out table);
            if (table != null)
            {
                return(table);                // EARLY exit
            }
            try
            {
                DataTable metaInfo;
                if ((isQuoted && meta.StoresMixedCaseQuotedIdentifiers))
                {
                    metaInfo = meta.GetTables(catalog, schema, name, Types);
                }
                else
                {
                    if ((isQuoted && meta.StoresUpperCaseQuotedIdentifiers) || (!isQuoted && meta.StoresUpperCaseIdentifiers))
                    {
                        metaInfo =
                            meta.GetTables(StringHelper.ToUpperCase(catalog), StringHelper.ToUpperCase(schema),
                                           StringHelper.ToUpperCase(name), Types);
                    }
                    else
                    {
                        if ((isQuoted && meta.StoresLowerCaseQuotedIdentifiers) || (!isQuoted && meta.StoresLowerCaseIdentifiers))
                        {
                            metaInfo =
                                meta.GetTables(StringHelper.ToLowerCase(catalog), StringHelper.ToLowerCase(schema),
                                               StringHelper.ToLowerCase(name), Types);
                        }
                        else
                        {
                            metaInfo = meta.GetTables(catalog, schema, name, Types);
                        }
                    }
                }
                DataRowCollection rows = metaInfo.Rows;

                foreach (DataRow tableRow in rows)
                {
                    string tableName = Convert.ToString(tableRow[meta.ColumnNameForTableName]);
                    if (name.Equals(tableName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        table = meta.GetTableMetadata(tableRow, extras);
                        tables[identifier] = table;
                        return(table);
                    }
                }

                log.Info("table not found: " + name);
                return(null);
            }
            catch (DbException sqle)
            {
                throw ADOExceptionHelper.Convert(sqlExceptionConverter, sqle, "could not get table metadata: " + name);
            }
        }
        /// <summary>
        /// Initializes the <see cref="SysCacheProvider"/> class.
        /// </summary>
        static SysCacheProvider()
        {
            Log = LoggerProvider.LoggerFor(typeof(SysCacheProvider));
            // We need to determine which cache regions are configured in the configuration file, but we cant create the
            // cache regions at this time because there could be nhibernate configuration values
            // that we need for the cache regions such as connection info to be used for data dependencies. But this info
            // isn't available until build cache is called. So allocate space but only create them on demand.

            var configSection = SysCacheSection.GetSection();

            if (configSection != null && configSection.CacheRegions.Count > 0)
            {
                CacheRegionSettings = new Dictionary <string, CacheRegionElement>(configSection.CacheRegions.Count);
                foreach (var cacheRegion in configSection.CacheRegions)
                {
                    if (cacheRegion is CacheRegionElement element)
                    {
                        CacheRegionSettings.Add(element.Name, element);
                    }
                }
            }
            else
            {
                CacheRegionSettings = new Dictionary <string, CacheRegionElement>(0);
                Log.Info(
                    "No cache regions specified. Cache regions can be specified in sysCache configuration section with custom settings.");
            }
        }
Beispiel #14
0
        static void RunLoop(object state)
        {
            var loop = (LoopExecutor)state;

            loop.SetCurrentExecutor(loop);

            Task.Factory.StartNew(
                () =>
            {
                try
                {
                    loop.Initialize();
                    loop.executionState = StartedState;
                    loop.loop.Run(uv_run_mode.UV_RUN_DEFAULT);
                    Logger.Info("{}: {} run finished.", loop.thread.Name, loop.loop.Handle);
                    loop.terminationCompletionSource.TryComplete();
                }
                catch (Exception ex)
                {
                    Logger.Error("{}: execution loop failed", loop.thread.Name, ex);
                    loop.terminationCompletionSource.TrySetException(ex);
                }

                loop.executionState = TerminatedState;
            },
                CancellationToken.None,
                TaskCreationOptions.None,
                loop.scheduler);
        }
Beispiel #15
0
 public static void IgnoringFrameForStreamRst(this IInternalLogger logger, IChannelHandlerContext ctx, Http2FrameTypes frameName, bool isResetSent, int lastStreamKnownByPeer)
 {
     logger.Info("{} ignoring {} frame for stream {}", ctx.Channel, frameName,
                 isResetSent ? "RST_STREAM sent." :
                 ("Stream created after GOAWAY sent. Last known stream by peer " +
                  lastStreamKnownByPeer));
 }
        /// <summary> Build a SQLExceptionConverter instance. </summary>
        /// <param name="dialect">The defined dialect. </param>
        /// <param name="properties">The configuration properties. </param>
        /// <returns> An appropriate <see cref="ISQLExceptionConverter"/> instance. </returns>
        /// <remarks>
        /// First, looks for a <see cref="Cfg.Environment.SqlExceptionConverter"/> property to see
        /// if the configuration specified the class of a specific converter to use.  If this
        /// property is set, attempt to construct an instance of that class.  If not set, or
        /// if construction fails, the converter specific to the dialect will be used.
        /// </remarks>
        public static ISQLExceptionConverter BuildSQLExceptionConverter(Dialect.Dialect dialect, IDictionary <string, string> properties)
        {
            ISQLExceptionConverter converter = null;

            string converterClassName;

            properties.TryGetValue(Cfg.Environment.SqlExceptionConverter, out converterClassName);
            if (!string.IsNullOrEmpty(converterClassName))
            {
                converter = ConstructConverter(converterClassName, dialect.ViolatedConstraintNameExtracter);
            }

            if (converter == null)
            {
                log.Info("Using dialect defined converter");
                converter = dialect.BuildSQLExceptionConverter();
            }

            IConfigurable confConv = converter as IConfigurable;

            if (confConv != null)
            {
                try
                {
                    confConv.Configure(properties);
                }
                catch (HibernateException e)
                {
                    log.Warn("Unable to configure SQLExceptionConverter", e);
                    throw;
                }
            }

            return(converter);
        }
Beispiel #17
0
        /// <summary>
        /// Initializes the index at the given index
        /// </summary>
        protected FSDirectory InitializeIndex(DirectoryInfo path, string indexName = null)
        {
            try
            {
                var directory = FSDirectory.Open(path.FullName);

                // Exit if the index already exists
                if (IndexReader.IndexExists(directory))
                {
                    return(directory);
                }

                // TODO:RB: re-add logging
                log.DebugFormat("Initialize index: '{0}'", path);

                var maxFieldLength = IndexWriter.MaxFieldLength.UNLIMITED;
                var policy         = new KeepOnlyLastCommitDeletionPolicy();

                using (var analyzer = new StandardAnalyzer(Environment.LuceneVersion))
                    using (var indexWriter = new IndexWriter(directory, analyzer, true, policy, maxFieldLength))
                    {
                        // Do nothing, index writer's constructor has initialized the index
                        log.Info("Index writer called to create directory" + path.FullName);

                        indexWriter.Close();
                    }

                return(directory);
            }
            catch (IOException e)
            {
                throw new HibernateException("Unable to initialize index: " + indexName ?? path.FullName, e);
            }
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            ConfigurationHelper.SetConsoleLogger();
            Logger.Info("test info logger");
            Logger.Error(new Exception("测试"));
            Console.WriteLine("当前线程ID:" + Thread.CurrentThread.ManagedThreadId.ToString());

            AsyncHelper.Run(async() =>
            {
                await new TaskFactory().StartNew(() =>
                {
                    Console.WriteLine("当前线程ID:" + Thread.CurrentThread.ManagedThreadId.ToString());
                });

                //  throw new Exception("异常报错");
            }
                            );


            //User info = new User() { UserID = 1, userName = "******" };

            //var jsonString = Json.GetJsonByObj(info);

            ////  Console.WriteLine(jsonString);

            //Logger.Info("test info Json {0}", jsonString);

            Console.ReadLine();

            Task.Factory.StartNew(() =>
            {
                return(true);
            });
        }
Beispiel #19
0
        private static void PopulateResult(
            string fieldName, IFieldBridge fieldBridge, Attributes.Store fieldStore,
            string[] fields, object[] result, Document document
            )
        {
            int matchingPosition = GetFieldPosition(fields, fieldName);

            if (matchingPosition != -1)
            {
                //TODO make use of an isTwoWay() method
                if (fieldStore != Attributes.Store.No && fieldBridge is ITwoWayFieldBridge)
                {
                    result[matchingPosition] = ((ITwoWayFieldBridge)fieldBridge).Get(fieldName, document);
                    if (logger.IsInfoEnabled)
                    {
                        logger.Info("Field " + fieldName + " projected as " + result[matchingPosition]);
                    }
                }
                else
                {
                    if (fieldStore == Attributes.Store.No)
                    {
                        throw new SearchException("Projecting an unstored field: " + fieldName);
                    }

                    throw new SearchException("IFieldBridge is not a ITwoWayFieldBridge: " + fieldBridge.GetType());
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// Adds an import to allow for the full class name <c>Namespace.Entity (AssemblyQualifiedName)</c>
        /// to be referenced as <c>Entity</c> or some other name in HQL.
        /// </summary>
        /// <param name="className">The name of the type that is being renamed.</param>
        /// <param name="rename">The new name to use in HQL for the type.</param>
        /// <exception cref="MappingException">Thrown when the rename already identifies another type.</exception>
        public void AddImport(string className, string rename)
        {
            if (rename == null)
            {
                throw new ArgumentNullException("rename");
            }
            // if the imports dictionary already contains the rename, then make sure
            // the rename is not for a different className.  If it is a different className
            // then we probably have 2 classes with the same name in a different namespace.  To
            // prevent this error one of the classes needs to have the attribute "
            string existing;

            imports.TryGetValue(rename, out existing);
            imports[rename] = className;
            if (existing != null)
            {
                if (existing.Equals(className))
                {
                    log.Info("duplicate import: " + className + "->" + rename);
                }
                else
                {
                    throw new DuplicateMappingException(
                              "duplicate import: " + rename + " refers to both " + className + " and " + existing
                              + " (try using auto-import=\"false\")", "import", rename);
                }
            }
        }
        public virtual void Configure(IType type, IDictionary <string, string> parms, Dialect.Dialect dialect)
        {
            IdentifierType = type;

            bool forceTableUse = PropertiesHelper.GetBoolean(ForceTableParam, parms, false);

            string sequenceName = DetermineSequenceName(parms, dialect);

            int initialValue  = DetermineInitialValue(parms);
            int incrementSize = DetermineIncrementSize(parms);

            string optimizationStrategy = DetermineOptimizationStrategy(parms, incrementSize);

            incrementSize = DetermineAdjustedIncrementSize(optimizationStrategy, incrementSize);

            Optimizer = OptimizerFactory.BuildOptimizer(
                optimizationStrategy,
                IdentifierType.ReturnedClass,
                incrementSize,
                PropertiesHelper.GetInt32(InitialParam, parms, -1));                 // Use -1 as default initial value here to signal that it's not set.

            if (!forceTableUse && RequiresPooledSequence(initialValue, incrementSize, Optimizer) && !dialect.SupportsPooledSequences)
            {
                // force the use of a table (overriding whatever the user configured) since the dialect
                // doesn't support the sequence features we need.
                forceTableUse = true;
                Log.Info("Forcing table use for sequence-style generator due to optimizer selection where db does not support pooled sequences.");
            }

            DatabaseStructure = BuildDatabaseStructure(type, parms, dialect, forceTableUse, sequenceName, initialValue, incrementSize);
            DatabaseStructure.Prepare(Optimizer);
        }
Beispiel #22
0
        public virtual void Configure(IDictionary <string, string> settings)
        {
            // Command timeout
            commandTimeout = PropertiesHelper.GetInt32(Environment.CommandTimeout, settings, -1);
            if (commandTimeout > -1 && log.IsInfoEnabled)
            {
                log.Info(string.Format("setting ADO.NET command timeout to {0} seconds", commandTimeout));
            }

            // Prepare SQL
            prepareSql = PropertiesHelper.GetBoolean(Environment.PrepareSql, settings, false);
            if (prepareSql && SupportsPreparingCommands)
            {
                log.Info("preparing SQL enabled");
            }
        }
Beispiel #23
0
        public void AddAssembly(string assemblyName)
        {
            log.Info("Searching for mapped documents in assembly: " + assemblyName);

            Assembly assembly;

            try
            {
                assembly = Assembly.Load(assemblyName);
            }
            catch (Exception e)
            {
                throw new ValidatorConfigurationException("Could not add assembly " + assemblyName, e);
            }

            AddAssembly(assembly);
        }
Beispiel #24
0
 void ChannelReadImpl(IChannelHandlerContext ctx, string msg)
 {
     if (msg.HasUpperChar())
     {
         Logger.Info("The message has upper chars.");
         ctx.WriteAsync("Your message has upper chars." + System.Environment.NewLine);
     }
 }
        private async Task <TResponse> SendRequest <TResponse>(HttpMethod method, string endpoint, object payload = null)
            where TResponse : class, new()
        {
            var jsonContent = payload != null?payload.ToHttpContent() : null;

            var requestMessage = new HttpRequestMessage(method, endpoint)
            {
                Content = jsonContent
            };

            _logger.Info(() => string.Concat(
                             "Request",
                             Environment.NewLine,
                             requestMessage,
                             Environment.NewLine,
                             payload != null ? JsonForCastle.SerializeObject(payload) : ""
                             ));

            try
            {
                var response = await _httpClient.SendAsync(requestMessage);

                var content = response.Content != null ? await response.Content.ReadAsStringAsync() : "";

                _logger.Info(() => string.Concat(
                                 "Response",
                                 Environment.NewLine,
                                 response,
                                 Environment.NewLine,
                                 content
                                 ));

                if (response.IsSuccessStatusCode)
                {
                    return(JsonForCastle.DeserializeObject <TResponse>(content));
                }

                throw await response.ToCastleException(requestMessage.RequestUri.AbsoluteUri);
            }
            catch (OperationCanceledException)
            {
                throw new CastleTimeoutException(
                          requestMessage.RequestUri.AbsoluteUri,
                          (int)_httpClient.Timeout.TotalMilliseconds);
            }
        }
Beispiel #26
0
        public UpdateTimestampsCache(Settings settings, IDictionary <string, string> props)
        {
            string prefix = settings.CacheRegionPrefix;

            regionName = prefix == null ? regionName : prefix + '.' + regionName;
            log.Info("starting update timestamps cache at region: " + regionName);
            updateTimestamps = settings.CacheProvider.BuildCache(regionName, props);
        }
Beispiel #27
0
        /// <summary>
        /// Start the Dme Tcp Server.
        /// </summary>
        public virtual async void Start()
        {
            //
            _bossGroup    = new MultithreadEventLoopGroup(1);
            _workerGroup  = new MultithreadEventLoopGroup();
            _scertHandler = new ScertServerHandler();

            // Add client on connect
            _scertHandler.OnChannelActive += (channel) =>
            {
                string key = channel.Id.AsLongText();
                _channelDatas.TryAdd(key, new ChannelData());
            };

            // Remove client on disconnect
            _scertHandler.OnChannelInactive += (channel) =>
            {
                string key = channel.Id.AsLongText();
                _channelDatas.TryRemove(key, out var data);
            };

            // Queue all incoming messages
            _scertHandler.OnChannelMessage += (channel, message) =>
            {
                string key = channel.Id.AsLongText();
                if (_channelDatas.TryGetValue(key, out var data))
                {
                    data.RecvQueue.Enqueue(message);
                }

                // Log if id is set
                if (message.CanLog())
                {
                    Logger.Info($"TCP RECV {channel}: {message}");
                }
            };

            var bootstrap = new ServerBootstrap();

            bootstrap
            .Group(_bossGroup, _workerGroup)
            .Channel <TcpServerSocketChannel>()
            .Option(ChannelOption.SoBacklog, 100)
            .Handler(new LoggingHandler(LogLevel.INFO))
            .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;

                pipeline.AddLast(new WriteTimeoutHandler(15));
                pipeline.AddLast(new ScertEncoder());
                pipeline.AddLast(new ScertIEnumerableEncoder());
                pipeline.AddLast(new ScertTcpFrameDecoder(DotNetty.Buffers.ByteOrder.LittleEndian, 1024, 1, 2, 0, 0, false));
                pipeline.AddLast(new ScertDecoder(_sessionCipher, AuthKey));
                pipeline.AddLast(_scertHandler);
            }));

            _boundChannel = await bootstrap.BindAsync(Port);
        }
Beispiel #28
0
        /// <summary>
        /// Cascade an action from the parent entity instance to all its children.  This
        /// form is typicaly called from within cascade actions.
        /// </summary>
        /// <param name="persister">The parent's entity persister </param>
        /// <param name="parent">The parent reference. </param>
        /// <param name="anything">
        /// Typically some form of cascade-local cache
        /// which is specific to each CascadingAction type
        /// </param>
        public void CascadeOn(IEntityPersister persister, object parent, object anything)
        {
            if (persister.HasCascades || action.RequiresNoCascadeChecking)
            {
                log.Info("processing cascade " + action + " for: " + persister.EntityName);

                IType[]        types         = persister.PropertyTypes;
                CascadeStyle[] cascadeStyles = persister.PropertyCascadeStyles;
                EntityMode     entityMode    = eventSource.EntityMode;
                bool           hasUninitializedLazyProperties = persister.HasUninitializedLazyProperties(parent, entityMode);
                for (int i = 0; i < types.Length; i++)
                {
                    CascadeStyle style = cascadeStyles[i];
                    if (hasUninitializedLazyProperties && persister.PropertyLaziness[i] && !action.PerformOnLazyProperty)
                    {
                        //do nothing to avoid a lazy property initialization
                        continue;
                    }

                    if (style.DoCascade(action))
                    {
                        CascadeProperty(parent, persister.GetPropertyValue(parent, i, entityMode), types[i], style, anything, false);
                    }
                    else if (action.RequiresNoCascadeChecking)
                    {
                        action.NoCascade(eventSource, persister.GetPropertyValue(parent, i, entityMode), parent, persister, i);
                    }
                }

                log.Info("done processing cascade " + action + " for: " + persister.EntityName);
            }
        }
Beispiel #29
0
        public PocoInstantiator(Mapping.Component component, IInstantiationOptimizer optimizer)
        {
            mappedClass    = component.ComponentClass;
            this.optimizer = optimizer;

            proxyInterface     = null;
            embeddedIdentifier = false;

            try
            {
                constructor = ReflectHelper.GetDefaultConstructor(mappedClass);
            }
            catch (PropertyNotFoundException)
            {
                log.Info(string.Format("no default (no-argument) constructor for class: {0} (class must be instantiated by Interceptor)", mappedClass.FullName));
                constructor = null;
            }
        }
Beispiel #30
0
        public void HandlePropertyBeingDereferenced(IType propertySource, string propertyName)
        {
            if (QueryableCollection != null && CollectionProperties.IsCollectionProperty(propertyName))
            {
                // propertyName refers to something like collection.size...
                return;
            }
            if (propertySource.IsComponentType)
            {
                // property name is a sub-path of a component...
                return;
            }

            IQueryable persister = Queryable;

            if (persister != null)
            {
                try
                {
                    Declarer propertyDeclarer = persister.GetSubclassPropertyDeclarer(propertyName);

                    if (Log.IsInfoEnabled)
                    {
                        Log.Info("handling property dereference [" + persister.EntityName + " (" + ClassAlias + ") -> " + propertyName + " (" + propertyDeclarer + ")]");
                    }
                    if (propertyDeclarer == Declarer.SubClass)
                    {
                        _dereferencedBySubclassProperty = true;
                        _includeSubclasses = true;
                    }
                    else if (propertyDeclarer == Declarer.SuperClass)
                    {
                        _dereferencedBySuperclassProperty = true;
                    }
                }
                catch (QueryException)
                {
                    // ignore it; the incoming property could not be found so we
                    // cannot be sure what to do here.  At the very least, the
                    // safest is to simply not apply any dereference toggling...
                }
            }
        }
Beispiel #31
0
 static RedisProvider()
 {
     Log = LoggerProvider.LoggerFor(typeof (RedisProvider));
     Config = ConfigurationManager.GetSection("redis") as RedisConfig;
     if (Config == null)
     {
         Log.Info("redis configuration section not found, using default configuration (127.0.0.1:6379).");
         Config = new RedisConfig("localhost",6379);
     }
 }
 static CouchbaseCacheProvider()
 {
     log = LoggerProvider.LoggerFor(typeof (CouchbaseCacheProvider));
     config = ConfigurationManager.GetSection("couchbase") as ICouchbaseClientConfiguration;
     if (config == null)
     {
         log.Info("couchbase configuration section not found, using default configuration (127.0.0.1:8091).");
         config = new CouchbaseClientConfiguration();
         config.Urls.Add(new UriBuilder("http://", IPAddress.Loopback.ToString(),8091, "pools").Uri);
     }
 }
 static MemCacheProvider()
 {
     log = LoggerProvider.LoggerFor(typeof (MemCacheProvider));
     config = ConfigurationManager.GetSection("enyim.com/memcached") as IMemcachedClientConfiguration;
     if (config == null)
     {
         log.Info("enyim.com/memcached configuration section not found, using default configuration (127.0.0.1:11211).");
         config = new MemcachedClientConfiguration();
         config.Servers.Add(new IPEndPoint(IPAddress.Loopback, 11211));
     }
 }