Exemple #1
0
        private void LogPropertyAccessorsErrors(PersistentClass persistentClass)
        {
            if (proxyValidator == null)
            {
                return;
            }

            // This method work when Environment.UseProxyValidator is off
            System.Type clazz = persistentClass.MappedClass;
            foreach (Mapping.Property property in persistentClass.PropertyIterator)
            {
                MethodInfo method = property.GetGetter(clazz).Method;
                if (!proxyValidator.IsProxeable(method))
                {
                    log.Error(
                        string.Format("Getters of lazy classes cannot be final: {0}.{1}", persistentClass.MappedClass.FullName,
                                      property.Name));
                }
                method = property.GetSetter(clazz).Method;
                if (!proxyValidator.IsProxeable(method))
                {
                    log.Error(
                        string.Format("Setters of lazy classes cannot be final: {0}.{1}", persistentClass.MappedClass.FullName,
                                      property.Name));
                }
            }
        }
Exemple #2
0
        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();
            }
        }
        public int ExecuteNonQuery(IDbCommand cmd)
        {
            CheckReaders();
            LogCommand(cmd);
            Prepare(cmd);
            Stopwatch duration = null;

            if (Log.IsDebugEnabled)
            {
                duration = Stopwatch.StartNew();
            }
            try
            {
                return(cmd.ExecuteNonQuery());
            }
            catch (Exception e)
            {
                e.Data["actual-sql-query"] = cmd.CommandText;
                Log.Error("Could not execute command: " + cmd.CommandText, e);
                throw;
            }
            finally
            {
                if (Log.IsDebugEnabled && duration != null)
                {
                    Log.DebugFormat("ExecuteNonQuery took {0} ms", duration.ElapsedMilliseconds);
                }
            }
        }
Exemple #4
0
        /// <summary></summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Put(object key, object value)
        {
            if (key == null)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("null key passed to 'Put'");
                }
                throw new ArgumentNullException("key", "null key not allowed");
            }
            if (value == null)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("null value passed to 'Put'");
                }
                throw new ArgumentNullException("value", "null value not allowed");
            }
            string cacheKey = GetCacheKey(key);

            if (log.IsDebugEnabled)
            {
                log.Debug(String.Format("setting value {1} for key {0}", cacheKey, value));
            }
            system.Add(cacheKey, new DictionaryEntry(key, value));
        }
Exemple #5
0
        private void ValidateLogoutViaPost(System.Collections.Specialized.NameValueCollection requestParams, out string message, out LogoutResponse response)
        {
            var parser = new HttpPostBindingParser(requestParams);

            logger.DebugFormat(TraceMessages.LogoutResponsePostBindingParse, parser.Message);

            response = Serialization.DeserializeFromXmlString <LogoutResponse>(parser.Message);

            var idp = IdpSelectionUtil.RetrieveIDPConfiguration(response.Issuer.Value, config);

            if (idp.Metadata == null)
            {
                logger.ErrorFormat(ErrorMessages.UnknownIdentityProvider, idp.Id);
                throw new Saml20Exception(string.Format(ErrorMessages.UnknownIdentityProvider, idp.Id));
            }

            if (!parser.IsSigned)
            {
                logger.Error(ErrorMessages.ResponseSignatureMissing);
                throw new Saml20Exception(ErrorMessages.ResponseSignatureMissing);
            }

            // signature on final message in logout
            if (!parser.CheckSignature(idp.Metadata.Keys))
            {
                logger.Error(ErrorMessages.ResponseSignatureInvalid);
                throw new Saml20Exception(ErrorMessages.ResponseSignatureInvalid);
            }

            message = parser.Message;
        }
        public ActionResult Create(string entityName, FormCollection collection)
        {
            var entity = _admin.GetEntity(entityName);

            if (entity == null)
            {
                return(RedirectToAction("NotFound", new { entityName }));
            }

            try
            {
                var savedId = _entityService.Create(entity, collection, Request.Files);
                if (savedId != null)
                {
                    _notificator.Success(IlaroAdminResources.AddSuccess, entity.Verbose.Singular);

                    return(SaveOrUpdateSucceed(entityName, savedId));
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                _notificator.Error(ex.Message);
            }

            var model = new EntityCreateModel
            {
                Entity           = entity,
                PropertiesGroups = _entityService.PrepareGroups(entity.CreateRecord(collection, Request.Files))
            };

            return(View(model));
        }
Exemple #7
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);
        }
		private static TimeSpan GetExpiration(IDictionary<string, string> props)
		{
			TimeSpan result = DefaultExpiration;
			string expirationString;
			if (!props.TryGetValue("expiration", out expirationString))
			{
				props.TryGetValue(Cfg.Environment.CacheDefaultExpiration, out expirationString);
			}

			if (expirationString != null)
			{
				try
				{
					int seconds = Convert.ToInt32(expirationString);
					result = TimeSpan.FromSeconds(seconds);
					log.Debug("new expiration value: " + seconds);
				}
				catch (Exception ex)
				{
					log.Error("error parsing expiration value");
					throw new ArgumentException("could not parse 'expiration' as a number of seconds", ex);
				}
			}
			else
			{
				if (log.IsDebugEnabled)
				{
					log.Debug("no expiration value given, using defaults");
				}
			}
			return result;
		}
