示例#1
0
 public SecureClient(ServiceEndPoint serviceEndpoint, X509Certificate2 clientCertificate, ILog log, ConnectionPool<ServiceEndPoint, SecureConnection> pool)
 {
     this.serviceEndpoint = serviceEndpoint;
     this.clientCertificate = clientCertificate;
     this.log = log;
     this.pool = pool;
 }
 internal static IOStrategy CreateIOStrategy(Node node)
 {
     var server = node.Hostname.Replace("8091", node.Ports.Direct.ToString(CultureInfo.InvariantCulture));
     var connectionPool = new ConnectionPool<EapConnection>(new PoolConfiguration(), UriExtensions.GetEndPoint(server));
     var ioStrategy = new DefaultIOStrategy(connectionPool);
     return ioStrategy;
 }
        public void SecureClientClearsPoolWhenAllConnectionsCorrupt()
        {
            var pool = new ConnectionPool<ServiceEndPoint, IConnection>();
            var stream = Substitute.For<IMessageExchangeStream>();
            stream.When(x => x.IdentifyAsClient()).Do(x => { throw new ConnectionInitializationFailedException(""); });
            for (int i = 0; i < SecureClient.RetryCountLimit; i++)
            {
                var connection = Substitute.For<IConnection>();
                connection.Protocol.Returns(new MessageExchangeProtocol(stream));
                pool.Return(endpoint, connection);
            }

            var request = new RequestMessage
            {
                Destination = endpoint,
                ServiceName = "IEchoService",
                MethodName = "SayHello",
                Params = new object[] { "Fred" }
            };

            var secureClient = new SecureClient(endpoint, Certificates.Octopus, log, pool);
            ResponseMessage response = null;
            secureClient.ExecuteTransaction((mep) => response = mep.ExchangeAsClient(request));

            // The pool should be cleared after the second failure
            stream.Received(2).IdentifyAsClient();
            // And a new valid connection should then be made
            Assert.AreEqual("Fred...", response.Result);
        }
示例#4
0
 public ClassQuery(string NameSpace, string query, Connection conn)
 {
     _connectionPassed = true;
     _conn = conn;
     _pool = conn.Pool;
     NewQuery(NameSpace, query);
 }
示例#5
0
 public EnumsHandler(ConnectionPool pool)
 {
     _pool = pool;
     _enumTableMaps = new Dictionary<Type, string>();
     _enumValuesMap = new Dictionary<Type, Dictionary<string, int>>();
     _enumReverseValuesMap = new Dictionary<Type, Dictionary<int, string>>();
 }
 public void TestFixtureSetup()
 {
     var configuration = new ClientConfiguration();
     var connectionPool = new ConnectionPool<EapConnection>(new PoolConfiguration(), UriExtensions.GetEndPoint(Address));
     var ioStrategy = new DefaultIOStrategy(connectionPool);
     _server = new Server(ioStrategy, new Node(), configuration);
 }
        public void When_Connecting_To_Dead_IP_Connection_Fails_After_n_Seconds()
        {
            const int connectionTimedOut = 10060;
            const string ipThatDoesNotExist = "198.0.0.1:11210";
            var ipEndpoint = UriExtensions.GetEndPoint(ipThatDoesNotExist);
            var connectionPoolConfig = new PoolConfiguration
            {
                ConnectTimeout = 1000 //set really low for test
            };
            var connectionPool = new ConnectionPool<Connection>(connectionPoolConfig, ipEndpoint);

            var stopWatch = new Stopwatch();
            try
            {
                stopWatch.Start();
                var connection = connectionPool.Acquire();
            }
            catch (SocketException e)
            {
                Assert.AreEqual(connectionTimedOut, e.ErrorCode);
            }
            finally
            {
                stopWatch.Stop();
                Assert.AreEqual(1.0d, Math.Round((double)stopWatch.Elapsed.Seconds));
            }
        }
 internal static IIOService CreateIOService(INodeAdapter node)
 {
     var server = node.Hostname.Replace("8091", node.KeyValue.ToString(CultureInfo.InvariantCulture));
     var connectionPool = new ConnectionPool<Connection>(new PoolConfiguration(), UriExtensions.GetEndPoint(server));
     var ioService = new PooledIOService(connectionPool);
     return ioService;
 }
 public StreamedFramingRequestChannel(ChannelManagerBase factory, IConnectionOrientedTransportChannelFactorySettings settings, EndpointAddress remoteAddresss, Uri via, IConnectionInitiator connectionInitiator, ConnectionPool connectionPool) : base(factory, remoteAddresss, via, settings.ManualAddressing)
 {
     this.settings = settings;
     this.connectionInitiator = connectionInitiator;
     this.connectionPool = connectionPool;
     this.messageEncoder = settings.MessageEncoderFactory.Encoder;
     this.upgrade = settings.Upgrade;
 }
示例#10
0
 public static ConnectionPool GetPool(string host, int port) {
     lock(_pools) {
         ConnectionPool pool;
         var key = string.Format("{0}:{1}", host, port);
         if(!_pools.TryGetValue(key, out pool)) {
             pool = new ConnectionPool(host, port);
             _pools[key] = pool;
         }
         return pool;
     }
 }
示例#11
0
 internal sealed override string ConstructClassViewString(ClassViewAttribute cva, ConnectionPool pool, QueryBuilder builder, ref List<IDbDataParameter> queryParameters, ref int parCount)
 {
     string ret = "( ";
     foreach (SelectParameter par in _parameters)
     {
         ret += " (" + par.ConstructClassViewString(cva,pool, builder, ref queryParameters, ref parCount) + ") " + JoinString;
     }
     if (_parameters.Length > 0)
         return ret.Substring(0, ret.Length - JoinString.Length) + ")";
     else
         return "";
 }
示例#12
0
 static DBAccess()
 {
     // initialize db connection pools
     dbBankIO = new ConnectionPool<NpgsqlConnection>("BankIO", AppConfig.GetItem("BankInDBString"));
     dbPayment = new ConnectionPool<NpgsqlConnection>("Payment", AppConfig.GetItem("PaymentDBString"));
     dbStamm = new ConnectionPool<NpgsqlConnection>("Stammdaten", AppConfig.GetItem("StammdatenDBString"));
     dbBilling = new ConnectionPool<NpgsqlConnection>("Billing", AppConfig.GetItem("Billing2DBString"));
     dbDoc = new ConnectionPool<NpgsqlConnection>("Doc", AppConfig.GetItem("DocDBString"));
     dbDocca = new ConnectionPool<NpgsqlConnection>("Docca", AppConfig.GetItem("DoccaDBString"));
     dbMisc = new ConnectionPool<NpgsqlConnection>("Misc", AppConfig.GetItem("MiscDBString"));
     dbServicePortal = new ConnectionPool<NpgsqlConnection>("ServicePortal", AppConfig.GetItem("ServicePortalDBString"));
 }
 public void When_pool_has_too_many_connections_and_gc_has_run_unreferenced_busy_sockets_are_collected() {
     Func<ISocket> socketFactory = () => new MockSocket();
     var pool = new ConnectionPool(socketFactory) { MaxConnections = 5 };
     var s1 = pool.GetSocket();
     var s2 = pool.GetSocket();
     var s3 = pool.GetSocket();
     var s4 = pool.GetSocket();
     var s5 = pool.GetSocket();
     s5 = null;
     GC.Collect();
     var s6 = pool.GetSocket();
     Assert.IsNotNull(s6);
 }
 public void ConnectionPoolDoesnSpawnNewConnections()
 {
     using(var pool = new ConnectionPool("localhost", 6379))
     {
         using(var con = pool.GetConnection())
         {
             var sampleOut = this.ReadLine();
             Assert.That(sampleOut, Is.StringContaining("Accepted 127.0.0.1"));
         }
         using (var con = pool.GetConnection())
         {
             var sampleOut = this.ReadLine();
             Assert.That(sampleOut, Is.Null);
         }
     }
 }
        public void When_GetBaseViewUri_Is_Called_With_EncryptTraffic_True_Uri_Is_SSL_URI()
        {
            var configuration = new ClientConfiguration
            {
                UseSsl = true
            };
            configuration.Initialize();

            var connectionPool = new ConnectionPool<EapConnection>(new PoolConfiguration(), UriExtensions.GetEndPoint(Address));
            var ioStrategy = new DefaultIOStrategy(connectionPool);
            using (var server = new Server(ioStrategy, new Node(), configuration))
            {
                var uri = server.GetBaseViewUri("default");
                Assert.AreEqual("https://localhost:18092/default", uri);
            }
        }
 public void Too_many_busy_connections_throws() {
     Func<ISocket> socketFactory = () => new MockSocket();
     var pool = new ConnectionPool(socketFactory) { MaxConnections = 5 };
     var s1 = pool.GetSocket();
     var s2 = pool.GetSocket();
     var s3 = pool.GetSocket();
     var s4 = pool.GetSocket();
     var s5 = pool.GetSocket();
     try {
         pool.GetSocket();
         Assert.Fail("didn't throw");
     } catch(PoolExhaustedException) {
         return;
     } catch(Exception e) {
         Assert.Fail(string.Format("threw {0} instead of PoolExhaustedException", e));
     }
 }
示例#17
0
 public ClassMapping(Connection conn, List<Type> tables)
 {
     _pool = conn.Pool;
     _classMaps = new Dictionary<Type, sTable>();
     _intermediateTables = new Dictionary<Type, Dictionary<string, sTable>>();
     _versionMaps = new Dictionary<Type, sTable>();
     _versionTypes = new Dictionary<Type, VersionField.VersionTypes>();
     Dictionary<string, sTable> intermediates;
     foreach (Type tbl in tables)
     {
         if (!_classMaps.ContainsKey(tbl))
         {
             _classMaps.Add(tbl, _ConstructTable(tbl,conn, out intermediates));
             if (intermediates.Count > 0)
                 _intermediateTables.Add(tbl, intermediates);
         }
     }
 }
示例#18
0
		public static ConnectionPool PoolFor(RemoteClientConfiguration configuration)
		{
			lock (_connectionPools)
			{
				ConnectionPool pool;
				var key = configuration.ToString();
				if(configuration.DedicatedPool) key +=  Guid.NewGuid();

				if (!_connectionPools.TryGetValue(key, out pool))
				{
					var host = configuration.Host;
					var port = configuration.Port;
					var maxConnections = configuration.MaxConnections;
					pool = new ConnectionPool(() => new RemoteConnection(host, port), maxConnections,host,port);
					_connectionPools[key] = pool;
				}
				return pool;
			}
		}
        protected ConnectionOrientedClientTransport( EndPoint remoteEndPoint, RpcTransportProtocol protocol, ClientEventLoop eventLoop, RpcClientOptions options )
            : base(protocol, eventLoop, options)
        {
            if ( remoteEndPoint == null )
            {
                throw new ArgumentNullException( "remoteEndPoint" );
            }

            this._connectionPool =
                new ConnectionPool(
                    remoteEndPoint,
                    protocol,
                    eventLoop,
                    options == null ? _defaultMinimumConnectionCount : ( options.MinimumConnectionCount ?? _defaultMinimumConnectionCount ),
                    options == null ? _defaultMaximumConnectionCount : ( options.MaximumConnectionCount ?? _defaultMaximumConnectionCount )
                );
            this._connectTimeout =
                options == null
                ? _defaultConnectTimeout
                : ( options.ConnectTimeout ?? _defaultConnectTimeout );
        }
 public void Release(ConnectionPool pool, TimeSpan timeout)
 {
     lock (this.ThisLock)
     {
         if (pool.Close(timeout))
         {
             List<ConnectionPool> list = this.registry[pool.Name];
             for (int i = 0; i < list.Count; i++)
             {
                 if (object.ReferenceEquals(list[i], pool))
                 {
                     list.RemoveAt(i);
                     break;
                 }
             }
             if (list.Count == 0)
             {
                 this.registry.Remove(pool.Name);
             }
         }
     }
 }
