Example #1
0
        public bool ImportTable(ImportTableArgs arg)
        {
            using( ConnectionScope scope = new ConnectionScope(TransactionMode.Required) ) {
                foreach( string tableName in arg.TableNames ) {

                    var parameter = new {
                        SrcProviderGUID = new Guid(arg.SrcProvider),
                        DestProviderGUID = new Guid(arg.DestProvider),
                        TableName = tableName
                    };

                    CPQuery.From("DELETE FROM esb_DbDistribute WHERE SrcProviderGUID=@SrcProviderGUID AND DestProviderGUID = @DestProviderGUID AND TableName = @TableName", parameter).ExecuteNonQuery();

                    EsbDbDistribute db = new EsbDbDistribute();
                    db.DbDistributeGUID = Guid.NewGuid();
                    db.DestProviderGUID = new Guid(arg.DestProvider);
                    db.SrcProviderGUID = new Guid(arg.SrcProvider);
                    db.TableName = tableName;
                    db.Status = "未同步";

                    db.Insert();
                }

                scope.Commit();
            }
            return true;
        }
Example #2
0
        public XmlResult AddUsers(string userList)
        {
            string returnMessage = string.Empty;
            try
            {
                IList<EsbUsers> esbUsersEntityList = XmlDataEntity.ConvertXmlToList<EsbUsers>(userList);

                using (ConnectionScope scope = new ConnectionScope(TransactionMode.Required))
                {
                    foreach (EsbUsers user in esbUsersEntityList)
                    {
                        if (EntityCommon.IsExistData("Esb_Users", "UserID", user.UserID.ToString()))
                        {
                            user.Delete();
                        }
                        user.Insert();
                    }

                    scope.Commit();
                }
            }
            catch(Exception ex)
            {
                returnMessage = "添加用户失败!";
            }

            return new XmlResult(returnMessage);
        }
Example #3
0
        public JsonResult SavePipe(EsbReceiverInterface pipe)
        {
            HttpResult hr = new HttpResult() { Result = true };

            using (ConnectionScope scope = new ConnectionScope(TransactionMode.Required)){
                if (pipe.ReceiverInterfaceID == Guid.Empty){
                    if (EntityCommon.IsExistData("Esb_ReceiverInterface", "ServiceName", pipe.ServiceName)){
                        hr.Result = false;
                        hr.ErrorMessage = "英文名称不允许重复,请重新录入英文名称!";
                        return new JsonResult(hr);
                    }
                    pipe.ReceiverInterfaceID = Guid.NewGuid();
                    pipe.Status = 1;
                    pipe.CreatedOn = DateTime.Now;
                    pipe.Insert();

                    //自动生成策略
                    EsbDistributeStrategy esbDistributeStrategyEntity = new EsbDistributeStrategy();
                    esbDistributeStrategyEntity.DistributeStrategyID = Guid.NewGuid();
                    esbDistributeStrategyEntity.ReceiverInterfaceID = pipe.ReceiverInterfaceID;
                    esbDistributeStrategyEntity.CreatedOn = DateTime.Now;
                    esbDistributeStrategyEntity.Status = 1;
                    esbDistributeStrategyEntity.Insert();
                }
                else{
                    pipe.ModifiedOn = DateTime.Now;
                    pipe.Update();
                }

                hr.KeyValue = pipe.ReceiverInterfaceID.ToString();
                scope.Commit();
            }
            return new JsonResult(hr);
        }
 protected virtual async Task<IDbAsyncConnection> OpenAsync(string connectionName)
 {
     ConnectionStringSettings setting = GetSetting(connectionName);
     string connectionString = setting.ConnectionString;
     var scope = new ConnectionScope(connectionString, () => Open(connectionString, setting));
     await scope.Initialize();
     return scope;
 }
        Task SendUsingNewConnection(IPipe<ConnectionContext> connectionPipe, ConnectionScope scope, CancellationToken cancellationToken)
        {
            try
            {
                if (_cacheTaskScope.StoppingToken.IsCancellationRequested)
                    throw new TaskCanceledException($"The connection is being disconnected: {_settings.ToDebugString()}");

                if (_log.IsDebugEnabled)
                    _log.DebugFormat("Connecting: {0}", _settings.ToDebugString());

                IConnection connection;
                if (_settings.ClusterMembers?.Any() ?? false)
                {
                    connection = _connectionFactory.CreateConnection(_settings.ClusterMembers, _settings.ClientProvidedName);
                }
                else
                {
                    var hostNames = Enumerable.Repeat(_settings.Host, 1).ToList();

                    connection = _connectionFactory.CreateConnection(hostNames, _settings.ClientProvidedName);
                }


                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Connected: {0} (address: {1}, local: {2}", _settings.ToDebugString(),
                        connection.Endpoint, connection.LocalPort);
                }

                EventHandler<ShutdownEventArgs> connectionShutdown = null;
                connectionShutdown = (obj, reason) =>
                {
                    Interlocked.CompareExchange(ref _scope, null, scope);

                    scope.Shutdown(reason.ReplyText);

                    connection.ConnectionShutdown -= connectionShutdown;
                };

                connection.ConnectionShutdown += connectionShutdown;

                var connectionContext = new RabbitMqConnectionContext(connection, _settings, _cacheTaskScope);

                connectionContext.GetOrAddPayload(() => _settings);

                scope.Connected(connectionContext);
            }
            catch (BrokerUnreachableException ex)
            {
                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.ConnectFaulted(ex);

                throw new RabbitMqConnectionException("Connect failed: " + _settings.ToDebugString(), ex);
            }

            return SendUsingExistingConnection(connectionPipe, scope, cancellationToken);
        }
Example #6
0
        public IReadOnlySession OpenReadOnlySession(ConnectionScope connectionScope)
        {
            if (log.IsDebug)
            {
                log.Debug(LogMessages.SessionFactory_CreatingReadOnlySession, this.connectionName);
            }

            return new ReadOnlySession(connectionScope, this.sqlDialect, this.dbDriver);
        }
Example #7
0
        public ISession OpenSession(ConnectionScope connectionScope)
        {
            if (log.IsDebug)
            {
                log.Debug(LogMessages.SessionFactory_CreatingSession, this.connectionName);
            }

            return new Session(connectionScope, this.sqlDialect, this.dbDriver, Listener.Listeners);
        }
Example #8
0
        public IAsyncReadOnlySession OpenAsyncReadOnlySession(ConnectionScope connectionScope)
        {
            if (log.IsDebug)
            {
                log.Debug(LogMessages.SessionFactory_CreatingAsyncReadOnlySession, this.connectionName);
            }

            SqlCharacters.Current = this.sqlDialect.SqlCharacters;

            return new AsyncReadOnlySession(connectionScope, this.sqlDialect, this.dbDriver);
        }
Example #9
0
 public JsonResult DeleteInvoker(string[] invokerGUIDList)
 {
     HttpResult hr = new HttpResult() { Result = true };
     string keyList = string.Join("','", invokerGUIDList);
     using( ConnectionScope scope = new ConnectionScope(TransactionMode.Required) ) {
         CPQuery.From(String.Format("delete from esb_Invoker where InvokerID in ('{0}')",
                                     keyList)).ExecuteNonQuery();
         scope.Commit();
     }
     return new JsonResult(hr);
 }