Exemple #9
0
        public void Execute(Action <string> scriptAction, bool execute, bool justDrop, IDbConnection connection,
                            TextWriter exportOutput)
        {
            Initialize();
            IDbCommand statement = null;

            if (execute && connection == null)
            {
                throw new ArgumentNullException("connection", "When export is set to true, you need to pass a non null connection");
            }
            if (execute)
            {
                statement = connection.CreateCommand();
            }

            try
            {
                for (int i = 0; i < dropSQL.Length; i++)
                {
                    Execute(scriptAction, execute, false, exportOutput, statement, dropSQL[i]);
                }

                if (!justDrop)
                {
                    for (int j = 0; j < createSQL.Length; j++)
                    {
                        Execute(scriptAction, execute, true, exportOutput, statement, createSQL[j]);
                    }
                }
            }
            finally
            {
                try
                {
                    if (statement != null)
                    {
                        statement.Dispose();
                    }
                }
                catch (Exception e)
                {
                    log.Error("Could not close connection: " + e.Message, e);
                }
                if (exportOutput != null)
                {
                    try
                    {
                        exportOutput.Close();
                    }
                    catch (Exception ioe)
                    {
                        log.Error("Error closing output file " + outputFile + ": " + ioe.Message, ioe);
                    }
                }
            }
        }
Exemple #10
0
        public async Task Start()
        {
            _group        = new MultithreadEventLoopGroup();
            _scertHandler = new ScertServerHandler();

            TimeLostConnection = null;

            // Add client on connect
            _scertHandler.OnChannelActive += (channel) =>
            {
            };

            // Remove client on disconnect
            _scertHandler.OnChannelInactive += async(channel) =>
            {
                Logger.Error($"Lost connection to MPS");
                TimeLostConnection = DateTime.UtcNow;
                await Stop();
            };

            // Queue all incoming messages
            _scertHandler.OnChannelMessage += (channel, message) =>
            {
                // Add to queue
                _mpsRecvQueue.Enqueue(message);

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

            _bootstrap = new Bootstrap();
            _bootstrap
            .Group(_group)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;

                pipeline.AddLast(new ScertEncoder());
                pipeline.AddLast(new ScertIEnumerableEncoder());
                pipeline.AddLast(new ScertTcpFrameDecoder(DotNetty.Buffers.ByteOrder.LittleEndian, Constants.MEDIUS_MESSAGE_MAXLEN, 1, 2, 0, 0, false));
                pipeline.AddLast(new ScertDecoder(_sessionCipher, _serverKey));
                pipeline.AddLast(_scertHandler);
            }));

            await ConnectMPS();
        }