示例#21
0
        public void PoolPerformanceCompare()
        {
            System.Diagnostics.Stopwatch sw1 = new Stopwatch();

                int count = 0;
                sw1.Start();
                while (sw1.ElapsedMilliseconds < TestTimeMs)
                {
                    using (var conn = RedisConnection.Connect(_host, 6379))
                    {
                        var f = new CommandFactory(new NormalCommandExecutor(conn));
                        f.Set(Guid.NewGuid().ToString(), "bar").Exec();
                        count++;
                    }
                }
                sw1.Stop();

                System.Diagnostics.Stopwatch sw2 = new Stopwatch();

                int count2 = 0;
                sw2.Start();
                using(var pool = new ConnectionPool(_host, 6379))
                {
                    while (sw2.ElapsedMilliseconds < TestTimeMs)
                    {
                        using (var conn = pool.GetConnection())
                        {
                            var f = new CommandFactory(new NormalCommandExecutor(conn));
                            f.Set(Guid.NewGuid().ToString(), "bar").Exec();
                            count2++;
                        }
                    }
                }
                sw2.Stop();

                Assert.Fail(String.Format("Pooled: {0} Sets/Sec, NotPooled: {1} Sets/Sec",
                    count2 * 1000.0 / sw2.ElapsedMilliseconds,
                    count * 1000.0 / sw1.ElapsedMilliseconds));
        }
示例#22
0
        public void Test()
        {
            ObjectPool<Connection> objectPool = new ConnectionPool("connection string", "username", "password");

            var connection1 = objectPool.Acquire();

            Assert.That(connection1, Is.Not.Null);
            Assert.That(connection1, Is.TypeOf<Connection>());

            var connection2 = objectPool.Acquire();

            Assert.That(connection2, Is.Not.Null);
            Assert.That(connection2, Is.TypeOf<Connection>());

            Assert.That(connection1, Is.Not.SameAs(connection2));

            objectPool.Release(connection1);

            var connection3 = objectPool.Acquire();

            Assert.That(connection1, Is.SameAs(connection3));
        }
示例#23
0
        public void Release(ConnectionPool pool, TimeSpan timeout)
        {
            lock (ThisLock)
            {
                if (pool.Close(timeout))
                {
                    List<ConnectionPool> registryEntry = _registry[pool.Name];
                    for (int i = 0; i < registryEntry.Count; i++)
                    {
                        if (object.ReferenceEquals(registryEntry[i], pool))
                        {
                            registryEntry.RemoveAt(i);
                            break;
                        }
                    }

                    if (registryEntry.Count == 0)
                    {
                        _registry.Remove(pool.Name);
                    }
                }
            }
        }
示例#24
0
        bool TransactionRepair(IInfoProvider2 dbq)
        {
            MySqlConnection  connection  = null;
            MySqlTransaction transaction = null;

            try
            {
                connection  = ConnectionPool.Request();
                transaction = connection.BeginTransaction();

                if (!ExistsCharacterEx(connection, dbq))
                {
                    InsertCharacterEx(connection, dbq);
                }
                if (!ExistsAdditionsEx(connection, dbq))
                {
                    InsertAdditionsEx(connection, dbq);
                }
                if (!ExistsEquipmentEx(connection, dbq))
                {
                    InsertEquipmentEx(connection, dbq);
                }
                if (!ExistsInventoryEx(connection, dbq))
                {
                    InsertInventoryEx(connection, dbq);
                }
                if (!ExistsStorageEx(connection, dbq))
                {
                    InsertStorageEx(connection, dbq);
                }
                if (!ExistsJobinformationEx(connection, dbq))
                {
                    InsertJobinformationEx(connection, dbq);
                }
                if (!ExistsWeaponsEx(connection, dbq))
                {
                    InsertWeaponsEx(connection, dbq);
                }
                if (!ExistsZoneEx(connection, dbq))
                {
                    InsertZoneEx(connection, dbq);
                }
                if (!ExistsQuestEx(connection, dbq))
                {
                    InsertQuestEx(connection, dbq);
                }
                if (!ExistsSpecialSkillsEx(connection, dbq))
                {
                    InsertSpecialSkillsEx(connection, dbq);
                }

                transaction.Commit();
                return(true);
            }
            catch (MySqlException ex)
            {
                __dbtracelog.WriteError("database", "Transaction load failed {0}", ex);

                try
                {
                    transaction.Rollback();
                }
                catch (MySqlException)
                {
                    __dbtracelog.WriteError("database", "Transaction failed to roll back");
                }

                return(false);
            }
            catch (Exception ex)
            {
                __dbtracelog.WriteError("database", "Transaction load failed {0}", ex);
                return(false);
            }
            finally
            {
                ConnectionPool.Release(connection);     //Always release connection
            }
        }
示例#25
0
文件: MEDMSql.cs 项目: PANKOVAN/TEST
        public IList Select(IList list, Type t, string sql, params object[] parms)
        {
            SqlConnection con = ConnectionPool.GetConnection();

            try
            {
                parms = GetParamList(parms);
                int             allCount = -1;
                IPaginationList plist    = null;
                if (list is IPaginationList)
                {
                    plist = (IPaginationList)(list);
                }

                DateTime   begtime = DateTime.Now;
                SqlCommand com     = new SqlCommand(sql, con);
                for (int i = 0; i < parms.Length - 1; i += 2)
                {
                    if (parms[i] != null)
                    {
                        com.Parameters.Add(new SqlParameter(parms[i].ToString(), PrepareParam(parms[i + 1])));
                    }
                }
                // Для PaginationList select выполняем в 2 этапа сначала считаем кол-во а потом сам select c добавленным top
                if (plist != null)
                {
                    if (plist.Top != "")
                    {
                        string sql1 = com.CommandText;
                        int    i    = sql1.IndexOf('*');
                        int    j    = sql1.ToLower().IndexOf("order by");
                        if (i > 0 && (j < 0 || i < j))
                        {
                            com.CommandText = sql1.Remove(j).Remove(i, 1).Insert(i, "count(*)");
                            allCount        = Convert.ToInt32(com.ExecuteScalar());
                            com.CommandText = sql1.Insert(i, plist.Top + " ");
                        }
                    }
                }
                bool f = MainDic.ContainsKey(t);
                using (SqlDataReader rdr = com.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        if (plist != null)
                        {
                            if ((plist.AllCount >= plist.StartPos || plist.StartPos == -1) && plist.AllCount < plist.StartPos + plist.PageSize || plist.StartPos == -1 || plist.PageSize == -1)
                            {
                                MObj obj = null;
                                if (f)
                                {
                                    obj = MainDic.CreateObj(t);
                                }
                                else
                                {
                                    obj = Activator.CreateInstance(t) as MObj;
                                    if (obj == null)
                                    {
                                        throw new Exception($@"Тип ""{t}"" не наследует от MObj");
                                    }
                                    obj.Model = this;
                                }
                                SetObjValues(obj, rdr);
                                if (obj is MEDMObj)
                                {
                                    MainDic.AddObj(obj as MEDMObj);
                                }
                                if (list != null)
                                {
                                    list.Add(obj);
                                }
                            }
                            plist.AllCount++;
                        }
                        else
                        {
                            MObj obj = null;
                            if (f)
                            {
                                obj = MainDic.CreateObj(t);
                            }
                            else
                            {
                                obj = Activator.CreateInstance(t) as MObj;
                                if (obj == null)
                                {
                                    throw new Exception($@"Тип ""{t}"" не наследует от MObj");
                                }
                                obj.Model = this;
                            }
                            SetObjValues(obj, rdr);
                            if (obj is MEDMObj)
                            {
                                MainDic.AddObj(obj as MEDMObj);
                            }
                            if (list != null)
                            {
                                list.Add(obj);
                            }
                        }
                    }
                }
                if (plist != null && allCount >= 0)
                {
                    plist.AllCount = allCount;
                }
                MainTrace.Add(TraceType.Sql, $"SELECT => {com.CommandText}");
            }
            finally
            {
                ConnectionPool.FreeConnection(con);
            }
            return(list);
        }
示例#26
0
 private static PooledStream CreateSmtpPooledStream(ConnectionPool pool)
 {
     return((PooledStream) new SmtpPooledStream(pool, TimeSpan.MaxValue, false));
 }
示例#27
0
 public ODatabase(string hostName, int port, string databaseName, ODatabaseType type, string userName, string userPassword, string poolAlias)
 {
     _connectionPool = new ConnectionPool(hostName, port, databaseName, type, userName, userPassword, poolAlias);
     ClientCache     = new ConcurrentDictionary <ORID, ODocument>();
 }
示例#28
0
 /// <summary>
 ///     Creates a new instance of Bucket.
 /// </summary>
 /// <param name="client">The RestClient which created this instance.</param>
 /// <param name="route">The route of the Bucket</param>
 /// <param name="redisPool">The ConnectionPool this Bucket should use</param>
 public RedisBucket(RestClient client, string route, ConnectionPool redisPool)
 {
     RedisPool = redisPool;
     Client    = client;
     Route     = route;
 }
        public void AddOper(Oper opers)
        {
            try
            {
                conn = ConnectionPool.BorrowConnection();

                trans = conn.BeginTransaction();
                DataTable dtOper = SqlHelper.ExecuteDataTable(trans, CommandType.Text, "select * from tbOper where cnvcOperName = '" + opers.cnvcOperName + "'");
                if (dtOper.Rows.Count > 0)
                {
                    throw new BusinessException("操作员管理", "操作员已存在!");
                }
                if (opers.cnvcCardNo.Length > 0)
                {
                    DataTable dtCard = SqlHelper.ExecuteDataTable(trans, CommandType.Text, "select * from tbOper where cnvcCardNo = 'aaa" + opers.cnvcCardNo + "'");
                    if (dtCard.Rows.Count > 0)
                    {
                        throw new BusinessException("操作员管理", "操作员卡号已存在!");
                    }
                    CardM1 m1        = new CardM1();
                    string strReturn = m1.PutOutCard("aaa" + opers.cnvcCardNo);
                    if (strReturn.Equals("OPSUCCESS"))
                    {
                        opers.cnvcCardNo = "aaa" + opers.cnvcCardNo;
                        EntityMapping.Create(opers, trans);
                        trans.Commit();
                    }
                    else
                    {
                        throw new BusinessException("卡操作异常", strReturn);
                    }
                }
                else
                {
                    EntityMapping.Create(opers, trans);
                    trans.Commit();
                }
            }
            catch (BusinessException bex)             //业务异常
            {
                //LogAdapter.WriteBusinessException(bex);
                trans.Rollback();
                throw new BusinessException(bex.Type, bex.Message);
            }
            catch (SqlException sex)               //数据库异常
            {
                //事务回滚
                trans.Rollback();
                //LogAdapter.WriteDatabaseException(sex);
                throw new BusinessException("数据库异常", sex.Message);
            }
            catch (Exception ex)                         //其他异常
            {
                //事务回滚
                trans.Rollback();
                //LogAdapter.WriteFeaturesException(ex);
                throw new BusinessException("其它异常", ex.Message);
            }
            finally
            {
                ConnectionPool.ReturnConnection(conn);
            }
        }