Example #10
0
File: Add.cs Project: qiqi545/HQ
 public static IdentityBuilder AddDocumentDbIdentityStore <TUser, TRole, TTenant, TApplication>(
     this IdentityBuilder identityBuilder,
     string connectionString,
     ConnectionScope scope = ConnectionScope.ByRequest)
     where TUser : IdentityUserExtended <string>
     where TRole : IdentityRoleExtended <string>
     where TTenant : IdentityTenant <string>
     where TApplication : IdentityApplication <string>
 {
     return(identityBuilder.AddDocumentDbIdentityStore <string, TUser, TRole, TTenant, TApplication>(
                connectionString, scope));
 }
Example #11
0
        public void Probe(ProbeContext context)
        {
            ConnectionScope connectionScope = _scope;

            if (connectionScope != null)
            {
                context.Set(new
                {
                    Connected = true
                });
            }
        }
        public ConnectionScope BeginConnection()
        {
            var connection = CreateConnection();

            Open(connection);

            var connectionScope = new ConnectionScope(this, connection);

            _liveConnectionScopes.Add(connectionScope);

            return connectionScope;
        }
Example #13
0
        public Customer GetCustomerByNumber(string number)
        {
            using (var connectionScope = new ConnectionScope())
            {
                var where = new PredicateGroup {
                    Operator = GroupOperator.And, Predicates = new List <IPredicate>()
                };
                where.Predicates.Add(Predicates.Field <Customer>(f => f.Number, Operator.Eq, number));

                return(connectionScope.Connection.GetList <Customer>(where.Predicates.Any() ? where : null).FirstOrDefault());
            }
        }
Example #14
0
        public ConnectionScope BeginConnection()
        {
            var connection = CreateConnection();

            Open(connection);

            var connectionScope = new ConnectionScope(this, connection);

            _liveConnectionScopes.Add(connectionScope);

            return(connectionScope);
        }
Example #15
0
 public void LoadGlobalSettings()
 {
     using (ConnectionScope.Enter())
     {
         using (ConnectionScope.Enter())
         {
             Domain.AddressType.AddressTypes   = new LazyDictionary <int, Domain.AddressType>(this.GetAddressTypes);
             Domain.DocumentType.DocumentTypes = new LazyDictionary <int, Domain.DocumentType>(this.GetDocumentTypes);
             Domain.Country.Countries          = new LazyDictionary <int, Domain.Country>(this.GetCountries);
             Domain.State.States = new LazyDictionary <int, Domain.State>(this.GetStates);
             Domain.SubmissionType.SubmissionTypes         = new LazyDictionary <int, Domain.SubmissionType>(this.GetSubmissionTypes);
             Domain.DocumentClassifier.DocumentClassifiers = new LazyDictionary <int, Domain.DocumentClassifier>(this.GetDocumentClassifiers);
             Domain.DocumentFormat.DocumentFormats         = new LazyDictionary <int, Domain.DocumentFormat>(this.GetDocumentFormats);
             Domain.PhoneType.PhoneTypes            = new LazyDictionary <int, Domain.PhoneType>(this.GetPhoneTypes);
             Domain.EmailType.EmailTypes            = new LazyDictionary <int, Domain.EmailType>(this.GetEmailTypes);
             Domain.EmailFormat.EmailFormats        = new LazyDictionary <int, Domain.EmailFormat>(this.GetEmailFormats);
             Domain.GovIDType.GovIDTypes            = new LazyDictionary <int, Domain.GovIDType>(this.GetGovIDTypes);
             Domain.PartyType.PartyTypes            = new LazyDictionary <int, Domain.PartyType>(this.GetPartyTypes);
             Domain.ApprovalStatus.ApprovalStatuses = new LazyDictionary <int, Domain.ApprovalStatus>(this.GetApprovalStatuses);
             Domain.PricingUnit.PricingUnits        = new LazyDictionary <int, Domain.PricingUnit>(this.GetPricingUnits);
             Domain.Gender.Genders                                = new LazyDictionary <int, Domain.Gender>(this.GetGenders);
             Domain.SmokeStatus.SmokeStatuses                     = new LazyDictionary <int, Domain.SmokeStatus>(this.GetSmokeStatuses);
             Domain.ConfigurationSettings.Configuration           = new LazyDictionary <string, Domain.Configuration>(this.GetConfigurations);
             Domain.OrderType.OrderTypes                          = new LazyDictionary <int, Domain.OrderType>(this.GetOrderTypes);
             Domain.Language.Languages                            = new LazyDictionary <int, Domain.Language>(this.GetLanguages);
             Domain.CredentialingStatus.CredentialingStatuses     = new LazyDictionary <int, Domain.CredentialingStatus>(this.GetCredentialingStatus);
             Domain.PermissionType.PermissionTypes                = new LazyDictionary <int, Domain.PermissionType>(this.GetPermissionTypes);
             Domain.OrderStatus.OrderStatuses                     = new LazyDictionary <int, Domain.OrderStatus>(this.GetOrderStatus);
             Domain.OrderAssignmentStatus.OrderAssignmentStatuses = new LazyDictionary <int, Domain.OrderAssignmentStatus>(this.GetOrderAssignmentStatuses);
             Domain.EmployeeStatus.EmployeeStatuses               = new LazyDictionary <int, Domain.EmployeeStatus>(this.GetEmployeeStatus);
             Domain.EmployeeTitle.EmployeeTitles                  = new LazyDictionary <int, Domain.EmployeeTitle>(this.GetEmployeeTitles);
             Domain.PurchaseOrderStatus.PurchaseOrderStatuses     = new LazyDictionary <int, Domain.PurchaseOrderStatus>(this.GetPurchaseOrderStatuses);
             Domain.SaleOrderStatus.SaleOrderStatuses             = new LazyDictionary <int, Domain.SaleOrderStatus>(this.GetSaleOrderStatuses);
             Domain.ItemType.Type = new LazyDictionary <int, Domain.ItemType>(this.GetItemTypes);
             Domain.SupplyOrderStatus.OrderStatuses = new LazyDictionary <int, Domain.SupplyOrderStatus>(this.GetSupplyOrderStatuses);
             Domain.EmailStatus.EmailStatuses       = new LazyDictionary <int, Domain.EmailStatus>(this.GetEmailStatus);
             Domain.ReminderType.ReminderTypes      = new LazyDictionary <int, Domain.ReminderType>(this.GetReminderTypes);
             Domain.ReminderTime.ReminderTimes      = new LazyDictionary <int, Domain.ReminderTime>(this.GetReminderTimes);
             Domain.OrderPriority.OrderPriorities   = new LazyDictionary <int, Domain.OrderPriority>(this.GetOrderPriorities);
             Domain.Priority.Priorities             = new LazyDictionary <int, Domain.Priority>(this.GetPriorities);
             Domain.PaymentType.PaymentTypes        = new LazyDictionary <int, Domain.PaymentType>(this.GetPaymentTypes);
             Domain.SurchargeType.SurchargeTypes    = new LazyDictionary <int, Domain.SurchargeType>(this.GetSurchargeTypes);
             Domain.ObjectType.ObjectTypes          = new LazyDictionary <int, Domain.ObjectType>(this.GetObjectTypes);
             Domain.PaymentCode.PaymentCodes        = new LazyDictionary <int, Domain.PaymentCode>(this.GetPaymentCodes);
             Domain.OrderAssignmentFeeType.OrderAssignmentFeeTypes = new LazyDictionary <int, Domain.OrderAssignmentFeeType>(this.GetOrderAssignmentFeeType);
             Domain.PaymentStatus.PaymentStatuses     = new LazyDictionary <int, Domain.PaymentStatus>(this.GetPaymentStatus);
             Domain.RequestStatus.RequestStatuses     = new LazyDictionary <int, Domain.RequestStatus>(this.GetRequestStatus);
             Domain.PaperworkStatus.PaperworkStatuses = new LazyDictionary <int, Domain.PaperworkStatus>(this.GetPaperWorkStatuses);
             Domain.OrderAssignmentStatus.SPOrderAssignmentStatuses = new LazyDictionary <int, Domain.OrderAssignmentStatus>(this.GetSPOrderAssignmentStatuses);
             Domain.NetworkRole.NetworkRoles = new LazyDictionary <int, Domain.NetworkRole>(this.GetNetworkRoles);
         }
     }
 }