Exemple #11
0
        private async Task Tick(IChannel clientChannel)
        {
            if (clientChannel == null)
            {
                return;
            }

            //
            List <BaseScertMessage> responses = new List <BaseScertMessage>();
            string key = clientChannel.Id.AsLongText();

            try
            {
                //
                if (_channelDatas.TryGetValue(key, out var data))
                {
                    // Process all messages in queue
                    while (data.RecvQueue.TryDequeue(out var message))
                    {
                        try
                        {
                            await ProcessMessage(message, clientChannel, data);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                        }
                    }

                    // Send if writeable
                    if (clientChannel.IsWritable)
                    {
                        // Add send queue to responses
                        while (data.SendQueue.TryDequeue(out var message))
                        {
                            responses.Add(message);
                        }

                        //
                        if (responses.Count > 0)
                        {
                            await clientChannel.WriteAndFlushAsync(responses);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }
        }
Exemple #12
0
        /// <summary>
        /// Deserializes an assertion, verifies its signature and logs in the user if the assertion is valid.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="elem">The elem.</param>
        public static Saml20Assertion HandleAssertion(XmlElement elem, Saml2Configuration config, Func <string, object> getFromCache, Action <string, object, DateTime> setInCache)
        {
            logger.DebugFormat(TraceMessages.AssertionProcessing, elem.OuterXml);

            var issuer = GetIssuer(elem);
            var endp   = IdpSelectionUtil.RetrieveIDPConfiguration(issuer, config);

            PreHandleAssertion(elem, endp);

            if (endp == null || endp.Metadata == null)
            {
                logger.Error(ErrorMessages.AssertionIdentityProviderUnknown);
                throw new Saml20Exception(ErrorMessages.AssertionIdentityProviderUnknown);
            }

            var quirksMode = endp.QuirksMode;
            var assertion  = new Saml20Assertion(elem, null, quirksMode, config);

            // Check signatures
            if (!endp.OmitAssertionSignatureCheck)
            {
                var keys = endp.Metadata.GetKeys(KeyTypes.Signing);
                if (keys == null || !keys.Any())
                {
                    keys = endp.Metadata.GetKeys(KeyTypes.Encryption);
                }
                var trusted = GetTrustedSigners(keys, endp);
                if (!assertion.CheckSignature(trusted))
                {
                    logger.Error(ErrorMessages.AssertionSignatureInvalid);
                    throw new Saml20Exception(ErrorMessages.AssertionSignatureInvalid);
                }
            }

            // Check expiration
            if (assertion.IsExpired)
            {
                logger.Error(ErrorMessages.AssertionExpired);
                throw new Saml20Exception(ErrorMessages.AssertionExpired);
            }

            // Check one time use
            if (assertion.IsOneTimeUse)
            {
                if (getFromCache(assertion.Id) != null)
                {
                    logger.Error(ErrorMessages.AssertionOneTimeUseExceeded);
                    throw new Saml20Exception(ErrorMessages.AssertionOneTimeUseExceeded);
                }

                setInCache(assertion.Id, string.Empty, assertion.NotOnOrAfter);
            }

            logger.DebugFormat(TraceMessages.AssertionParsed, assertion.Id);
            return(assertion);
        }
Exemple #13
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("--"))
                    {
                        //if (args[i].StartsWith("--properties="))
                        //{
                        //  propFile = args[i].Substring(13);
                        //}
                        //else
                        if (args[i].StartsWith("--config="))
                        {
                            cfg.Configure(args[i].Substring(9));
                        }
                        else if (args[i].StartsWith("--naming="))
                        {
                            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("Error running schema update", e);
                Console.WriteLine(e);
            }
        }
Exemple #14
0
        public async Task Tick()
        {
            if (_boundChannel == null || !_boundChannel.Active)
            {
                return;
            }

            //
            List <ScertDatagramPacket> responses = new List <ScertDatagramPacket>();

            try
            {
                // Process all messages in queue
                while (_recvQueue.TryDequeue(out var message))
                {
                    try
                    {
                        ProcessMessage(message);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e);
                    }
                }

                // Send if writeable
                if (_boundChannel.IsWritable)
                {
                    // Add send queue to responses
                    while (_sendQueue.TryDequeue(out var message))
                    {
                        responses.Add(message);
                    }

                    //
                    if (responses.Count > 0)
                    {
                        if (responses.Count > 2)
                        {
                        }
                        await _boundChannel.WriteAndFlushAsync(responses);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }
        }
        public void TestFixtureSetUp()
        {
            try
            {
                Configure();

                CreateSchema();
                BuildSessionFactory();
            }
            catch (System.Exception e)
            {
                log.Error("Error while setting up the test fixture", e);
                throw;
            }
        }
Exemple #16
0
 public override async void ChannelInactive(IChannelHandlerContext ctx)
 {
     if (!_normalShutdown && _streamName != null && _tag == RtmpTag.Publisher)
     {
         var stream = _mediaStreamDic.GetValueOrDefault(_streamName);
         if (stream != null)
         {
             await stream.SendEofToAllSubscriberAndClose();
         }
         else
         {
             logger.Error($"stream:{nameof(_streamName)} is null");
         }
     }
 }
Exemple #17
0
 /// <summary>
 /// Generate an <see cref="Int16"/>, <see cref="Int32"/>, or <see cref="Int64"/>
 /// for the identifier by using a database sequence.
 /// </summary>
 /// <param name="session">The <see cref="ISessionImplementor"/> this id is being generated in.</param>
 /// <param name="obj">The entity for which the id is being generated.</param>
 /// <returns>The new identifier as a <see cref="Int16"/>, <see cref="Int32"/>, or <see cref="Int64"/>.</returns>
 public virtual object Generate(ISessionImplementor session, object obj)
 {
     try
     {
         var          cmd    = session.Batcher.PrepareCommand(CommandType.Text, sql, SqlTypeFactory.NoTypes);
         DbDataReader reader = null;
         try
         {
             reader = session.Batcher.ExecuteReader(cmd);
             try
             {
                 reader.Read();
                 object result = IdentifierGeneratorFactory.Get(reader, identifierType, session);
                 if (log.IsDebugEnabled)
                 {
                     log.Debug("Sequence identifier generated: " + result);
                 }
                 return(result);
             }
             finally
             {
                 reader.Close();
             }
         }
         finally
         {
             session.Batcher.CloseCommand(cmd, reader);
         }
     }
     catch (DbException sqle)
     {
         log.Error("error generating sequence", sqle);
         throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "could not get next sequence value");
     }
 }
Exemple #18
0
        /// <summary>
        /// Execute all SQL and second-level cache updates, in a
        /// special order so that foreign-key constraints cannot
        /// be violated:
        /// <list type="bullet">
        /// <item> <description>Inserts, in the order they were performed</description> </item>
        /// <item> <description>Updates</description> </item>
        /// <item> <description>Deletion of collection elements</description> </item>
        /// <item> <description>Insertion of collection elements</description> </item>
        /// <item> <description>Deletes, in the order they were performed</description> </item>
        /// </list>
        /// </summary>
        protected virtual void PerformExecutions(IEventSource session)
        {
            if (log.IsDebugEnabled)
            {
                log.Debug("executing flush");
            }

            try
            {
                session.ConnectionManager.FlushBeginning();
                // we need to lock the collection caches before
                // executing entity inserts/updates in order to
                // account for bidi associations
                session.ActionQueue.PrepareActions();
                session.ActionQueue.ExecuteActions();
            }
            catch (HibernateException he)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Could not synchronize database state with session", he);
                }
                throw;
            }
            finally
            {
                session.ConnectionManager.FlushEnding();
            }
        }