示例#30
0
 public HabboDao(ConnectionPool connectionPool)
 {
     this.connectionPool = connectionPool;
 }
示例#31
0
 internal override sealed string ConstructClassViewString(ClassViewAttribute cva, ConnectionPool pool, QueryBuilder builder, ref List<IDbDataParameter> queryParameters, ref int parCount)
 {
     string ret = FieldName+" ";
     if (FieldValue == null)
     {
         ret += ComparatorString + " " + builder.CreateParameterName("parameter_" + parCount.ToString());
         queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), FieldValue));
         parCount++;
     }
     else if (FieldValue.GetType().IsArray || (FieldValue is ICollection))
     {
         if (SupportsList)
         {
             ret += " " + ComparatorString + " ( ";
             foreach (object obj in (IEnumerable)FieldValue)
             {
                 ret += builder.CreateParameterName("parameter_" + parCount.ToString()) + ",";
                 if (cva.Query.IsEnumField(FieldName))
                     queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), pool.GetEnumID(obj.GetType(), obj.ToString())));
                 else
                     queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), obj));
                 parCount++;
             }
             ret = ret.Substring(0, ret.Length - 1);
             ret += " )";
         }
         else
         {
             string tmp = ret + " " + ComparatorString+" ";
             ret = "(";
             foreach (object obj in (IEnumerable)FieldValue)
             {
                 ret += tmp+builder.CreateParameterName("parameter_" + parCount.ToString()) + " OR ";
                 if (cva.Query.IsEnumField(FieldName))
                     queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), pool.GetEnumID(obj.GetType(), obj.ToString())));
                 else
                     queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), obj));
                 parCount++;
             }
             ret = ret.Substring(0, ret.Length - 3);
             ret += ")";
         }
     }
     else
     {
         ret += ComparatorString + " ";
         ret += builder.CreateParameterName("parameter_" + parCount.ToString());
         if (cva.Query.IsEnumField(FieldName))
             queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), pool.GetEnumID(FieldValue.GetType(), FieldValue.ToString())));
         else
             queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), FieldValue));
         parCount++;
     }
     return ret;
 }
示例#32
0
 private bool _RecurIsPrimaryKeyField(string fieldName, Type tableType,ConnectionPool pool)
 {
     sTable map = pool.Mapping[tableType];
     if (fieldName.Contains("."))
     {
         if (new List<string>(map.PrimaryKeyProperties).Contains(fieldName.Substring(0, fieldName.IndexOf("."))))
         {
             Type newType = tableType.GetProperty(fieldName.Substring(0, fieldName.IndexOf(".")), Utility._BINDING_FLAGS_WITH_INHERITANCE).PropertyType;
             if (newType.IsArray)
                 newType = newType.GetElementType();
             return _RecurIsPrimaryKeyField(fieldName.Substring(fieldName.IndexOf(".") + 1), newType, pool);
         }
     }
     return new List<string>(map.PrimaryKeyProperties).Contains(fieldName);
 }
示例#33
0
 public MySqlSession(ConnectionPool pool)
 {
     Pool = pool;
 }
示例#34
0
        public void DeleteAssignLog(ProduceLog produceLog, OperLog operLog)
        {
            using (SqlConnection conn = ConnectionPool.BorrowConnection())
            {
                SqlTransaction trans = conn.BeginTransaction();
                try
                {
                    string   strSysTime = SqlHelper.ExecuteScalar(trans, CommandType.Text, "select getdate()").ToString();
                    DateTime dtSysTime  = DateTime.Parse(strSysTime);

                    OrderSerialNo serialNo = new OrderSerialNo();
                    serialNo.cnvcFill    = "0";
                    serialNo.cnnSerialNo = Convert.ToDecimal(EntityMapping.Create(serialNo, trans));

                    ProduceLog oldLog = new ProduceLog();
                    oldLog.cnnProduceSerialNo = produceLog.cnnProduceSerialNo;
                    oldLog = EntityMapping.Get(oldLog, trans) as ProduceLog;
                    if (oldLog == null)
                    {
                        throw new Exception("生产计划不存在");
                    }
                    if (oldLog.cnvcProduceState != "6")
                    {
                        throw new Exception("生产计划不在已分货状态,不能清除分货数据");
                    }
                    if (oldLog.cnvcProduceState == "7")
                    {
                        throw new Exception("已分货出库");
                    }
                    oldLog.cnvcOperID  = produceLog.cnvcOperID;
                    oldLog.cndOperDate = dtSysTime;

                    //清除分货数据
                    string strsql = "delete from tbassignlog where cnnproduceserialno=" + produceLog.cnnProduceSerialNo.ToString();
//					DataTable dtal = SqlHelper.ExecuteDataTable(trans,CommandType.Text,strsql);
//					if(dtal.Rows.Count == 0) throw new Exception("未找到分货数据");
//					Entity.AssignLog al = new AssignLog(dtal);
//					EntityMapping.Delete(al,trans);
                    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strsql);

                    strsql = "delete from tbassigndetail where cnnproduceserialno=" + produceLog.cnnProduceSerialNo.ToString();
                    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strsql);
                    strsql = "update tbproducechecklog set cnnassigncount=0 where cnnproduceserialno=" + produceLog.cnnProduceSerialNo.ToString();
                    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strsql);
                    //更新订单生产计划状态
                    string strUpdateOrder = "update tbOrderBook set cnvcOrderState='1' "
                                            +
                                            " where cnnOrderSerialNo in (select cnnOrderSerialNo from tbProduceOrderLog where cnvcType='0' and cnnProduceSerialNo=" + oldLog.cnnProduceSerialNo + ") ";
                    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strUpdateOrder);
                    //更新生产计划状态

                    oldLog.cnvcProduceState = "5";
                    EntityMapping.Update(oldLog, trans);

                    operLog.cndOperDate  = dtSysTime;
                    operLog.cnvcComments = "生产流水:" + produceLog.cnnProduceSerialNo.ToString();
                    EntityMapping.Create(operLog, trans);
                    trans.Commit();
                }
                catch (SqlException sex)
                {
                    trans.Rollback();
                    LogAdapter.WriteDatabaseException(sex);
                    throw sex;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    LogAdapter.WriteFeaturesException(ex);
                    throw ex;
                }
                finally
                {
                    ConnectionPool.ReturnConnection(conn);
                }
            }
        }
示例#35
0
        //入库
        public void ProduceCheck(DataTable dtProduce, OperLog operLog, string strProduceDeptID, string strProduceSerialNo)
        {
            using (SqlConnection conn = ConnectionPool.BorrowConnection())
            {
                //conn.Open();

                SqlTransaction trans = conn.BeginTransaction();
                try
                {
                    string   strSysTime = SqlHelper.ExecuteScalar(trans, CommandType.Text, "select getdate()").ToString();
                    DateTime dtSysTime  = DateTime.Parse(strSysTime);

                    string strComments = "";
                    foreach (DataRow drProduce in dtProduce.Rows)
                    {
                        ProduceCheckLog check = new ProduceCheckLog(drProduce);
                        check.cnvcOperID        = operLog.cnvcOperID;
                        check.cnvcProduceDeptID = strProduceDeptID;
                        check.cndOperDate       = dtSysTime;

                        ProduceCheckLog check2 = new ProduceCheckLog();
                        check2.cnnProduceSerialNo = check.cnnProduceSerialNo;
                        check2.cnvcInvCode        = check.cnvcInvCode;
                        check2 = EntityMapping.Get(check2, trans) as ProduceCheckLog;
                        if (check2 == null)
                        {
                            EntityMapping.Create(check, trans);
                        }
                        else
                        {
                            check2.cnnCheckCount = check.cnnCheckCount;
                            check2.cnvcOperID    = operLog.cnvcOperID;
                            check2.cndOperDate   = dtSysTime;
                            check2.cnnTeamID     = check.cnnTeamID;
                            check2.cnnProducerID = check.cnnProducerID;
                            EntityMapping.Update(check2, trans);
                        }
                        strComments += "[" + check.cnvcInvCode + ":" + check.cnnCheckCount.ToString() + "]";
                    }
                    ProduceLog pl = new ProduceLog();
                    pl.cnnProduceSerialNo = decimal.Parse(strProduceSerialNo);
                    pl = EntityMapping.Get(pl, trans) as ProduceLog;
                    if (pl == null)
                    {
                        throw new Exception("生产数据异常");
                    }
                    pl.cnvcProduceState = "4";
                    pl.cnvcOperID       = operLog.cnvcOperID;
                    pl.cndOperDate      = dtSysTime;
                    EntityMapping.Update(pl, trans);

                    operLog.cndOperDate  = dtSysTime;
                    operLog.cnvcComments = "生产流水:" + strProduceSerialNo + strComments;
                    EntityMapping.Create(operLog, trans);
                    trans.Commit();
                }
                catch (SqlException sex)
                {
                    trans.Rollback();
                    LogAdapter.WriteDatabaseException(sex);
                    throw sex;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    LogAdapter.WriteFeaturesException(ex);
                    throw ex;
                }
                finally
                {
                    ConnectionPool.ReturnConnection(conn);
                }
            }
        }