Example #16
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="AmqpClient"/> class.
        /// </summary>
        ///
        /// <param name="host">The fully qualified host name for the Event Hubs namespace.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
        /// <param name="eventHubName">The name of the specific Event Hub to connect the client to.</param>
        /// <param name="credential">The Azure managed identity credential to use for authorization.  Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
        /// <param name="clientOptions">A set of options to apply when configuring the client.</param>
        /// <param name="connectionScope">The optional scope to use for AMQP connection management.  If <c>null</c>, a new scope will be created.</param>
        /// <param name="messageConverter">The optional converter to use for transforming AMQP message-related types.  If <c>null</c>, a new converter will be created.</param>
        ///
        /// <remarks>
        ///   As an internal type, this class performs only basic sanity checks against its arguments.  It
        ///   is assumed that callers are trusted and have performed deep validation.
        ///
        ///   Any parameters passed are assumed to be owned by this instance and safe to mutate or dispose;
        ///   creation of clones or otherwise protecting the parameters is assumed to be the purview of the
        ///   caller.
        /// </remarks>
        ///
        protected AmqpClient(string host,
                             string eventHubName,
                             EventHubTokenCredential credential,
                             EventHubConnectionOptions clientOptions,
                             AmqpConnectionScope connectionScope,
                             AmqpMessageConverter messageConverter)
        {
            Argument.AssertNotNullOrEmpty(host, nameof(host));
            Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
            Argument.AssertNotNull(credential, nameof(credential));
            Argument.AssertNotNull(clientOptions, nameof(clientOptions));

            try
            {
                EventHubsEventSource.Log.EventHubClientCreateStart(host, eventHubName);

                ServiceEndpoint = new UriBuilder
                {
                    Scheme = clientOptions.TransportType.GetUriScheme(),
                    Host   = host
                }.Uri;

                ConnectionEndpoint = clientOptions.CustomEndpointAddress switch
                {
                    null => ServiceEndpoint,

                    _ => new UriBuilder
                    {
                        Scheme = ServiceEndpoint.Scheme,
                        Host   = clientOptions.CustomEndpointAddress.Host
                    }.Uri
                };

                EventHubName     = eventHubName;
                Credential       = credential;
                MessageConverter = messageConverter ?? new AmqpMessageConverter();
                ConnectionScope  = connectionScope ?? new AmqpConnectionScope(ServiceEndpoint, ConnectionEndpoint, eventHubName, credential, clientOptions.TransportType, clientOptions.Proxy);

                ManagementLink = new FaultTolerantAmqpObject <RequestResponseAmqpLink>(
                    timeout => ConnectionScope.OpenManagementLinkAsync(timeout, CancellationToken.None),
                    link =>
                {
                    link.Session?.SafeClose();
                    link.SafeClose();
                    EventHubsEventSource.Log.FaultTolerantAmqpObjectClose(nameof(RequestResponseAmqpLink), "", EventHubName, "", "", link.TerminalException?.Message);
                });
            }
            finally
            {
                EventHubsEventSource.Log.EventHubClientCreateComplete(host, eventHubName);
            }
        }
Example #17
0
File: Add.cs Project: qiqi545/HQ
 public static IdentityBuilder AddSqliteIdentityStore <TUser, TRole, TTenant, TApplication>(
     this IdentityBuilder identityBuilder,
     string connectionString, ConnectionScope scope = ConnectionScope.ByRequest,
     IConfiguration databaseConfig = null)
     where TUser : IdentityUserExtended <string>
     where TRole : IdentityRoleExtended <string>
     where TTenant : IdentityTenant <string>
     where TApplication : IdentityApplication <string>
 {
     return(identityBuilder.AddSqliteIdentityStore <string, TUser, TRole, TTenant, TApplication>(connectionString,
                                                                                                 scope,
                                                                                                 databaseConfig));
 }