Exemple #19
0
        public bool Validate(Entity entity)
        {
            var instance = entity.CreateIntance();
            var context  = new ValidationContext(instance);
            var isValid  = true;

            foreach (var property in entity.Properties)
            {
                if (property.TypeInfo.IsFile)
                {
                    var result = _fileValidator.Validate(property);
                    if (result == false)
                    {
                        isValid = false;
                    }
                }
                foreach (var validator in property.ValidationAttributes)
                {
                    try
                    {
                        validator.Validate(property.Value.Raw, context);
                    }
                    catch (ValidationException ex)
                    {
                        isValid = false;
                        _notificator.AddModelError(property.Name, ex.Message);
                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex);
                    }
                }
            }
            return(isValid);
        }
        /// <summary>
        /// Execute all SQL and second-level cache updates, in a
        /// special order so that foreign-key constraints cannot
        /// be violated:
        /// <list type="bullet">
        /// <item> <description>Inserts, in the order they were performed</description> </item>
        /// <item> <description>Updates</description> </item>
        /// <item> <description>Deletion of collection elements</description> </item>
        /// <item> <description>Insertion of collection elements</description> </item>
        /// <item> <description>Deletes, in the order they were performed</description> </item>
        /// </list>
        /// </summary>
        /// <param name="session">The session being flushed</param>
        protected virtual void PerformExecutions(IEventSource session)
        {
            if (log.IsDebugEnabled)
            {
                log.Debug("executing flush");
            }

            try
            {
                session.ConnectionManager.FlushBeginning();
                // IMPL NOTE : here we alter the flushing flag of the persistence context to allow
                //		during-flush callbacks more leniency in regards to initializing proxies and
                //		lazy collections during their processing.
                // For more information, see HHH-2763 / NH-1882
                session.PersistenceContext.Flushing = true;
                // we need to lock the collection caches before
                // executing entity inserts/updates in order to
                // account for bidi associations
                session.ActionQueue.PrepareActions();
                session.ActionQueue.ExecuteActions();
            }
            catch (HibernateException he)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Could not synchronize database state with session", he);
                }
                throw;
            }
            finally
            {
                session.PersistenceContext.Flushing = false;
                session.ConnectionManager.FlushEnding();
            }
        }