示例#36
0
        public void AddAssignLog(ProduceLog produceLog, OperLog operLog, string strwhhouse)      //,BusiLog busiLog)
        {
            using (SqlConnection conn = ConnectionPool.BorrowConnection())
            {
                SqlTransaction trans = conn.BeginTransaction();
                try
                {
                    string   strSysTime = SqlHelper.ExecuteScalar(trans, CommandType.Text, "select getdate()").ToString();
                    DateTime dtSysTime  = DateTime.Parse(strSysTime);

                    OrderSerialNo serialNo = new OrderSerialNo();
                    serialNo.cnvcFill    = "0";
                    serialNo.cnnSerialNo = Convert.ToDecimal(EntityMapping.Create(serialNo, trans));

                    ProduceLog oldLog = new ProduceLog();
                    oldLog.cnnProduceSerialNo = produceLog.cnnProduceSerialNo;
                    oldLog = EntityMapping.Get(oldLog, trans) as ProduceLog;
                    if (oldLog == null)
                    {
                        throw new Exception("生产计划不存在");
                    }
                    if (oldLog.cnvcProduceState == "6")
                    {
                        throw new Exception("已分货");
                    }
                    if (oldLog.cnvcProduceState == "7")
                    {
                        throw new Exception("已分货出库");
                    }
                    oldLog.cnvcOperID  = produceLog.cnvcOperID;
                    oldLog.cndOperDate = dtSysTime;

                    AssignLog assign = new AssignLog();
                    assign.cndOperDate        = dtSysTime;
                    assign.cnnAssignSerialNo  = serialNo.cnnSerialNo;
                    assign.cnnProduceSerialNo = oldLog.cnnProduceSerialNo;
                    assign.cnvcShipOperID     = produceLog.cnvcOperID;
                    assign.cnvcShipDeptID     = oldLog.cnvcProduceDeptID;
                    assign.cnvcOperID         = produceLog.cnvcOperID;
                    assign.cndShipDate        = oldLog.cndProduceDate;
                    //订单数据
                    string    strOrderSql       = @"select * from tbOrderBook where cnnOrderSerialNo in 
						(select cnnOrderSerialNo from tbProduceOrderLog where cnnProduceSerialNo="                         + oldLog.cnnProduceSerialNo.ToString() + ")";
                    DataTable dtOrder           = SqlHelper.ExecuteDataTable(trans, CommandType.Text, strOrderSql);
                    string    strOrderDetailSql = @"select * from tbOrderBookDetail where cnnOrderSerialNo in 
						(select cnnOrderSerialNo from tbProduceOrderLog where cnnProduceSerialNo="                         + oldLog.cnnProduceSerialNo.ToString() + ")";
                    DataTable dtOrderDetail     = SqlHelper.ExecuteDataTable(trans, CommandType.Text, strOrderDetailSql);
                    DataTable dtDept            = SingleTableQuery.ExcuteQuery("tbDept", trans);
                    //生产盘点数据
                    string strCheckSql = "select * "
                                         + " from tbProduceCheckLog where cnnProduceSerialNo=" +
                                         oldLog.cnnProduceSerialNo.ToString() + " and cnnCheckCount>0 and cnbInWh=1";
                    DataTable dtProduce = SqlHelper.ExecuteDataTable(trans, CommandType.Text, strCheckSql);
                    #region 分货不按可用量分
                    string strwhsql = "SELECT cnvcinvcode,sum(cnnAvaQuantity) as cnnwhcount FROM tbCurrentStock "
                                      + " WHERE cnvcwhcode='" + strwhhouse + "' AND cnvcStopFlag='0'  and CONVERT(char(10),isnull(cndExpDate,''),121)>=CONVERT(char(10),getdate(),121)  "
                                      + " group by cnvcinvcode";
                    DataTable dtwh = SqlHelper.ExecuteDataTable(trans, CommandType.Text, strwhsql);


                    Helper.DataTableConvert(dtProduce, "cnvcInvCode", "cnnCheckCount", dtwh, "cnvcinvcode", "cnnwhcount", "");
                    #endregion
                    //订单按产品分类汇总
                    //分配 外订订单有限分配
                    Helper.DataTableConvert(dtOrderDetail, "cnnOrderSerialNo", "cnvcOrderType", dtOrder, "cnnOrderSerialNo", "cnvcOrderType", "");
                    Helper.DataTableConvert(dtOrderDetail, "cnnOrderSerialNo", "cnvcOrderDeptID", dtOrder, "cnnOrderSerialNo", "cnvcOrderDeptID", "");
                    Helper.DataTableConvert(dtOrderDetail, "cnnOrderSerialNo", "cndShipDate", dtOrder, "cnnOrderSerialNo", "cndShipDate", "");
                    Helper.DataTableConvert(dtOrderDetail, "cnvcOrderDeptID", "cnnPriority", dtDept, "cnvcDeptID", "cnnPriority", "");
                    //
                    dtOrderDetail.Columns.Add("cnnAssignCount");
                    foreach (DataRow dr in dtOrderDetail.Rows)
                    {
                        dr["cnnAssignCount"] = 0;
                    }

                    DataView dvOrder = new DataView(dtOrderDetail);
                    dvOrder.Sort = "cnvcOrderType desc,cnnPriority asc,cnnOrderSerialNo asc";
                    Hashtable hOrderSerialNo = new Hashtable();
                    foreach (DataRowView dv in dvOrder)
                    {
                        string  strOrderSerialNo = dv["cnnOrderSerialNo"].ToString();
                        string  strProductCode   = dv["cnvcInvCode"].ToString();
                        string  strOrderCount    = dv["cnnOrderCount"].ToString();
                        string  strAssignCount   = dv["cnnAssignCount"].ToString();
                        decimal dOrderCount      = decimal.Parse(strOrderCount);
                        decimal dAssignCount     = Convert.ToDecimal(strAssignCount);
                        string  strOrderType     = dv["cnvcOrderType"].ToString();

                        DataRow[] drProduces = dtProduce.Select("cnvcInvCode='" + strProductCode + "'");
                        if (drProduces.Length == 0)
                        {
                            continue;                                                //throw new Exception(strProductCode+"无可分货量");
                        }
                        //						if(drProduces.Length > 0)
                        //						{

                        DateTime dtMDate      = Convert.ToDateTime(drProduces[0]["cndMDate"].ToString());
                        DateTime dtExpDate    = Convert.ToDateTime(drProduces[0]["cndExpDate"].ToString());
                        string   strSumCount  = drProduces[0]["cnnCheckCount"].ToString();
                        decimal  dSumCount    = decimal.Parse(strSumCount);
                        string   strSumAssign = drProduces[0]["cnnAssignCount"].ToString();
                        decimal  dSumAssign   = decimal.Parse(strSumAssign);
                        //if(dSumCount <=0) throw new Exception(strProductCode+"无可分货量");
                        //						if(dSumCount > 0)
                        //						{
                        AssignDetail assignDetail = new AssignDetail();
                        assignDetail.cnnAssignSerialNo  = assign.cnnAssignSerialNo;
                        assignDetail.cnnProduceSerialNo = assign.cnnProduceSerialNo;
                        assignDetail.cnnOrderSerialNo   = decimal.Parse(strOrderSerialNo);
                        assignDetail.cnvcInvCode        = strProductCode;
                        assignDetail.cndMdate           = dtMDate;
                        assignDetail.cndExpDate         = dtExpDate;

                        if (dSumCount >= dOrderCount - dAssignCount)
                        {
                            assignDetail.cnnOrderCount      = dOrderCount;
                            assignDetail.cnnAssignCount     = dOrderCount - dAssignCount;
                            drProduces[0]["cnnCheckCount"]  = dSumCount - dOrderCount + dAssignCount;
                            drProduces[0]["cnnAssignCount"] = dSumAssign + dOrderCount - dAssignCount;
                        }
                        else
                        {
                            if (strOrderType == "WDO" || strOrderType == "WDOSELF")
                            {
                                throw new Exception("订单流水为" + dv["cnnOrderSerialNo"].ToString() + "的外订定单" + strProductCode + "不能满足分配");
                            }
                            assignDetail.cnnOrderCount      = dOrderCount;
                            assignDetail.cnnAssignCount     = dSumCount;
                            drProduces[0]["cnnCheckCount"]  = 0;
                            drProduces[0]["cnnAssignCount"] = dSumAssign + dSumCount;
                        }

                        EntityMapping.Create(assignDetail, trans);
                        if (!hOrderSerialNo.Contains(dv["cnnOrderSerialNo"].ToString()))
                        {
                            hOrderSerialNo.Add(dv["cnnOrderSerialNo"].ToString(), dv["cnnOrderSerialNo"].ToString());
                            assign.cnnOrderSerialNo  = decimal.Parse(dv["cnnOrderSerialNo"].ToString());
                            assign.cnvcReceiveDeptID = dv["cnvcOrderDeptID"].ToString();
                            assign.cndShipDate       = DateTime.Parse(dv["cndShipDate"].ToString());
                            EntityMapping.Create(assign, trans);
                        }

                        //								string strOrderBookDetail = "update tbOrderBookDetail set cnnAssignCount="+Convert.ToString(assignDetail.cnnAssignCount+dAssignCount)+" where cnnOrderSerialNo="+strOrderSerialNo+" and cnvcProductCode='"+strProductCode+"'";
                        //								SqlHelper.ExecuteNonQuery(trans,CommandType.Text,strOrderBookDetail);
                        //						}



                        //						}
                    }
                    foreach (DataRow drProduce in dtProduce.Rows)
                    {
                        ProduceCheckLog check  = new ProduceCheckLog(drProduce);
                        string          strSql = "update tbProduceCheckLog set cnnAssignCount=" + check.cnnAssignCount.ToString() + " where cnnProduceSerialNo=" + check.cnnProduceSerialNo.ToString() + " and cnvcInvCode='" + check.cnvcInvCode + "'";
                        SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql);
                    }
                    //更新订单生产计划状态
                    string strUpdateOrder = "update tbOrderBook set cnvcOrderState='2' "
                                            +
                                            " where cnnOrderSerialNo in (select cnnOrderSerialNo from tbProduceOrderLog where cnvcType='0' and cnnProduceSerialNo=" + oldLog.cnnProduceSerialNo + ") ";
                    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strUpdateOrder);
                    //更新生产计划状态

                    oldLog.cnvcProduceState = "6";
                    EntityMapping.Update(oldLog, trans);

                    operLog.cndOperDate  = dtSysTime;
                    operLog.cnvcComments = "分货流水:" + produceLog.cnnProduceSerialNo.ToString();
                    EntityMapping.Create(operLog, trans);
                    trans.Commit();
                }
                catch (SqlException sex)
                {
                    trans.Rollback();
                    LogAdapter.WriteDatabaseException(sex);
                    throw sex;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    LogAdapter.WriteFeaturesException(ex);
                    throw ex;
                }
                finally
                {
                    ConnectionPool.ReturnConnection(conn);
                }
            }
        }
        public string OperCardCallBack(string strOperName)
        {
            string strRet3 = "";

            try
            {
                conn  = ConnectionPool.BorrowConnection();
                trans = conn.BeginTransaction();
                CardM1 m1        = new CardM1();
                string strCardNo = "";
                string strRet    = m1.ReadCard(out strCardNo);             //,out dtemp,out itemp);

                if (strRet != ConstMsg.RFOK)
                {
                    strRet3 += " 读卡失败";
                }
                DataTable dtOper = SqlHelper.ExecuteDataTable(trans, CommandType.Text, "select * from tbOper where cnvcCardNo is not null and cnvcCardNo='" + strCardNo + "'");

                if (dtOper.Rows.Count == 0)
                {
                    strRet3 += " 操作员不存在";
                }
                else
                {
                    Oper oldOper = new Oper(dtOper);
                    oldOper.cnvcCardNo = "";
                    EntityMapping.Update(oldOper, trans);
                    //流水
                    SeqSerialNo serial = new SeqSerialNo();
                    serial.cnvcFill = "0";
                    decimal dSerialNo = EntityMapping.Create(serial, trans);

                    //操作日志
                    OperLog operLog = new OperLog();
                    operLog.cnnSerialNo  = dSerialNo;
                    operLog.cnvcOperName = strOperName;                    //member.cnvcOperName;
                    operLog.cndOperDate  = DateTime.Now;
                    operLog.cnvcOperFlag = ConstApp.Oper_Flag_OperInCallBack;
                    EntityMapping.Create(operLog, trans);
                }
                trans.Commit();
                string strRet2 = m1.RecycleCard();
                if (strRet != ConstMsg.RFOK)
                {
                    strRet3 += " 操作员卡回收失败";
                }
            }
            catch (BusinessException bex)             //业务异常
            {
                //事务回滚
                trans.Rollback();
                //LogAdapter.WriteBusinessException(bex);
                throw new BusinessException(bex.Type, bex.Message);
            }
            catch (SqlException sex)               //数据库异常
            {
                //事务回滚
                trans.Rollback();
                //LogAdapter.WriteDatabaseException(sex);
                throw new BusinessException("数据库异常", sex.Message);
            }
            catch (Exception ex)                         //其他异常
            {
                //事务回滚
                trans.Rollback();
                //LogAdapter.WriteFeaturesException(ex);
                throw new BusinessException("其它异常", ex.Message);
            }
            finally
            {
                ConnectionPool.ReturnConnection(conn);
            }
            return(strRet3);
        }