Example #18
0
        public ContractTemplate GetTemplate(Guid templateGuid)
        {
            using (var scope = ConnectionScope.GetExistOrCreate())
            {
                return(CPQuery.Create(@"
SELECT  ContractTemplateGUID ,
        TemplateName,
        TemplateContent
FROM    dbo.Geek_ContractTemplate
WHERE ContractTemplateGUID=@templateGuid
", new { templateGuid }).ToSingle <ContractTemplate>());
            }
        }
Example #19
0
 internal Session(
     ConnectionScope connectionScope,
     ISqlDialect sqlDialect,
     IDbDriver sqlDriver,
     IList <IDeleteListener> deleteListeners,
     IList <IInsertListener> insertListeners,
     IList <IUpdateListener> updateListeners)
     : base(connectionScope, sqlDialect, sqlDriver)
 {
     this.deleteListeners = deleteListeners;
     this.insertListeners = insertListeners;
     this.updateListeners = updateListeners;
 }
Example #20
0
        public static IdentityBuilder AddSqlServerIdentityStore <TKey, TUser, TRole, TTenant>(
            this IdentityBuilder identityBuilder,
            string connectionString, ConnectionScope scope = ConnectionScope.ByRequest, IConfiguration databaseConfig = null)
            where TKey : IEquatable <TKey>
            where TUser : IdentityUserExtended <TKey>
            where TRole : IdentityRoleExtended <TKey>
            where TTenant : IdentityTenant <TKey>
        {
            var configureDatabase =
                databaseConfig != null ? databaseConfig.Bind : (Action <SqlServerOptions>)null;

            return(AddSqlServerIdentityStore <TKey, TUser, TRole, TTenant>(identityBuilder, connectionString, scope, configureDatabase));
        }
Example #21
0
        public List <Contract> GetList()
        {
            using (var scope = ConnectionScope.GetExistOrCreate())
            {
                return(CPQuery.Create(@"
SELECT  ContractGUID ,
        ContractName ,
        ContractTemplateGUID
FROM    [dbo].[Geek_Contract]
WHERE   ApproveStatus IS NULL
        OR ApproveStatus = '不通过'").ToList <Contract>());
            }
        }
Example #22
0
        public DiscountModel GetDiscountModel(Guid id)
        {
            using (var connectionScope = new ConnectionScope())
            {
                var result = new DiscountModel();

                result.Discount  = connectionScope.Connection.Get <Discount>(id);
                result.Products  = connectionScope.Connection.GetList <DiscountProduct>(Predicates.Field <DiscountProduct>(f => f.DiscountId, Operator.Eq, id)).ToList();
                result.Customers = connectionScope.Connection.GetList <DiscountCustomer>(Predicates.Field <DiscountCustomer>(f => f.DiscountId, Operator.Eq, id)).ToList();

                return(result);
            }
        }
        Task SendUsingNewConnection(IPipe <ConnectionContext> connectionPipe, ConnectionScope scope, CancellationToken cancellationToken)
        {
            try
            {
                if (_cacheTaskScope.StoppingToken.IsCancellationRequested)
                {
                    throw new TaskCanceledException($"The connection is being disconnected: {_settings.ToDebugString()}");
                }

                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Connecting: {0}", _connectionFactory.ToDebugString());
                }

                var connection = _connectionFactory.CreateConnection();

                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Connected: {0} (address: {1}, local: {2}", _connectionFactory.ToDebugString(),
                                     connection.Endpoint, connection.LocalPort);
                }

                EventHandler <ShutdownEventArgs> connectionShutdown = null;
                connectionShutdown = (obj, reason) =>
                {
                    Interlocked.CompareExchange(ref _scope, null, scope);

                    scope.Shutdown(reason.ReplyText);

                    connection.ConnectionShutdown -= connectionShutdown;
                };

                connection.ConnectionShutdown += connectionShutdown;

                var connectionContext = new RabbitMqConnectionContext(connection, _settings, _cacheTaskScope);

                connectionContext.GetOrAddPayload(() => _settings);

                scope.Connected(connectionContext);
            }
            catch (BrokerUnreachableException ex)
            {
                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.ConnectFaulted(ex);

                throw new RabbitMqConnectionException("Connect failed: " + _connectionFactory.ToDebugString(), ex);
            }

            return(SendUsingExistingConnection(connectionPipe, scope, cancellationToken));
        }
Example #24
0
        public static DataTable GetOrderInfoTable()
        {
            // 把结果用静态变量缓存起来,避免影响测试时间
            // 由于在运行测试前,会有一次单独的调用,所以并没有线程安全问题。

            if (s_OrderInfoTable == null)
            {
                using (ConnectionScope scope = ConnectionScope.Create()) {
                    s_OrderInfoTable = CPQuery.Create(QueryText, new { TopN = 50 }).ToDataTable();
                }
            }

            return(s_OrderInfoTable);
        }
Example #25
0
 /// <summary>
 /// Get all domains
 /// </summary>
 /// <returns></returns>
 public IList <T> GetAll()
 {
     using (ConnectionScope.Enter())
     {
         if (typeof(ISoftDeletable).IsAssignableFrom(typeof(T)))
         {
             return(this.Search(SearchQueryBuilder.CreateQuery()).Items);
         }
         else
         {
             return(this.GetByCriteria());
         }
     }
 }
Example #26
0
        public IEnumerable <DiscountProduct> GetDiscountProductsByCustomerId(Guid customerId)
        {
            using (var connectionScope = new ConnectionScope())
            {
                var sql = @"
                    select 
                        * 
                    from 
                        [DiscountProduct] dp
                        join [DiscountCustomer] dc on dc.DiscountId = dp.DiscountId and dc.CustomerId = @CustomerId";

                return(connectionScope.Connection.Query <DiscountProduct>(sql, new { CustomerId = customerId }).ToList());
            }
        }
Example #27
0
        public static IServiceCollection AddDatabaseConnection <TScope, TConnectionFactory>(
            this IServiceCollection services, string connectionString, ConnectionScope scope,
            Action <IDbConnection, IServiceProvider> onConnection = null,
            Action <IDbCommand, Type, IServiceProvider> onCommand = null)
            where TConnectionFactory : class, IConnectionFactory, new()
        {
            services.AddTransient(r => _container.Resolve <IDataConnection <TScope> >());

            var serviceProvider = services.BuildServiceProvider();

            _container = _container ?? new DependencyContainer(serviceProvider);
            _container.AddAspNetCore();
            _container.Register(r => serviceProvider);

            var slot = $"{typeof(TScope).FullName}";

            AddDatabaseConnection <TConnectionFactory>(services, connectionString, scope, slot, onConnection, onCommand);

            switch (scope)
            {
            case ConnectionScope.AlwaysNew:
                _container.Register <IDataConnection <TScope> >(r =>
                                                                new DataConnection <TScope>(r.Resolve <DataContext>(slot), r.MustResolve <IServiceProvider>(),
                                                                                            onCommand));
                break;

            case ConnectionScope.ByRequest:
                _container.Register <IDataConnection <TScope> >(
                    r => new DataConnection <TScope>(r.Resolve <DataContext>(slot), r.MustResolve <IServiceProvider>(),
                                                     onCommand), Lifetime.Request);
                break;

            case ConnectionScope.ByThread:
                _container.Register <IDataConnection <TScope> >(
                    r => new DataConnection <TScope>(r.Resolve <DataContext>(slot), r.MustResolve <IServiceProvider>(),
                                                     onCommand), Lifetime.Thread);
                break;

            case ConnectionScope.KeepAlive:
                _container.Register <IDataConnection <TScope> >(
                    r => new DataConnection <TScope>(r.Resolve <DataContext>(slot), r.MustResolve <IServiceProvider>(),
                                                     onCommand), Lifetime.Permanent);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(scope), scope, null);
            }

            return(services);
        }
Example #28
0
 /// <summary>
 /// Get Domain by ID
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public T GetByID(TIdentifier id)
 {
     using (ConnectionScope.Enter())
     {
         T entity;
         entity = (T)NHibernateSession.Get(persitentType, id);
         ISoftDeletable softDeletable = entity as ISoftDeletable;
         if (softDeletable != null && softDeletable.DeletedDate != null)
         {
             entity = default(T);
         }
         return(entity);
     }
 }
Example #29
0
 internal Browser(ConnectionScope scope, string guid, BrowserInitializer initializer)
 {
     _scope           = scope.CreateChild(guid);
     _channel         = new BrowserChannel(guid, scope, this);
     IsConnected      = true;
     _channel.Closed += (sender, e) =>
     {
         IsConnected        = false;
         _isClosedOrClosing = true;
         Disconnected?.Invoke(this, EventArgs.Empty);
         _scope.Dispose();
         _closedTcs.TrySetResult(true);
     };
 }
Example #30
0
        /// <summary>
        /// 保存合同条款
        /// </summary>
        /// <param name="term">条款</param>
        /// <param name="contractGuid">合同Guid</param>
        private void SaveTerm(ContractTerm term, Guid contractGuid)
        {
            string sql;

            term.ContractGuid = contractGuid;

            if (term.ContractTermGUID == Guid.Empty)
            {
                sql = @"
INSERT  INTO [dbo].[Geek_ContractTerm]
        ( [ContractTermGUID] ,
          [CreatedTime] ,
          [CreatedGUID] ,
          [CreatedName] ,
          [ModifiedTime] ,
          [ModifiedGUID] ,
          [ModifiedName] ,
          [ContractGuid] ,
          [TermToField] ,
          [TermContent]
        )
VALUES  ( NEWID() ,
          GETDATE() ,
          '4230BC6E-69E6-46A9-A39E-B929A06A84E8' ,
          '系统管理员' ,
          GETDATE() ,
          '4230BC6E-69E6-46A9-A39E-B929A06A84E8' ,
          '系统管理员' ,
          @ContractGuid ,
          @TermToField ,
          @TermContent
        )";
            }
            else
            {
                sql = @"
UPDATE  [dbo].[Geek_ContractTerm]
SET     [ModifiedTime] = GETDATE() ,
        [ModifiedGUID] = '4230BC6E-69E6-46A9-A39E-B929A06A84E8' ,
        [ModifiedName] = '系统管理员' ,
        [TermContent] = @TermContent 
WHERE   ContractTermGUID = @ContractTermGUID";
            }

            using (var scope = ConnectionScope.GetExistOrCreate())
            {
                CPQuery.Create(sql, term).ExecuteNonQuery();
            }
        }
        /// <summary>
        ///   Creates the AMQP link to be used for producer-related operations and ensures
        ///   that the corresponding state for the producer has been updated based on the link
        ///   configuration.
        /// </summary>
        ///
        /// <param name="partitionId">The identifier of the Event Hub partition to which it is bound; if unbound, <c>null</c>.</param>
        /// <param name="producerIdentifier">The identifier associated with the producer.</param>
        /// <param name="partitionOptions">The set of options, if any, that should be considered when initializing the producer.</param>
        /// <param name="timeout">The timeout to apply for creating the link.</param>
        /// <param name="cancellationToken">The cancellation token to consider when creating the link.</param>
        ///
        /// <returns>The AMQP link to use for producer-related operations.</returns>
        ///
        /// <remarks>
        ///   This method will modify class-level state, setting those attributes that depend on the AMQP
        ///   link configuration.  There exists a benign race condition in doing so, as there may be multiple
        ///   concurrent callers.  In this case, the attributes may be set multiple times but the resulting
        ///   value will be the same.
        /// </remarks>
        ///
        protected virtual async Task <SendingAmqpLink> CreateLinkAndEnsureProducerStateAsync(string partitionId,
                                                                                             string producerIdentifier,
                                                                                             PartitionPublishingOptionsInternal partitionOptions,
                                                                                             TimeSpan timeout,
                                                                                             CancellationToken cancellationToken)
        {
            var link             = default(SendingAmqpLink);
            var operationTimeout = RetryPolicy.CalculateTryTimeout(0);

            try
            {
                link = await ConnectionScope.OpenProducerLinkAsync(partitionId, ActiveFeatures, partitionOptions, operationTimeout, timeout, producerIdentifier, cancellationToken).ConfigureAwait(false);

                if (!MaximumMessageSize.HasValue)
                {
                    // This delay is necessary to prevent the link from causing issues for subsequent
                    // operations after creating a batch.  Without it, operations using the link consistently
                    // timeout.  The length of the delay does not appear significant, just the act of introducing
                    // an asynchronous delay.
                    //
                    // For consistency the value used by the legacy Event Hubs client has been brought forward and
                    // used here.

                    await Task.Delay(15, cancellationToken).ConfigureAwait(false);

                    MaximumMessageSize = (long)link.Settings.MaxMessageSize;
                }

                if (InitializedPartitionProperties == null)
                {
                    var producerGroup = link.ExtractSettingPropertyValueOrDefault(AmqpProperty.ProducerGroupId, default(long?));
                    var ownerLevel    = link.ExtractSettingPropertyValueOrDefault(AmqpProperty.ProducerOwnerLevel, default(short?));
                    var sequence      = link.ExtractSettingPropertyValueOrDefault(AmqpProperty.ProducerSequenceNumber, default(int?));

                    // Once the properties are initialized, clear the starting sequence number to ensure that the current
                    // sequence tracked by the service is used should the link need to be recreated; this avoids the need for
                    // the transport producer to have awareness of the sequence numbers of events being sent.

                    InitializedPartitionProperties          = new PartitionPublishingPropertiesInternal(false, producerGroup, ownerLevel, sequence);
                    partitionOptions.StartingSequenceNumber = null;
                }
            }
            catch (Exception ex)
            {
                ExceptionDispatchInfo.Capture(ex.TranslateConnectionCloseDuringLinkCreationException(EventHubName)).Throw();
            }

            return(link);
        }
Example #32
0
        public void AddReceipt(Invoice invoice, IEnumerable <InvoiceItem> items)
        {
            using (var transaction = new TransactionScope())
                using (var connection = new ConnectionScope())
                {
                    if (invoice.Id == Guid.Empty)
                    {
                        invoice.Id = Guid.NewGuid();
                    }

                    // Update Inventory.
                    foreach (var item in items)
                    {
                        var product = ProductManager.GetProduct(item.ProductId);
                        if (product == null)
                        {
                            throw new Exception("Product not found.");
                        }

                        // Stock Correction?
                        // TODO.

                        // Movement.
                        ProductManager.AddMovement(new ProductMovement
                        {
                            Id               = Guid.NewGuid(),
                            ProductId        = item.ProductId,
                            DateTime         = invoice.DateTime,
                            MovementType     = ProductMovementType.Receipt,
                            Quantity         = item.Quantity,
                            SourceId         = invoice.Id,
                            SourceItemNumber = item.ItemNumber
                        });
                    }

                    // Add Customer Transaction.
                    CustomerManager.AddTransaction(new CustomerTransaction()
                    {
                        Id         = Guid.NewGuid(),
                        CustomerId = invoice.CustomerId,
                        DateTime   = invoice.DateTime,
                        Type       = CustomerTransactionType.Payment,
                        Amount     = items.Aggregate(0.0m, (total, item) => total += item.Quantity * item.Price) * -1.0m,
                        SourceId   = invoice.Id
                    });

                    transaction.Complete();
                }
        }
Example #33
0
        public void Test_DataTable_ToSingle()
        {
            using (ConnectionScope scope = ConnectionScope.Create()) {
                var       queryArgument = new { MaxCustomerID = 10 };
                DataTable table         = CPQuery.Create(GetSql("GetCustomerList"), queryArgument).ToDataTable();

                Customer customer1 = table.Rows[0].ToSingle <Customer>();
                Customer customer2 = CPQuery.Create(GetSql("GetCustomerList"), queryArgument).ToSingle <Customer>();

                string json1 = customer1.ToJson();
                string json2 = customer2.ToJson();

                Assert.AreEqual(json1, json2);
            }
        }
Example #34
0
        public void Test_DataTable_ToList()
        {
            using (ConnectionScope scope = ConnectionScope.Create()) {
                var       queryArgument = new { MaxCustomerID = 10 };
                DataTable table         = CPQuery.Create(GetSql("GetCustomerList"), queryArgument).ToDataTable();

                List <Customer> list1 = table.ToList <Customer>();
                List <Customer> list2 = CPQuery.Create(GetSql("GetCustomerList"), queryArgument).ToList <Customer>();

                string json1 = list1.ToJson();
                string json2 = list2.ToJson();

                Assert.AreEqual(json1, json2);
            }
        }
Example #35
0
File: Add.cs Project: qiqi545/HQ
 public static IdentityBuilder AddDocumentDbIdentityStore <TKey, TUser, TRole, TTenant, TApplication>(
     this IdentityBuilder identityBuilder,
     string connectionString,
     ConnectionScope scope = ConnectionScope.ByRequest)
     where TKey : IEquatable <TKey>
     where TUser : IdentityUserExtended <TKey>
     where TRole : IdentityRoleExtended <TKey>
     where TTenant : IdentityTenant <TKey>
     where TApplication : IdentityApplication <TKey>
 {
     return(identityBuilder.AddDocumentDbIdentityStore <TKey, TUser, TRole, TTenant, TApplication>(o =>
     {
         DefaultDbOptions(connectionString, o);
     }, scope));
 }
        /// <summary>
        /// 分页查询,返回实体列表
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="command">XmlCommand实例引用</param>
        /// <param name="pageInfo">分页信息</param>
        /// <returns>实体集合</returns>
        public static List <T> ToPageList <T>(this XmlCommand command, PagingInfo pageInfo) where T : class, new()
        {
            CPQuery query1 = null;
            CPQuery query2 = null;

            CreatePagedQuery(command, pageInfo, out query1, out query2);

            // 确保在一个连接中执行二次数据库操作
            using (ConnectionScope scope = ConnectionScope.GetExistOrCreate()) {
                List <T> list = query1.ToList <T>();
                pageInfo.TotalRows = query2.ExecuteScalar <int>();

                return(list);
            }
        }
        /// <summary>
        /// 分页查询,返回DataTable
        /// </summary>
        /// <param name="command"></param>
        /// <param name="pageInfo"></param>
        /// <returns></returns>
        public static System.Data.DataTable ToPageTable(this XmlCommand command, PagingInfo pageInfo)
        {
            CPQuery query1 = null;
            CPQuery query2 = null;

            CreatePagedQuery(command, pageInfo, out query1, out query2);

            // 确保在一个连接中执行二次数据库操作
            using (ConnectionScope scope = ConnectionScope.GetExistOrCreate()) {
                System.Data.DataTable table = query1.ToDataTable();
                pageInfo.TotalRows = query2.ExecuteScalar <int>();

                return(table);
            }
        }
Example #38
0
        public List <FieldInfo> GetFields()
        {
            using (var scope = ConnectionScope.GetExistOrCreate())
            {
                return(CPQuery.Create(@"
SELECT  field_name_c Text, field_name Field
FROM    dbo.data_dict
WHERE   table_name = 'Geek_Contract'
        AND field_name NOT IN ( 'ApproverGUID','ApproverName','ApproveStatus','ApproveTime', 'CreatedGUID', 'ContractTemplateGUID', 'ContractGUID', 'CreatedTime', 'CreatedName',
                                'ContractContent', 'ModifiedGUID', 'ModifiedTime', 'ModifiedName', 'VersionNumber' )
ORDER BY field_name

").ToList <FieldInfo>());
            }
        }
Example #39
0
        public static void UnSafeInit(string connectionString)
        {
            if (s_inited)
            {
                throw new InvalidOperationException("请不要多次调用UnSafeInit方法!");
            }


            // 设置默认的连接字符串。
            ConnectionScope.SetDefaultConnection(connectionString);

            s_inited = true;

            BuildManager.StartAutoCompile();
        }
Example #40
0
        /// <summary>
        /// Insert a domain
        /// </summary>
        /// <param name="obj">Domain</param>
        /// <returns></returns>
        public T Insert(T obj)
        {
            using (ConnectionScope.Enter())
            {
                ISoftDeletable softDeletable = obj as ISoftDeletable;
                if (softDeletable != null)
                {
                    softDeletable.CreatedDate  = DateTime.Now;
                    softDeletable.ModifiedDate = DateTime.Now;
                }
                TIdentifier id = (TIdentifier)NHibernateSession.Save(obj);
                obj = GetByID(id);

                return(obj);
            }
        }
Example #41
0
        protected SessionBase(ConnectionScope connectionScope, IDbDriver dbDriver)
        {
            this.ConnectionScope = connectionScope;
            this.DbDriver = dbDriver;

            this.Connection = dbDriver.CreateConnection();

            if (this.ConnectionScope == ConnectionScope.PerSession)
            {
                if (Log.IsDebug)
                {
                    Log.Debug(LogMessages.Session_OpeningConnection);
                }

                this.Connection.Open();
            }
        }
Example #42
0
        public bool DelTable(DelTableArgs arg)
        {
            using( ConnectionScope scope = new ConnectionScope(TransactionMode.Required) ) {
                foreach( string oid in arg.DbDistributes ) {

                    var parameter = new {
                        DbDistributeGUID = new Guid(oid),
                    };

                    CPQuery.From("DELETE FROM esb_DbDistribute WHERE DbDistributeGUID=@DbDistributeGUID", parameter).ExecuteNonQuery();

                }

                scope.Commit();
            }
            return true;
        }
        /// <summary>
        /// Gets or creates connection to the cluster.
        /// </summary>
        /// <param name="scope"> The scope. </param>
        /// <param name="partitionKey"> The partition key. </param>
        /// <returns> </returns>
        public Connection GetOrCreateConnection(ConnectionScope scope, PartitionKey partitionKey)
        {
            //provide connections on command level only
            if(scope == ConnectionScope.Connection)
                return null;

            int count = _nodes.Count;
            int offset = _rnd.Next(count);

            Connection connection = null;

            //try to get an unused connection from a random node
            for(int i = 0; i < count; i++)
            {
                Node randomNode = _nodes[(offset + i)%count];

                //skip if node is down
                if(!randomNode.IsUp) continue;

                //try get a connection from it
                connection = randomNode.GetConnection();

                //connection is not used to the max, ok to use
                if(connection != null && connection.Load < _config.NewConnectionTreshold)
                    break;

                //get a new connection to the node if possible
                if(_config.MaxConnections <= 0 || _connectionCount < _config.MaxConnections)
                {
                    //try to get a new connection from this random node
                    Connection newConnection = randomNode.CreateConnection();

                    if(newConnection != null)
                    {
                        Interlocked.Increment(ref _connectionCount);
                        newConnection.OnConnectionChange +=
                            (c, ev) => { if(ev.Connected == false) Interlocked.Decrement(ref _connectionCount); };

                        connection = newConnection;
                        break;
                    }
                }
            }

            return connection;
        }
Example #44
0
        public JsonResult DeletePipe(string[] pipeGUIDList)
        {
            if (pipeGUIDList == null || pipeGUIDList.Length == 0)
                throw new ArgumentException("接收接口列表不能为空.");

            HttpResult hr = new HttpResult() { Result = true };
            string keyList = string.Join("','", pipeGUIDList);

            using (ConnectionScope scope = new ConnectionScope(TransactionMode.Required)){
                CPQuery.From(string.Format("delete from esb_ReceiverInterface where ReceiverInterfaceID in ('{0}')", keyList)).ExecuteNonQuery();
                CPQuery.From(string.Format("delete from esb_DistributeStrategy where ReceiverInterfaceID in ('{0}')", keyList)).ExecuteNonQuery();
                CPQuery.From(string.Format("delete from esb_DistributeFailedInform where ReceiverInterfaceID in ('{0}')", keyList)).ExecuteNonQuery();
                CPQuery.From(string.Format("delete from esb_VerifyDistribute where ReceiverInterfaceID in ('{0}')", keyList)).ExecuteNonQuery();
                scope.Commit();
            }

            return new JsonResult(hr);
        }
Example #45
0
        public string SaveXml(string dateXml, string userXml)
        {
            HttpResult hr = new HttpResult() { Result = true };

            try
            {
                EsbInvoker esbInvokerEntity = XmlDataEntity.ConvertXmlToSingle<EsbInvoker>(dateXml);
                EsbUsers user = userXml.FromXml<EsbUsers>();

                using (ConnectionScope scope = new ConnectionScope(TransactionMode.Required))
                {
                    if (esbInvokerEntity.InvokerID == Guid.Empty)
                    {
                        if (EntityCommon.IsExistData("Esb_Invoker", "InvokerCode", esbInvokerEntity.InvokerCode))
                        {
                            hr.Result = false;
                            hr.ErrorMessage = "用户代码不允许重复,请重新录入用户代码!";
                            return hr.ToXml();
                        }
                        esbInvokerEntity.InvokerID = Guid.NewGuid();
                        esbInvokerEntity.CreatedOn = DateTime.Now;
                        esbInvokerEntity.CreatedBy = user.UserID;

                        esbInvokerEntity.Insert();
                    }
                    else
                    {
                        esbInvokerEntity.ModifiedOn = DateTime.Now;
                        esbInvokerEntity.ModifiedBy = user.UserID;
                        esbInvokerEntity.Update();
                    }

                    hr.KeyValue = esbInvokerEntity.InvokerID.ToString();
                    scope.Commit();
                }
            }
            catch (Exception)
            {
                hr.Result = false;
                hr.ErrorMessage = "运行时异常,请与管理员联系!";
            }

            return hr.ToXml();
        }
Example #46
0
        public JsonResult DeleteDB(DelDBArgs arg)
        {
            if (arg == null || arg.DbDistributes == null || arg.DbDistributes.Length == 0)
                throw new ArgumentException("数据库分发接口列表不能为空.");

            HttpResult hr = new HttpResult() { Result = true };

            using (ConnectionScope scope = new ConnectionScope(TransactionMode.Required)){
                foreach (string oid in arg.DbDistributes){
                    var parameter = new{
                        DbDistributeGUID = new Guid(oid),
                    };

                    CPQuery.From("DELETE FROM esb_DbDistribute WHERE DbDistributeGUID=@DbDistributeGUID", parameter).ExecuteNonQuery();
                }
                scope.Commit();
            }
            return new JsonResult(hr);
        }
        public Task Send(IPipe<ConnectionContext> connectionPipe, CancellationToken cancellationToken)
        {
            ConnectionScope newScope = null;
            ConnectionScope existingScope;

            lock (_scopeLock)
            {
                existingScope = _scope;
                if (existingScope == null)
                {
                    newScope = new ConnectionScope();
                    _scope = newScope;
                }
            }
            if (existingScope != null)
                return SendUsingExistingConnection(connectionPipe, cancellationToken, existingScope);

            return SendUsingNewConnection(connectionPipe, newScope, cancellationToken);
        }
 internal NHibernateTransactionContext()
 {
   if (ConnectionContext.Current == null)
   {
     _connectionScope = ConnectionScope.Enter();
   }
   try
   {
     _transaction = NHibernateClientProvider.CurrentSession.BeginTransaction();
   }
   catch
   {
     if (_connectionScope != null)
     {
       _connectionScope.Leave();
     }
     throw;
   }
 }
        /// <summary>
        /// Gets or creates connection to the cluster.
        /// </summary>
        /// <param name="scope"> The scope. </param>
        /// <param name="partitionKey"> The partition key. </param>
        /// <returns> </returns>
        /// <exception cref="CqlException">
        /// Can not connect to any node of the cluster! All connectivity to the cluster seems to be
        /// lost
        /// </exception>
        public Connection GetOrCreateConnection(ConnectionScope scope, PartitionKey partitionKey)
        {
            //provide connections on command level only
            if(scope == ConnectionScope.Connection)
                return null;

            //try based on partition first
            if(partitionKey != null && partitionKey.IsSet)
            {
                var nodes = _nodes.GetResponsibleNodes(partitionKey).Where(n => n.IsUp).OrderBy(n => n.Load);

                foreach(Node node in nodes)
                {
                    Connection connection = node.GetOrCreateConnection();
                    if(connection != null)
                        return connection;
                }
            }

            return _baseStrategy.GetOrCreateConnection(scope, partitionKey);
        }
Example #50
0
        public JsonResult DeleteUsers(string keyList)
        {
            HttpResult hr = new HttpResult() { Result = true };
            keyList = keyList.Replace(";", "','");

            try
            {
                using (ConnectionScope scope = new ConnectionScope(TransactionMode.Required))
                {
                    CPQuery.From(String.Format("delete from esb_Users where UserID in ('{0}')", keyList)).ExecuteNonQuery();
                    CPQuery.From(String.Format("delete from esb_DistributeFailedInform where UserID in ('{0}')", keyList)).ExecuteNonQuery();
                    scope.Commit();
                }
            }
            catch
            {
                hr.Result = false;
                hr.ErrorMessage = "删除用户失败!";
            }

            return new JsonResult(hr);
        }
        /// <summary>
        /// Gets or creates connection to the cluster.
        /// </summary>
        /// <param name="scope"> </param>
        /// <param name="partitionKey"> </param>
        /// <returns> </returns>
        public Connection GetOrCreateConnection(ConnectionScope scope, PartitionKey partitionKey)
        {
            //provide connections on command level only
            if(scope == ConnectionScope.Connection)
                return null;

            //Sort the nodes by load (used first)
            Node leastUsedNode =
                _nodes.Where(n => n.IsUp).SmallestOrDefault(
                    n => n.ConnectionCount > 0 ? n.Load : _config.NewConnectionTreshold - 1);

            //no node found! weird...
            if(leastUsedNode == null)
                return null;

            //try get a connection from it
            Connection connection = leastUsedNode.GetConnection();

            //smallest connection from smallest node
            if(connection != null && connection.Load < _config.NewConnectionTreshold)
                return connection;

            if(_config.MaxConnections <= 0 || _connectionCount < _config.MaxConnections)
            {
                //try to get a new connection from this smallest node
                Connection newConnection = leastUsedNode.CreateConnection();

                if(newConnection != null)
                {
                    Interlocked.Increment(ref _connectionCount);
                    newConnection.OnConnectionChange +=
                        (c, ev) => { if(ev.Connected == false) Interlocked.Decrement(ref _connectionCount); };

                    return newConnection;
                }
            }

            return connection;
        }
Example #52
0
        /// <summary>
        /// 新增事件队列
        /// </summary>
        /// <param name="receiverInterfaceId"></param>
        /// <param name="contents"></param>
        public void SaveByEventQueue(Guid receiverInterfaceId, List<EsbVerifyDistribute> entityList, string contents)
        {
            using (ConnectionScope scope = new ConnectionScope(TransactionMode.Required))
            {
                int resultFirst = 1;
                int resultSecond = 1;
                if (entityList.Exists(entity => entity.DistributeStrategy == 0))
                {
                    resultFirst = CreateEventQueue(receiverInterfaceId, contents, 0);
                }

                if (!(resultFirst < 1) && entityList.Exists(entity => entity.DistributeStrategy == 1))
                {
                    resultSecond = CreateEventQueue(receiverInterfaceId, contents, 1);
                }

                if (resultFirst < 1 || resultSecond < 1)
                    throw new ApplicationException("保存事件队列失败!");

                scope.Commit();
            }
        }
        async Task SendUsingNewConnection(IPipe<ConnectionContext> connectionPipe, ConnectionScope scope, CancellationToken cancellationToken)
        {
            try
            {
                if (_signal.CancellationToken.IsCancellationRequested)
                    throw new TaskCanceledException($"The connection is being disconnected: {_settings.ToDebugString()}");

                if (_log.IsDebugEnabled)
                    _log.DebugFormat("Connecting: {0}", _connectionFactory.ToDebugString());

                IConnection connection = _connectionFactory.CreateConnection();

                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Connected: {0} (address: {1}, local: {2}", _connectionFactory.ToDebugString(),
                        connection.RemoteEndPoint, connection.LocalEndPoint);
                }

                EventHandler<ShutdownEventArgs> connectionShutdown = null;
                connectionShutdown = (obj, reason) =>
                {
                    connection.ConnectionShutdown -= connectionShutdown;

                    Interlocked.CompareExchange(ref _scope, null, scope);

                    scope.Close();
                };

                connection.ConnectionShutdown += connectionShutdown;

                var connectionContext = new RabbitMqConnectionContext(connection, _settings, _signal.CancellationToken);

                connectionContext.GetOrAddPayload(() => _settings);

                scope.Connected(connectionContext);
            }
            catch (BrokerUnreachableException ex)
            {
                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.ConnectFaulted(ex);

                throw new RabbitMqConnectionException("Connect failed: " + _connectionFactory.ToDebugString(), ex);
            }

            try
            {
                using (SharedConnectionContext context = await scope.Attach(cancellationToken))
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Using new connection: {0}", ((ConnectionContext)context).HostSettings.ToDebugString());

                    await connectionPipe.Send(context);
                }
            }
            catch (Exception ex)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The connection usage threw an exception", ex);

                throw;
            }
        }
 /// <summary>
 /// Invoked when a connection is no longer in use by the application
 /// </summary>
 /// <param name="connection"> The connection no longer used. </param>
 /// <param name="scope"> The scope. </param>
 public void ReturnConnection(Connection connection, ConnectionScope scope)
 {
     //no-op
 }
        static async Task SendUsingExistingConnection(IPipe<ConnectionContext> connectionPipe, CancellationToken cancellationToken, ConnectionScope scope)
        {
            try
            {
                using (SharedConnectionContext context = await scope.Attach(cancellationToken))
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Using existing connection: {0}", ((ConnectionContext)context).HostSettings.ToDebugString());

                    await connectionPipe.Send(context);
                }
            }
            catch (Exception ex)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The existing connection usage threw an exception", ex);

                throw;
            }
        }
 /// <summary>
 /// Invoked when a connection is no longer in use by the application
 /// </summary>
 /// <param name="connection"> The connection no longer used. </param>
 public void ReturnConnection(Connection connection, ConnectionScope scope)
 {
     //connections are shared, nothing to do here
 }