Exemple #21
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);
            });
        }
Exemple #22
0
        public override INHibernateProxy GetProxy(object id, ISessionImplementor session)
        {
            try
            {
                var initializer = new CastleLazyInitializer(this.EntityName, this.PersistentClass, id, this.GetIdentifierMethod, this.SetIdentifierMethod, this.ComponentIdType, session);

                object generatedProxy;

                if (this.IsClassProxy)
                {
                    generatedProxy = ProxyGenerator.CreateClassProxy(this.PersistentClass, this.Interfaces, initializer);
                }
                else
                {
                    generatedProxy = ProxyGenerator.CreateInterfaceProxyWithoutTarget(this.Interfaces[0], this.Interfaces, initializer);
                }

                initializer.SetConstructed();

                return((INHibernateProxy)generatedProxy);
            }
            catch (Exception e)
            {
                Log.Error("Creating a proxy instance failed", e);

                throw new HibernateException("Creating a proxy instance failed", e);
            }
        }
        public object ExecuteWithChanges(
            DbCommand cmd,
            string entityName,
            EntityChangeType changeType,
            Func <string> changeDescriber = null)
        {
            _log.DebugFormat("Executing command: \r\n {0}", cmd.CommandText);
            object result;

            using (var conn = DB.OpenConnection())
                using (var tx = conn.BeginTransaction())
                {
                    try
                    {
                        cmd.Connection  = conn;
                        cmd.Transaction = tx;
                        result          = cmd.ExecuteScalar();

                        if (result != null)
                        {
                            if (Admin.IsChangesEnabled)
                            {
                                var changeCmd = CreateChangeCommand(entityName, changeType, result.ToString(), changeDescriber);
                                _log.DebugFormat("Executing change command: \r\n {0}", changeCmd.CommandText);
                                changeCmd.Connection  = conn;
                                changeCmd.Transaction = tx;
                                changeCmd.ExecuteNonQuery();
                            }

                            _log.Debug("Commit transaction");
                            tx.Commit();
                        }
                        else
                        {
                            Rollback(tx);
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex);
                        Rollback(tx);
                        throw;
                    }
                }

            return(result);
        }
Exemple #24
0
        public static void BuggyImplementation(this IInternalLogger logger, SingleThreadEventExecutor eventExecutor)
        {
            var type = eventExecutor.GetType();

            logger.Error(
                $"Buggy {type.Name} implementation; {type.Name}.ConfirmShutdown() must be called "
                + "before run() implementation terminates.");
        }
 private void NotifyLocalSynchsBeforeTransactionCompletion()
 {
     if (synchronizations != null)
     {
         for (int i = 0; i < synchronizations.Count; i++)
         {
             ISynchronization sync = synchronizations[i];
             try
             {
                 sync.BeforeCompletion();
             }
             catch (Exception e)
             {
                 Log.Error("exception calling user Synchronization", e);
             }
         }
     }
 }
        /// <summary>
        /// Returns a <see cref="System.Type"/> from an already loaded Assembly or an
        /// Assembly that is loaded with a partial name.
        /// </summary>
        /// <param name="name">An <see cref="AssemblyQualifiedTypeName" />.</param>
        /// <param name="throwOnError"><see langword="true" /> if an exception should be thrown
        /// in case of an error, <see langword="false" /> otherwise.</param>
        /// <returns>
        /// A <see cref="System.Type"/> object that represents the specified type,
        /// or <see langword="null" /> if the type cannot be loaded.
        /// </returns>
        /// <remarks>
        /// Attempts to get a reference to the type from an already loaded assembly.  If the
        /// type cannot be found then the assembly is loaded using
        /// <see cref="Assembly.Load(string)" />.
        /// </remarks>
        public static System.Type TypeFromAssembly(AssemblyQualifiedTypeName name, bool throwOnError)
        {
            try
            {
                // Try to get the type from an already loaded assembly
                System.Type type = System.Type.GetType(name.ToString());

                if (type != null)
                {
                    return(type);
                }

                if (name.Assembly == null)
                {
                    // No assembly was specified for the type, so just fail
                    string message = "Could not load type " + name + ". Possible cause: no assembly name specified.";
                    log.Warn(message);
                    if (throwOnError)
                    {
                        throw new TypeLoadException(message);
                    }
                    return(null);
                }

                Assembly assembly = Assembly.Load(name.Assembly);

                if (assembly == null)
                {
                    log.Warn("Could not load type " + name + ". Possible cause: incorrect assembly name specified.");
                    return(null);
                }

                type = assembly.GetType(name.Type, throwOnError);

                if (type == null)
                {
                    log.Warn("Could not load type " + name + ".");
                    return(null);
                }

                return(type);
            }
            catch (Exception e)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Could not load type " + name + ".", e);
                }
                if (throwOnError)
                {
                    throw;
                }
                return(null);
            }
        }