示例#38
0
        private void Export_Click(object sender, RoutedEventArgs e)
        {
            var Connection = ConnectionPool.TryGetConnection();
            //实例化基本信息服务,传入连接对象
            HistorianImpl historian = new HistorianImpl(Connection);

            DataTable dt = new DataTable();

            dt.Columns.Add("时间", typeof(String));
            //列
            foreach (MemberChoice member in Data.memberDataChoice)
            {
                dt.Columns.Add(member.NameChoice, typeof(String));
            }
            //行
            if (Data.memberDataChoice[0].Entity.ToString() == "REAL32")
            {
                try
                {
                    Entity <FloatData> entitylist = historian.GetFloatArchivedValues(Convert.ToInt32(Data.memberDataChoice[0].IDChoice),
                                                                                     10000,
                                                                                     Convert.ToDateTime(this.DatePckerStart.Value),
                                                                                     Convert.ToDateTime(this.DatePickerEnd.Value));
                    foreach (FloatData floatData in entitylist.Data)
                    {
                        dt.Rows.Add("[" + floatData.Time.ToString("yyyy-MM-dd HH:mm:ss") + "." + floatData.Ms.ToString().PadLeft(3, '0') + "]", floatData.Value);
                    }
                } catch { }
            }
            if (Data.memberDataChoice[0].Entity.ToString() == "BOOL")
            {
                try
                {
                    Entity <IntData> entitylist = historian.GetIntArchivedValues(Convert.ToInt32(Data.memberDataChoice[0].IDChoice),
                                                                                 10000,
                                                                                 Convert.ToDateTime(this.DatePckerStart.Value),
                                                                                 Convert.ToDateTime(this.DatePickerEnd.Value));
                    foreach (IntData intData in entitylist.Data)
                    {
                        dt.Rows.Add("[" + intData.Time.ToString("yyyy-MM-dd/HH:mm:ss") + "." + intData.Ms.ToString().PadLeft(3, '0') + "]", intData.Value);
                    }
                } catch { }
            }
            //查出数据
            for (int i = 1; i < Data.memberDataChoice.Count; i++)
            {
                if (Data.memberDataChoice[i].Entity.ToString() == "REAL32")
                {
                    try
                    {
                        Entity <FloatData> entitylist = historian.GetFloatArchivedValues(Convert.ToInt32(Data.memberDataChoice[i].IDChoice),
                                                                                         10000,
                                                                                         Convert.ToDateTime(this.DatePckerStart.Value),
                                                                                         Convert.ToDateTime(this.DatePickerEnd.Value));
                        for (int j = 0; j < entitylist.Count; j++)
                        {
                            dt.Rows[j][Data.memberDataChoice[i].NameChoice] = entitylist.Data[j].Value;
                        }
                    } catch { }
                }
                if (Data.memberDataChoice[i].Entity.ToString() == "BOOL")
                {
                    try
                    {
                        Entity <IntData> entitylist = historian.GetIntArchivedValues(Convert.ToInt32(Data.memberDataChoice[i].IDChoice),
                                                                                     10000,
                                                                                     Convert.ToDateTime(this.DatePckerStart.Value),
                                                                                     Convert.ToDateTime(this.DatePickerEnd.Value));
                        for (int j = 0; j < entitylist.Count; j++)
                        {
                            dt.Rows[j][Data.memberDataChoice[i].NameChoice] = entitylist.Data[j].Value;
                        }
                    } catch { }
                }
            }
            //导出csv
            string FilePath = System.Environment.CurrentDirectory + "\\data" + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";

            this.CreateCSVWithCommaByDataTableAndFilePath(dt, FilePath);
        }
 internal EapConnection(ConnectionPool <EapConnection> connectionPool, Socket socket, IByteConverter converter)
     : this(connectionPool, socket, new NetworkStream(socket), converter)
 {
 }
示例#40
0
        public void BOSMOD(Entity.BillOfOutStorage bos, Entity.BusiLog bl, bool isHis)
        {
            ConnectionPool.IsCenter = false;
            using (SqlConnection conn = ConnectionPool.BorrowConnection())
            {
                //conn.Open();
                SqlTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);
                try
                {
                    string   strSysTime = SqlHelper.ExecuteScalar(trans, CommandType.Text, "select getdate()").ToString();
                    DateTime dtSysTime  = DateTime.Parse(strSysTime);

                    Entity.OilStorage os = new OilStorage(bl.ToTable());
                    os.cnvcGoodsName = bos.cnvcGoodsName;
                    os.cnvcGoodsType = bos.cnvcGoodsType;
                    os = EntityMapping.Get(os, trans) as OilStorage;
                    if (null == os)
                    {
                        throw new BusinessException(bexType.noobject, "库存获取错误");
                    }

                    Guid gd = Guid.NewGuid();

                    //判断修改操作类型 改多为入库 改少为出库
                    Entity.BillOfOutStorage oldbos = new BillOfOutStorage(bos.GetOriginalValue());
                    string strOperType             = "";
                    if (oldbos.cnnCount > bos.cnnCount)
                    {
                        strOperType = OutType.BOSIn;
                    }
                    else
                    {
                        strOperType = OutType.BOSOut;
                    }

                    //验收单
                    //bos.cnvcInType = strOperType;
                    bos.cndOperDate = dtSysTime;
                    if (isHis)
                    {
                        Entity.BillOfOutStorageHis boshis = new BillOfOutStorageHis(bos.GetOriginalValue());
                        EntityMapping.Delete(boshis, trans);

                        //boshis.SynchronizeModifyValue(bos);
                        EntityMapping.Create(bos, trans);
                    }
                    else
                    {
                        EntityMapping.Update(bos, trans);
                    }
                    if (bos.cnnCount != oldbos.cnnCount)
                    {
                        //库存日志
                        Entity.OilStorageLog ol = new OilStorageLog(bos.ToTable());
                        ol.cnvcDeptName  = bl.cnvcDeptName;
                        ol.cnvcOperType  = strOperType;
                        ol.cnnSerial     = gd;
                        ol.cnnLastCount  = os.cnnStorageCount;
                        ol.cnnInOutCount = oldbos.cnnCount - bos.cnnCount;                      //bos.cnnCount-oldbos.cnnCount;
                        ol.cnnCurCount   = os.cnnStorageCount + oldbos.cnnCount - bos.cnnCount;
                        EntityMapping.Create(ol, trans);

                        //库存
                        os.cnnStorageCount = ol.cnnCurCount;
                        EntityMapping.Update(os, trans);
                    }
                    //日志
                    bl.cnnSerial    = gd;
                    bl.cnvcComments = "出库单修改,出入库量:" + (oldbos.cnnCount - bos.cnnCount);                //(bos.cnnCount-oldbos.cnnCount);
                    bl.cnvcOperType = OperType.OP202;
                    bl.cndOperDate  = dtSysTime;
                    bl.cnvcSource   = InSource.cs;
                    EntityMapping.Create(bl, trans);

                    trans.Commit();
                }
                catch (BusinessException bex)
                {
                    trans.Rollback();
                    LogAdapter.WriteBusinessException(bex);
                    throw bex;
                }
                catch (SqlException sex)
                {
                    trans.Rollback();
                    LogAdapter.WriteDatabaseException(sex);
                    throw sex;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    LogAdapter.WriteFeaturesException(ex);
                    throw ex;
                }
                finally
                {
                    ConnectionPool.ReturnConnection(conn);
                }
            }
        }
示例#41
0
 protected virtual IModel CreateChannel(string channelName, string connectionName)
 {
     return(ConnectionPool
            .Get(connectionName)
            .CreateModel());
 }
示例#42
0
 public PooledSqliteConnection(ConnectionPool connectionPool, string filePath) : base(connectionPool)
 {
     FilePath = filePath;
     FileTime = File.GetLastWriteTime(FilePath);
 }
示例#43
0
 public ODatabase(ConnectionOptions options)
 {
     _connectionPool = new ConnectionPool(options.HostName, options.Port, options.DatabaseName, options.DatabaseType, options.UserName, options.Password, options.PoolAlias);
     ClientCache     = new ConcurrentDictionary <ORID, ODocument>();
 }
            private FastQuery CreateIncrementCounterQuery(SqliteConnection connection, ConnectionPool pool)
            {
                var sql = $"UPDATE {MetadataTable} SET `Counter` = `Counter` + 1 " +
                          $"WHERE `PK` = @Pk";
                var fq = new FastQuery(sql, connection, pool);

                return(fq);
            }