Example #57
0
 private static void DoSendMail(string mailContent, ConnectionScope scope)
 {
     CPQuery.From(mailContent).ExecuteNonQuery();
     scope.Commit();
 }
Example #58
0
        /// <summary>
        /// 发送失败通知消息
        /// </summary>
        /// <param name="entity"></param>
        public static void SendMail(EsbDistributionTask entity)
        {
            try
            {
                string strSqlsendMail = @"INSERT INTO myMailSend
                            (MailGUID,SMTPServer,[PassWord],SenderName,SenderMail,PlanSendTime,[Application],[Function],ApplicationName,
                            [Subject],ReceiveMail,MailBody,Status,SubmitTime)
                            VALUES
                            (newid(),'{0}','{1}','{2}','{3}',getdate(),'0000','00','ESB',
                            '明源软件-ESB数据分发失败-预警通知','{4}','{5}','未发送',getdate())";
                var re = GetDictionary();
                if (re["EnabledEmail"] != "1") return;

                strSqlsendMail = string.Format(strSqlsendMail,
                                               re["MailSMTPServer"], re["MailPassWord"], re["MailSenderName"],
                                               re["MailSender"], "{0}", "{1}");

                var strSqlBuilder = new StringBuilder();

                var parameter1 = new { ReceiverInterfaceID = entity.ReceiverInterfaceID };
                var userList = CPQuery.From(@"select * from esb_Users").ToList<EsbUsers>();
                foreach (EsbUsers esbUserse in userList)
                {
                    strSqlBuilder.AppendLine(string.Format(strSqlsendMail, esbUserse.EmailUrl, "{0}"));
                }
                if (strSqlBuilder.Length < 1) return;
                var parameter2 = new { DistributionTaskID = entity.DistributionTaskID };
                var errorMsg =
                    CPQuery.From(@"select '接收接口:'+r.ServiceName+' - '+r.DisplayName + CHAR(13)
                                    +'分发业务系统:'+ provider.ProviderName +' - '+ provider.DisplayName+ CHAR(13)
                                    + '服务地址:'+ provider.protocol + '://' + provider.domain + ':' + cast(provider.port as nvarchar(255)) + s.relativepath + CHAR(13)
                                    + '服务操作:'+ t.MethodName  + CHAR(13)
                                    + '错误信息:'+ CHAR(13) + t.DistributionResult
                                    from esb_DistributionTask t
                                    join esb_ReceiverInterface r on r.ReceiverInterfaceID = t.ReceiverInterfaceID
                                    join esb_ServiceInfo s on t.ServiceInfoID = s.ServiceInfoID
                                    join dbo.esb_provider provider on s.providerid = provider.providerid
                                    where t.DistributionTaskID = @DistributionTaskID", parameter2).ExecuteScalar<string>();

                var mailContent = string.Format(strSqlBuilder.ToString(), errorMsg);
                if (string.IsNullOrEmpty(re["ToSendSystem"]))
                {
                    using (ConnectionScope scope = new ConnectionScope(TransactionMode.Required))
                    {
                        DoSendMail(mailContent, scope);
                    }
                }
                else
                {
                    using (ConnectionScope scope = new ConnectionScope(TransactionMode.Required, EsbProviderService.GetSqlConnectionString(re["ToSendSystem"])))
                    {
                        DoSendMail(mailContent, scope);
                    }
                }
            }
            catch (Exception exception)
            {
                new MyLogger().WriteLog(LogLevel.Error, "发送失败通知失败!", exception.ToString());
            }
        }
Example #59
0
        public ISession OpenSession(ConnectionScope connectionScope)
        {
            if (log.IsDebug)
            {
                log.Debug(LogMessages.SessionFactory_CreatingSession, this.connectionName);
            }

            SqlCharacters.Current = this.sqlDialect.SqlCharacters;

            return new Session(connectionScope, this.sqlDialect, this.dbDriver, this.sessionListeners);
        }
Example #60
0
 public TestSessionBase(ConnectionScope connectionScope, IDbDriver dbDriver)
     : base(connectionScope, dbDriver)
 {
 }