Exemple #27
0
        private async Task Tick(IChannel clientChannel)
        {
            if (clientChannel == null)
            {
                return;
            }

            //
            string key = clientChannel.Id.AsLongText();

            try
            {
                //
                if (_channelDatas.TryGetValue(key, out var data))
                {
                    // Disconnect on destroy
                    if (data.ClientObject != null && data.ClientObject.IsDestroyed)
                    {
                        await DisconnectClient(clientChannel);

                        return;
                    }

                    // Process all messages in queue
                    while (data.RecvQueue.TryDequeue(out var message))
                    {
                        try
                        {
                            await ProcessMessage(message, clientChannel, data);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }
        }
Exemple #28
0
        public void OnEvent(PluginEvent eventType, object data)
        {
            if (!_pluginCallbackInstances.ContainsKey(eventType))
            {
                return;
            }

            foreach (var callbacks in _pluginCallbackInstances[eventType])
            {
                try
                {
                    _engine.Operations.Invoke(callbacks, eventType, data);
                }
                catch (Exception e)
                {
                    Logger.Error($"PLUGIN OnEvent Exception. {callbacks}({eventType}, {data})");
                    Logger.Error(_engine.GetService <ExceptionOperations>().FormatException(e));
                }
            }
        }
Exemple #29
0
        private void BuildDocumentFields(Object instance, Document doc, DocumentMapping classMapping, string prefix)
        {
            if (instance == null)
            {
                return;
            }

            object unproxiedInstance = Unproxy(instance);

            foreach (var bridge in classMapping.ClassBridges)
            {
                var bridgeName = prefix + bridge.Name;
                try
                {
                    bridge.Bridge.Set(
                        bridgeName,
                        unproxiedInstance,
                        doc,
                        GetStore(bridge.Store),
                        GetIndex(bridge.Index),
                        bridge.Boost
                        );
                }
                catch (Exception e)
                {
                    logger.Error(
                        string.Format(CultureInfo.InvariantCulture, "Error processing class bridge for {0}",
                                      bridgeName), e);
                }
            }

            foreach (var field in classMapping.Fields)
            {
                BuildDocumentField(field, unproxiedInstance, doc, prefix);
            }

            foreach (var embedded in classMapping.Embedded)
            {
                BuildDocumentFieldsForEmbedded(embedded, unproxiedInstance, doc, prefix);
            }
        }
Exemple #30
0
        /// <summary>
        /// Performs the attribute query and adds the resulting attributes to <c>Saml20Identity.Current</c>.
        /// </summary>
        /// <param name="context">The http context.</param>
        public void PerformQuery(HttpContext context)
        {
            var config = Saml2Config.GetConfig();

            var endpointId = StateService.Get <string>(Saml20AbstractEndpointHandler.IdpLoginSessionKey);

            if (string.IsNullOrEmpty(endpointId))
            {
                Logger.Error(ErrorMessages.AttrQueryNoLogin);
                throw new InvalidOperationException(ErrorMessages.AttrQueryNoLogin);
            }

            var ep = config.IdentityProviders.FirstOrDefault(x => x.Id == endpointId);

            if (ep == null)
            {
                throw new Saml20Exception(string.Format(ErrorMessages.UnknownIdentityProvider, endpointId));
            }

            PerformQuery(context, ep);
        }