示例#45
0
        internal void GetConnection(ServicePoint servicePoint)
        {
            if (isConnected)
            {
                throw new InvalidOperationException(SR.GetString(SR.SmtpAlreadyConnected));
            }

            if (Logging.On)
            {
                Logging.Associate(Logging.Web, this, servicePoint);
            }
            Debug.Assert(servicePoint != null, "servicePoint was null from SmtpTransport");
            connectionPool = ConnectionPoolManager.GetConnectionPool(servicePoint, "", m_CreateConnectionCallback);

            PooledStream pooledStream = connectionPool.GetConnection((object)this, null, Timeout);

            while (((SmtpPooledStream)pooledStream).creds != null && ((SmtpPooledStream)pooledStream).creds != credentials)
            {
                // destroy this connection so that a new connection can be created
                // in order to use the proper credentials.  Do not just close the
                // connection since it's in a state where a QUIT could be sent
                connectionPool.PutConnection(pooledStream, pooledStream.Owner, Timeout, false);
                pooledStream = connectionPool.GetConnection((object)this, null, Timeout);
            }
            if (Logging.On)
            {
                Logging.Associate(Logging.Web, this, pooledStream);
            }

            lock (this) {
                this.pooledStream = pooledStream;
            }

            ((SmtpPooledStream)pooledStream).creds = credentials;

            responseReader = new SmtpReplyReaderFactory(pooledStream.NetworkStream);

            //set connectionlease
            pooledStream.UpdateLifetime();

            //if the stream was already used, then we've already done the handshake
            if (((SmtpPooledStream)pooledStream).previouslyUsed == true)
            {
                isConnected = true;
                return;
            }

            LineInfo info = responseReader.GetNextReplyReader().ReadLine();

            switch (info.StatusCode)
            {
            case SmtpStatusCode.ServiceReady:
            {
                break;
            }

            default:
            {
                throw new SmtpException(info.StatusCode, info.Line, true);
            }
            }

            try
            {
                extensions = EHelloCommand.Send(this, client.clientDomain);
                ParseExtensions(extensions);
            }
            catch (SmtpException e)
            {
                if ((e.StatusCode != SmtpStatusCode.CommandUnrecognized) &&
                    (e.StatusCode != SmtpStatusCode.CommandNotImplemented))
                {
                    throw e;
                }

                HelloCommand.Send(this, client.clientDomain);
                //if ehello isn't supported, assume basic login
                supportedAuth = SupportedAuth.Login;
            }

#if !FEATURE_PAL
            // Establish TLS
            if (enableSsl)
            {
                if (!serverSupportsStartTls)
                {
                    // Either TLS is already established or server does not support TLS
                    if (!(pooledStream.NetworkStream is TlsStream))
                    {
                        throw new SmtpException(SR.GetString(SR.MailServerDoesNotSupportStartTls));
                    }
                }
                StartTlsCommand.Send(this);
                TlsStream TlsStream = new TlsStream(servicePoint.Host, pooledStream.NetworkStream, clientCertificates, servicePoint, client, null);

                pooledStream.NetworkStream = TlsStream;

                //for SMTP, the CBT should be unique
                this.channelBindingToken = TlsStream.GetChannelBinding(ChannelBindingKind.Unique);

                responseReader = new SmtpReplyReaderFactory(pooledStream.NetworkStream);

                // According to RFC 3207: The client SHOULD send an EHLO command
                // as the first command after a successful TLS negotiation.
                extensions = EHelloCommand.Send(this, client.clientDomain);
                ParseExtensions(extensions);
            }
#endif // !FEATURE_PAL

            //if no credentials were supplied, try anonymous
            //servers don't appear to anounce that they support anonymous login.
            if (credentials != null)
            {
                for (int i = 0; i < authenticationModules.Length; i++)
                {
                    //only authenticate if the auth protocol is supported  - [....]
                    if (!AuthSupported(authenticationModules[i]))
                    {
                        continue;
                    }

                    NetworkCredential credential = credentials.GetCredential(servicePoint.Host,
                                                                             servicePoint.Port, authenticationModules[i].AuthenticationType);
                    if (credential == null)
                    {
                        continue;
                    }

                    Authorization auth = SetContextAndTryAuthenticate(authenticationModules[i], credential, null);

                    if (auth != null && auth.Message != null)
                    {
                        info = AuthCommand.Send(this, authenticationModules[i].AuthenticationType, auth.Message);

                        if (info.StatusCode == SmtpStatusCode.CommandParameterNotImplemented)
                        {
                            continue;
                        }

                        while ((int)info.StatusCode == 334)
                        {
                            auth = authenticationModules[i].Authenticate(info.Line, null, this, this.client.TargetName, this.channelBindingToken);
                            if (auth == null)
                            {
                                throw new SmtpException(SR.GetString(SR.SmtpAuthenticationFailed));
                            }
                            info = AuthCommand.Send(this, auth.Message);

                            if ((int)info.StatusCode == 235)
                            {
                                authenticationModules[i].CloseContext(this);
                                isConnected = true;
                                return;
                            }
                        }
                    }
                }
            }
            isConnected = true;
        }
            private FastQuery CreateGetExactMetadataQuery(SqliteConnection connection, ConnectionPool pool)
            {
                var sql = $"SELECT * " +
                          $"from {MetadataTable} " +
                          $"WHERE `PK` = @Pk";
                // TODO optional params via coalesce
                var fq = new FastQuery(sql, connection, pool);

                return(fq);
            }
示例#47
0
 public MySqlSession(ConnectionPool pool, int poolGeneration)
 {
     Pool           = pool;
     PoolGeneration = poolGeneration;
 }
            private FastQuery CreateInsertMetadataRowQuery(SqliteConnection connection, ConnectionPool pool)
            {
#pragma warning disable HAA0201 // Implicit string concatenation allocation
                var sql = $"INSERT INTO {MetadataTable} " +
                          $"(`PK`, `RepoId`, `ContainerId`, `ParentId`, `Counter`, `Version`, `RemoteId`, `Permissions`, `SchemaType`, `Schema`, `Metadata`) " +
                          $"VALUES (@PK, @RepoId, @ContainerId, @ParentId, @Counter, @Version, @RemoteId, @Permissions, @SchemaType, @Schema, @Metadata)";
                var fq = new FastQuery(sql, connection, pool);
                return(fq);
            }
示例#49
0
        public void UpdateAssignLog(AssignDetail detail, OperLog operLog)
        {
            using (SqlConnection conn = ConnectionPool.BorrowConnection())
            {
                SqlTransaction trans = conn.BeginTransaction();
                try
                {
                    string   strSysTime = SqlHelper.ExecuteScalar(trans, CommandType.Text, "select getdate()").ToString();
                    DateTime dtSysTime  = DateTime.Parse(strSysTime);


                    Entity.ProduceCheckLog pcl = new ProduceCheckLog();
                    pcl.cnnProduceSerialNo = detail.cnnProduceSerialNo;
                    pcl.cnvcInvCode        = detail.cnvcInvCode;
                    pcl = EntityMapping.Get(pcl, trans) as ProduceCheckLog;
                    if (pcl == null)
                    {
                        throw new Exception("无法定位生产");
                    }

                    AssignDetail detailOld = EntityMapping.Get(detail, trans) as AssignDetail;


                    pcl.cnnAssignCount = pcl.cnnAssignCount + detail.cnnAssignCount - detailOld.cnnAssignCount;
                    EntityMapping.Update(pcl, trans);

//					if(detail.cnnAssignCount != detailOld.cnnAssignCount)
//					{

//						OrderSerialNo serialNo = new OrderSerialNo();
//						serialNo.cnvcFill = "0";
//						serialNo.cnnSerialNo = Convert.ToDecimal(EntityMapping.Create(serialNo, trans));
                    string strComments = "";
                    detailOld.cnnAssignCount = detail.cnnAssignCount;
                    EntityMapping.Update(detailOld, trans);
                    strComments = "[" + detail.cnvcInvCode + ":" + detail.cnnAssignCount + "]";
                    //}

                    operLog.cndOperDate  = dtSysTime;
                    operLog.cnvcComments = "分货流水:" + detail.cnnAssignSerialNo.ToString() + strComments;
                    EntityMapping.Create(operLog, trans);

                    trans.Commit();
                }
                catch (SqlException sex)
                {
                    trans.Rollback();
                    LogAdapter.WriteDatabaseException(sex);
                    throw sex;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    LogAdapter.WriteFeaturesException(ex);
                    throw ex;
                }
                finally
                {
                    ConnectionPool.ReturnConnection(conn);
                }
            }
        }
示例#50
0
        /// <summary>
        /// When overridden in the derived class, removes all of the primary keys from a table where there is no foreign keys for the
        /// respective primary key.
        /// For safety reasons, if a column has no foreign keys, the query will be aborted.
        /// </summary>
        /// <param name="schema">The schema or database name of the table.</param>
        /// <param name="table">The table to check.</param>
        /// <param name="column">The primary key column.</param>
        /// <returns>The number of rows removed, or -1 if there were no foreign keys for the given column in the first place.</returns>
        public override int RemoveUnreferencedPrimaryKeys(string schema, string table, string column)
        {
            // How many keys to grab at a time. Larger value = greater memory usage, but fewer queries.
            const int batchSize = 4192;

            var ret = 0;

            // Get all of the fully-qualified foreign key columns
            var foreignKeys = GetPrimaryKeyReferences(schema, table, column);

            if (foreignKeys.IsEmpty())
            {
                const string errmsg = "Aborted RemoveUnreferencedPrimaryKeys on {0}.{1}.{2} - no foreign key references found.";
                if (log.IsWarnEnabled)
                {
                    log.WarnFormat(errmsg, schema, table, column);
                }
                return(-1);
            }

            // Grab a raw database connection so we can execute queries directly
            using (var pconn = ConnectionPool.Acquire())
            {
                var conn = pconn.Connection;

                var       fkCmds     = new List <DbCommand>();
                DbCommand grabPKsCmd = null;
                DbCommand deleteCmd  = null;

                // Find the number of rows in the table
                int numRows;
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = string.Format("SELECT COUNT(*) FROM {0}.{1}", schema, table);
                    using (var r = cmd.ExecuteReader(CommandBehavior.SingleResult))
                    {
                        if (!r.Read())
                        {
                            const string errmsg = "Failed to read result for query: {0}";
                            if (log.IsErrorEnabled)
                            {
                                log.ErrorFormat(errmsg, cmd.CommandText);
                            }
                            Debug.Fail(string.Format(errmsg, cmd.CommandText));
                            return(0);
                        }

                        numRows = r.GetInt32(0);
                    }
                }

                if (numRows == 0)
                {
                    return(0);
                }

                try
                {
                    /* CREATE THE COMMANDS */

                    // Create the command to grab the primary keys
                    grabPKsCmd             = conn.CreateCommand();
                    grabPKsCmd.CommandText = string.Format("SELECT `{0}` FROM {1}.{2} LIMIT @low, @high", column, schema, table);

                    var grabPKsParamLow = grabPKsCmd.CreateParameter();
                    grabPKsParamLow.ParameterName = "@low";
                    grabPKsCmd.Parameters.Add(grabPKsParamLow);

                    var grabPKsParamHigh = grabPKsCmd.CreateParameter();
                    grabPKsParamHigh.ParameterName = "@high";
                    grabPKsCmd.Parameters.Add(grabPKsParamHigh);

                    // Create the command for deleting the row
                    deleteCmd             = conn.CreateCommand();
                    deleteCmd.CommandText = string.Format("DELETE FROM {0}.{1} WHERE `{2}` = @value", schema, table, column);

                    var deleteParam = deleteCmd.CreateParameter();
                    deleteParam.ParameterName = "@value";
                    deleteCmd.Parameters.Add(deleteParam);

                    // Create a command for each of the individual foreign key references
                    foreach (var fk in foreignKeys)
                    {
                        var cmd = conn.CreateCommand();
                        cmd.CommandText = string.Format("SELECT COUNT(*) FROM {0}.{1} WHERE `{2}`=@value", fk.Schema, fk.Table,
                                                        fk.Column);

                        var p = cmd.CreateParameter();
                        p.ParameterName = "@value";
                        cmd.Parameters.Add(p);

                        fkCmds.Add(cmd);
                    }

                    /* SEARCH AND DESTROY */

                    // Loop as many times as we need for each batch to run
                    var rowsLow = 0;
                    while (rowsLow < numRows)
                    {
                        // Grab all the primary key values for this batch
                        var primaryKeys = new List <object>();
                        grabPKsCmd.Parameters["@low"].Value  = rowsLow;
                        grabPKsCmd.Parameters["@high"].Value = batchSize;

                        using (var r = grabPKsCmd.ExecuteReader())
                        {
                            while (r.Read())
                            {
                                primaryKeys.Add(r[0]);
                            }
                        }

                        // Loop though each primary key value
                        foreach (var pk in primaryKeys)
                        {
                            var pkInUse = false;

                            // Loop through each queries for the foreign keys
                            foreach (var cmd in fkCmds)
                            {
                                // Set the value to look for equal to that of our primary key
                                cmd.Parameters[0].Value = pk;

                                // Execute the query to see if there is any usages of the primary key
                                using (var r = cmd.ExecuteReader(CommandBehavior.SingleResult))
                                {
                                    if (!r.Read())
                                    {
                                        const string errmsg = "Failed to read result for query: {0}";
                                        if (log.IsErrorEnabled)
                                        {
                                            log.ErrorFormat(errmsg, cmd.CommandText);
                                        }
                                        Debug.Fail(string.Format(errmsg, cmd.CommandText));

                                        // When we fail to read the result, completely skip this value just in case
                                        // there is something wrong. Safer to not delete than to delete.
                                        pkInUse = true;
                                        break;
                                    }

                                    var count = r.GetInt32(0);
                                    if (count > 0)
                                    {
                                        pkInUse = true;
                                    }
                                }

                                if (pkInUse)
                                {
                                    break;
                                }
                            }

                            // If the primary key is not in use, delete it
                            if (!pkInUse)
                            {
                                const string msg = "Deleting pk `{0}` from {1}.{2}.";
                                if (log.IsDebugEnabled)
                                {
                                    log.DebugFormat(msg, pk, schema, table);
                                }

                                deleteCmd.Parameters[0].Value = pk;
                                var rowsDeleted = deleteCmd.ExecuteNonQuery();
                                Debug.Assert(rowsDeleted == 0 || rowsDeleted == 1);

                                ret += rowsDeleted;

                                // Adjust the row count since we did just delete a row
                                numRows -= rowsDeleted;
                                rowsLow -= rowsDeleted;
                            }
                        }

                        // Move down to the next batch
                        rowsLow += batchSize;
                    }
                }
                finally
                {
                    // Release the commands
                    if (deleteCmd != null)
                    {
                        deleteCmd.Dispose();
                    }

                    if (grabPKsCmd != null)
                    {
                        grabPKsCmd.Dispose();
                    }

                    foreach (var cmd in fkCmds)
                    {
                        cmd.Dispose();
                    }
                }
            }

            if (log.IsInfoEnabled)
            {
                log.InfoFormat("Deleted {0} unreferenced rows from {1}.{2} using column {3}.", ret, schema, table, column);
            }

            return(ret);
        }
示例#51
0
 private string _RecurLocateTranslatePrimaryKeyField(string fieldName, Type tableType, ConnectionPool pool)
 {
     string ret = "";
     sTable map = pool.Mapping[tableType];
     if (fieldName.Contains("."))
     {
         Type newType = tableType.GetProperty(fieldName.Substring(0, fieldName.IndexOf(".")), Utility._BINDING_FLAGS_WITH_INHERITANCE).PropertyType;
         if (newType.IsArray)
             newType = newType.GetElementType();
         foreach (sTableField fld in map[fieldName.Substring(0, fieldName.IndexOf("."))])
         {
             if (fld.ExternalField == _RecurLocateTranslatePrimaryKeyField(fieldName.Substring(fieldName.IndexOf(".") + 1), newType, pool))
             {
                 ret = fld.Name;
                 break;
             }
         }
     }
     else
         ret = map[fieldName][0].Name;
     return ret;
 }
示例#52
0
        public void AssignOut(string strProduceSerialNo, OperLog operLog, string strWarehouse)
        {
            using (SqlConnection conn = ConnectionPool.BorrowConnection())
            {
                //conn.Open();

                SqlTransaction trans = conn.BeginTransaction();
                try
                {
                    string   strSysTime = SqlHelper.ExecuteScalar(trans, CommandType.Text, "select getdate()").ToString();
                    DateTime dtSysTime  = DateTime.Parse(strSysTime);

                    string    strsql1      = "SELECT * FROM tbProduceLog WHERE cnvcProduceState='6' and cnnProduceSerialNo=" + strProduceSerialNo;
                    DataTable dtProduceLog = SqlHelper.ExecuteDataTable(trans, CommandType.Text, strsql1);
                    //rr.cndMakeDate = dtSysTime;
                    //EntityMapping.Create(rr,trans);
                    if (dtProduceLog.Rows.Count == 0)
                    {
                        throw new Exception("生产计划不在分货状态!");
                    }
                    Entity.ProduceLog pl = new ProduceLog(dtProduceLog);

                    string    strsql2           = "select * from tbproducechecklog WHERE cnnAssignCount>0 and cnnproduceserialno=" + strProduceSerialNo;
                    DataTable dtProduceCheckLog = SqlHelper.ExecuteDataTable(trans, CommandType.Text, strsql2);
                    if (dtProduceCheckLog.Rows.Count == 0)
                    {
                        throw new Exception("分货出库产品数量都为0");
                    }

                    DataTable dtInv             = SingleTableQuery.ExcuteQuery("tbInventory", trans);
                    DataTable dtComputationUnit = SingleTableQuery.ExcuteQuery("tbComputationUnit", trans);

                    string    strsql3     = "select * from tbassignlog where cnnproduceserialno=" + strProduceSerialNo;
                    DataTable dtAssignLog = SqlHelper.ExecuteDataTable(trans, CommandType.Text, strsql3);
                    if (dtAssignLog.Rows.Count == 0)
                    {
                        throw new Exception("未找到分货流水");
                    }
                    Entity.AssignLog al = new AssignLog(dtAssignLog);

                    Entity.RdRecord rr = new RdRecord();
                    rr.cnvcRdCode = "RD010";
                    rr.cnvcRdFlag = "0";
                    rr.cnvcWhCode = strWarehouse;
                    rr.cnvcDepID  = pl.cnvcProduceDeptID;
                    //rr.cnvcOperName = operLog.cnvcop
                    rr.cnvcComments  = "分货出库";
                    rr.cnvcMaker     = operLog.cnvcOperID;
                    rr.cnnProorderID = pl.cnnProduceSerialNo;
                    rr.cnvcState     = "2";
                    rr.cndMakeDate   = dtSysTime;
                    long rrid = EntityMapping.Create(rr, trans);

                    foreach (DataRow drProduceCheckLog in dtProduceCheckLog.Rows)
                    {
                        Entity.ProduceCheckLog pcl = new ProduceCheckLog(drProduceCheckLog);


                        Entity.RdRecordDetail rrd = new RdRecordDetail();
                        rrd.cnvcFlag   = "0";
                        rrd.cndExpDate = pcl.cndExpDate;                    //Convert.ToDateTime(this.txtProduceDate.Text).AddDays(pc.cnnDays).AddDays(Convert.ToDouble(txtDays.Text));//Convert.ToDateTime(this.txtExpDate.Text);
                        rrd.cndMdate   = pcl.cndMDate;                      //Convert.ToDateTime(this.txtProduceDate.Text);
                        rrd.cnnRdID    = Convert.ToDecimal(rrid);
                        rrd.cnvcPOID   = al.cnnAssignSerialNo.ToString();

                        DataRow[] drinvs = dtInv.Select("cnvcInvCode='" + pcl.cnvcInvCode + "'");
                        if (drinvs.Length == 0)
                        {
                            throw new Exception(pcl.cnvcInvCode + "存货档案未设置");
                        }
                        Entity.Inventory inv = new AMSApp.zhenghua.Entity.Inventory(drinvs[0]);


                        rrd.cnvcInvCode     = inv.cnvcInvCode;
                        rrd.cnvcGroupCode   = inv.cnvcGroupCode;
                        rrd.cnvcComunitCode = inv.cnvcSTComUnitCode;

                        DataRow[] drcus = dtComputationUnit.Select("cnvcGroupCode='" + inv.cnvcGroupCode + "' and cnbMainUnit=1");
                        if (drcus.Length == 0)
                        {
                            throw new Exception(inv.cnvcGroupCode + "未设置主计量单位");
                        }
                        decimal   dchangerate    = Convert.ToDecimal(drcus[0]["cnichangrate"].ToString());
                        DataRow[] drcus1         = dtComputationUnit.Select("cnvcGroupCode='" + inv.cnvcGroupCode + "' and cnvcComUnitCode='" + inv.cnvcSTComUnitCode + "'");
                        decimal   dchangerate_st = Convert.ToDecimal(drcus1[0]["cnichangrate"].ToString());

//						string strcssql = "SELECT * FROM tbCurrentStock WHERE cnvcWhCode='"+strWarehouse+"' AND cnvcInvCode='"+pcl.cnvcInvCode+"'";
//						DataTable dtcs = SqlHelper.ExecuteDataTable(trans,CommandType.Text,strcssql);


                        string strcssql = "SELECT * FROM tbCurrentStock WHERE cnvcWhCode='" + strWarehouse + "' AND cnvcInvCode='" + pcl.cnvcInvCode + "'"
                                          + " and CONVERT(char(10),isnull(cndExpDate,''),121)>=CONVERT(char(10),getdate(),121) ";
                        string strcssql2 = "SELECT isnull(sum(cnnAvaQuantity),0) FROM tbCurrentStock WHERE cnvcWhCode='" + strWarehouse + "' AND cnvcInvCode='" + pcl.cnvcInvCode + "'"
                                           + " and CONVERT(char(10),isnull(cndExpDate,''),121)>=CONVERT(char(10),getdate(),121) ";
                        DataTable dtcs         = SqlHelper.ExecuteDataTable(trans, CommandType.Text, strcssql);
                        decimal   davaquantity = Convert.ToDecimal(SqlHelper.ExecuteScalar(trans, CommandType.Text, strcssql2).ToString());

                        if (dtcs.Rows.Count == 0)
                        {
                            throw new Exception(pcl.cnvcInvCode + "无库存");
                        }
                        if (davaquantity - pcl.cnnAssignCount * dchangerate_st / dchangerate < 0)
                        {
                            throw new Exception(pcl.cnvcInvCode + "库存不足");
                        }

//						if(cs.cnnAvaQuantity - pcl.cnnAssignCount<0)
//							throw new Exception(pcl.cnvcInvCode+"库存不足");
                        decimal dhave = 0;
                        foreach (DataRow drcs in dtcs.Rows)
                        {
                            Entity.CurrentStock cs = new CurrentStock(drcs);
//							if(cs.cnnAvaQuantity - pcl.cnnAssignCount<0)
//								throw new Exception(pcl.cnvcInvCode+"库存不足");
//							cs.cnnAvaQuantity = cs.cnnAvaQuantity - pcl.cnnAssignCount;
//							cs.cnnQuantity = cs.cnnQuantity - pcl.cnnAssignCount;
//							EntityMapping.Update(cs,trans);


                            if (cs.cnnAvaQuantity > pcl.cnnAssignCount * dchangerate_st / dchangerate - dhave)
                            {
                                cs.cnnAvaQuantity = cs.cnnAvaQuantity - pcl.cnnAssignCount * dchangerate_st / dchangerate;
                                cs.cnnQuantity    = cs.cnnQuantity - pcl.cnnAssignCount * dchangerate_st / dchangerate;
                                EntityMapping.Update(cs, trans);
                                break;
                            }
                            else
                            {
                                cs.cnnAvaQuantity = 0;
                                cs.cnnQuantity    = 0;
                                EntityMapping.Update(cs, trans);
                                dhave += cs.cnnAvaQuantity;
                            }
                        }
                        rrd.cnnQuantity = pcl.cnnAssignCount * dchangerate_st / dchangerate;
                        EntityMapping.Create(rrd, trans);
                    }


                    //string strsql = "update tbMakeDetail set cnbCollar=1 where cnnMakeSerialNo="+strMakeSerialNo;
                    //SqlHelper.ExecuteNonQuery(trans,CommandType.Text,strsql);

                    string strsql4 = "update tbproducelog set cnvcproducestate='7' where cnnproduceserialno=" + strProduceSerialNo;
                    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strsql4);

                    operLog.cndOperDate  = dtSysTime;
                    operLog.cnvcComments = "生产流水:" + strProduceSerialNo;
                    EntityMapping.Create(operLog, trans);

                    trans.Commit();
                }
                catch (SqlException sex)
                {
                    trans.Rollback();
                    LogAdapter.WriteDatabaseException(sex);
                    throw sex;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    LogAdapter.WriteFeaturesException(ex);
                    throw ex;
                }
                finally
                {
                    ConnectionPool.ReturnConnection(conn);
                }
            }
        }
示例#53
0
 internal sealed override string ConstructString(Type tableType, ConnectionPool pool, QueryBuilder builder, ref List<IDbDataParameter> queryParameters, ref int parCount)
 {
     bool found = false;
     string ret = "";
     FieldType? type=null;
     Type _objType = null;
     int fieldLength = 0;
     bool isExternal = false;
     bool isClassBased=false;
     Type newType;
     Type linkedType;
     string alias = "";
     string fldName = LocateTableField(FieldName,tableType, out isClassBased, out isExternal,out newType,out alias,out linkedType);
     found = fldName != null;
     if ((alias != null) && (alias.Length > 0))
         alias = "main_table_" + alias + ".";
     if (isExternal)
     {
         if (found)
         {
             if ((alias == "")||(alias==null))
                 alias = "main_table.";
             sTable relatedMap = pool.Mapping[newType];
             if (isClassBased)
             {
                 sTable map = pool.Mapping[linkedType];
                 if (FieldValue != null)
                 {
                     foreach (string prop in relatedMap.PrimaryKeyProperties)
                     {
                         foreach (sTableField fld in relatedMap[prop])
                         {
                             foreach (sTableField f in map[fldName])
                             {
                                 if (f.ExternalField == fld.Name)
                                 {
                                     ret += " AND " + (this.CaseInsensitive ? "UPPER(" : "") + alias + f.Name + (this.CaseInsensitive ? ")" : "") + " " + ComparatorString + " " + builder.CreateParameterName("parameter_" + parCount.ToString());
                                     object val = QueryBuilder.LocateFieldValue((Org.Reddragonit.Dbpro.Structure.Table)FieldValue, fld, pool);
                                     queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), val, f.Type, f.Length));
                                     parCount++;
                                     break;
                                 }
                             }
                         }
                     }
                 }
                 else
                 {
                     foreach (sTableField f in map[fldName])
                     {
                         ret += " AND " + (this.CaseInsensitive ? "UPPER(" : "") + alias + f.Name + (this.CaseInsensitive ? ")" : "") + " " + ComparatorString + " " + builder.CreateParameterName("parameter_" + parCount.ToString());
                         queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), null, f.Type, f.Length));
                         parCount++;
                     }
                 }
             }
             else
             {
                 foreach (string prop in relatedMap.PrimaryKeyProperties)
                 {
                     sTableField[] flds = relatedMap[prop];
                     if (flds[0].ExternalField != null)
                     {
                         Org.Reddragonit.Dbpro.Structure.Table tbl = null;
                         if (FieldValue != null)
                             tbl = (Org.Reddragonit.Dbpro.Structure.Table)QueryBuilder.LocateFieldValue((Org.Reddragonit.Dbpro.Structure.Table)FieldValue, flds[0], pool);
                         if (tbl != null)
                         {
                             sTable relMap = pool.Mapping[tbl.GetType()];
                             foreach (sTableField fld in relMap.Fields)
                             {
                                 foreach (sTableField f in flds)
                                 {
                                     if (fld.Name == f.ExternalField)
                                     {
                                         ret += " AND " + (this.CaseInsensitive ? "UPPER(" : "") + alias + flds[0].Name + (this.CaseInsensitive ? ")" : "") + " " + ComparatorString + " " + builder.CreateParameterName("parameter_" + parCount.ToString());
                                         object val = QueryBuilder.LocateFieldValue(tbl, fld, pool);
                                         queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), val, fld.Type, fld.Length));
                                         parCount++;
                                         break;
                                     }
                                 }
                             }
                         }
                         else
                         {
                             foreach (sTableField fld in flds)
                             {
                                 ret += " AND " + (this.CaseInsensitive ? "UPPER(" : "") + alias + flds[0].Name + (this.CaseInsensitive ? ")" : "") + " " + ComparatorString + " " + builder.CreateParameterName("parameter_" + parCount.ToString());
                                 queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), null, fld.Type, fld.Length));
                                 parCount++;
                             }
                         }
                     }
                     else
                     {
                         type = flds[0].Type;
                         fieldLength = flds[0].Length;
                         ret += " AND " + (this.CaseInsensitive ? "UPPER(" : "") + alias + flds[0].Name + (this.CaseInsensitive ? ")" : "") + " " + ComparatorString + " " + builder.CreateParameterName("parameter_" + parCount.ToString());
                         if (type == FieldType.ENUM)
                             queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), pool.GetEnumID(newType.GetProperty(prop, Utility._BINDING_FLAGS).PropertyType, ((Org.Reddragonit.Dbpro.Structure.Table)FieldValue).GetField(prop).ToString())));
                         else if (FieldValue == null)
                             queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), null, type.Value, fieldLength));
                         else
                         {
                             object val = ((Org.Reddragonit.Dbpro.Structure.Table)FieldValue).GetField(prop);
                             if (val == null)
                                 val = QueryBuilder.LocateFieldValue((Org.Reddragonit.Dbpro.Structure.Table)FieldValue, flds[0], pool);
                             queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), val, type.Value, fieldLength));
                         }
                         parCount++;
                     }
                 }
             }
             ret = ret.Substring(4);
         }else
             throw new Exception("Unable to handler external fields without specifying class name.");
     }
     else
     {
         if ((alias == "") || (alias == null))
             alias = "main_table.";
         if (fldName != null)
         {
             ret = (this.CaseInsensitive ? "UPPER(" : "") + alias + fldName + " " + (this.CaseInsensitive ? ")" : "");
             foreach (sTableField fld in pool.Mapping[newType].Fields)
             {
                 if (fld.Name == fldName)
                 {
                     type = fld.Type;
                     fieldLength = fld.Length;
                     break;
                 }
             }
         }
         if (!found)
             ret = FieldName + " ";
         if (SupportsList)
         {
             ret += ComparatorString + " (";
             if (FieldValue.GetType().IsArray || (FieldValue is IEnumerable))
             {
                 foreach (object obj in (IEnumerable)FieldValue)
                 {
                     if (_objType == null)
                         _objType = obj.GetType();
                     ret += builder.CreateParameterName("parameter_" + parCount.ToString()) + ",";
                     if ((_objType != null) && Utility.IsEnum(_objType))
                     {
                         queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), pool.GetEnumID(_objType, obj.ToString())));
                     }
                     else
                     {
                         if (type.HasValue)
                             queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), obj, type.Value, fieldLength));
                         else
                             queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), obj));
                     }
                     parCount++;
                 }
                 ret = ret.Substring(0, ret.Length - 1);
             }
             else
             {
                 ret += builder.CreateParameterName("parameter_" + parCount.ToString());
                 if (_objType == null)
                     _objType = FieldValue.GetType();
                 if ((_objType != null) && Utility.IsEnum(_objType))
                     queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), pool.GetEnumID(_objType, FieldValue.ToString())));
                 else
                 {
                     if (type.HasValue)
                         queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), FieldValue, type.Value, fieldLength));
                     else
                         queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), FieldValue));
                 }
                 parCount++;
             }
             ret += ")";
         }
         else
         {
             if (FieldValue == null)
             {
                 ret += ComparatorString +" "+ builder.CreateParameterName("parameter_" + parCount.ToString());
                 queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), FieldValue));
                 parCount++;
             }
             else if (FieldValue.GetType().IsArray || (FieldValue is ICollection))
             {
                 string tmp = ret;
                 tmp += ComparatorString+ " ";
                 ret += "( ";
                 foreach (object obj in (IEnumerable)FieldValue)
                 {
                     if (_objType == null)
                         _objType = obj.GetType();
                     ret += tmp + builder.CreateParameterName("parameter_" + parCount.ToString()) + " AND ";
                     if ((_objType != null) && Utility.IsEnum(_objType))
                     {
                         queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), pool.GetEnumID(_objType, obj.ToString())));
                     }
                     else
                     {
                         if (type.HasValue)
                             queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), obj, type.Value, fieldLength));
                         else
                             queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), obj));
                     }
                     parCount++;
                 }
                 ret = ret.Substring(0, tmp.Length - 4);
                 ret += " )";
             }
             else
             {
                 ret += ComparatorString+" ";
                 ret += builder.CreateParameterName("parameter_" + parCount.ToString());
                 if (_objType == null)
                     _objType = FieldValue.GetType();
                 if ((_objType != null) && Utility.IsEnum(_objType))
                 {
                     queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), pool.GetEnumID(_objType, FieldValue.ToString())));
                 }
                 else
                 {
                     if (type.HasValue)
                         queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), FieldValue, type.Value, fieldLength));
                     else
                         queryParameters.Add(pool.CreateParameter(builder.CreateParameterName("parameter_" + parCount.ToString()), FieldValue));
                 }
                 parCount++;
             }
         }
     }
     return ret;
 }
示例#54
0
 public ODatabase(string hostName, int port, string databaseName, ODatabaseType type, string userName, string userPassword, X509Certificate2Collection sslCerts)
 {
     _connectionPool = new ConnectionPool(hostName, port, databaseName, type, userName, userPassword, sslCerts);
     ClientCache     = new ConcurrentDictionary <ORID, ODocument>();
 }
 internal static IOStrategy CreateIOStrategy(string server)
 {
     var connectionPool = new ConnectionPool<EapConnection>(new PoolConfiguration(), UriExtensions.GetEndPoint(server));
     var ioStrategy = new DefaultIOStrategy(connectionPool);
     return ioStrategy;
 }
示例#56
0
 public void Open()
 {
     m_dbConnection = ConnectionPool.GetDbConnection();
     m_state        = ConnectionState.Open;
 }
 public ConnectionPoolHelper(ConnectionPool connectionPool, IConnectionInitiator connectionInitiator, Uri via)
 {
     this.connectionInitiator = connectionInitiator;
     this.connectionPool = connectionPool;
     this.via = via;
 }
示例#58
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="databaseSettings"></param>
 /// <param name="connectionPool"></param>
 public ArangoDatabase(ClientSettings databaseSettings, ConnectionPool <IConnection> connectionPool)
 {
     this.databaseSettings = databaseSettings;
     this.connectionPool   = connectionPool;
 }
示例#59
0
 public DBCommand(ConnectionPool pool, Int32 timeoutSec = 60)
 {
     _pool = pool;
     _isAsync = false;
     CommandTimeout = timeoutSec;
 }
示例#60
0
 public void Dispose()
 {
     Db.Multiplexer.GetSubscriber().UnsubscribeAll();
     ConnectionPool.Dispose();
 }