Debug() public static method

public static Debug ( string msg ) : void
msg string
return void
Exemplo n.º 1
0
        public bool Connect(string ipAddressOrHostName, int port)
        {
            lock (m_SyncRoot)
            {
                m_WorkingQueue.Clear();
            }

            m_IncompletePacket.Clear();
            m_IncompleteDecompressionPacket.Clear();

            if (IsConnected)
            {
                Disconnect();
            }

            bool success = true;

            try
            {
                if (!IPAddress.TryParse(ipAddressOrHostName, out m_ServerAddress))
                {
                    IPAddress[] ipAddresses = Dns.GetHostAddresses(ipAddressOrHostName);

                    if (ipAddresses.Length == 0)
                    {
                        throw new NetworkException("Host address was unreachable or invalid, unable to obtain an ip address.");
                    }

                    // On Vista and later, the first ip address is an empty one '::1'.
                    // This makes sure we choose the first valid ip address.
                    foreach (IPAddress address in ipAddresses)
                    {
                        if (address.ToString().Length <= 7)
                        {
                            continue;
                        }

                        m_ServerAddress = address;
                        break;
                    }
                }

                m_ServerEndPoint = new IPEndPoint(m_ServerAddress, port);

                Tracer.Debug("Connecting to {0}:{1}...", m_ServerAddress, port);

                m_ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_ServerSocket.Connect(m_ServerEndPoint);

                if (m_ServerSocket.Connected)
                {
                    Tracer.Debug("Connected.");
                    SocketState state = new SocketState(m_ServerSocket, m_BufferPool.AcquireBuffer());
                    m_ServerSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, OnReceive, state);
                }
            }
            catch
            {
                success = false;
            }

            m_IsConnected = success;
            return(success);
        }
Exemplo n.º 2
0
        public int UpdateVehicleDispatchAndDetail(T_OA_VEHICLEDISPATCH entity, List <T_OA_VEHICLEDISPATCHDETAIL> vddList)
        {
            try
            {
                //VehicleDispatchManageDal vdmDal = new VehicleDispatchManageDal();
                ////更新主表
                //return vdmDal.UpdateVehicleDispatchAndDetail(entity, vddList);

                BeginTransaction();

                ///////////////////
                int aaa = Update(entity);
                if (!(aaa > 0))
                {
                    RollbackTransaction();
                    return(-1);
                }

                if (vddList == null || vddList.Count == 0)
                {
                    CommitTransaction();
                    return(1);
                }
                var ents = from ent in dal.GetObjects <T_OA_VEHICLEDISPATCHDETAIL>().Include("T_OA_VEHICLEDISPATCH")
                           where ent.T_OA_VEHICLEDISPATCH.VEHICLEDISPATCHID == entity.VEHICLEDISPATCHID
                           select ent;
                if (ents.Count() > 0)
                {
                    ents.ToList().ForEach(item =>
                    {
                        dal.DeleteFromContext(item);
                    });
                    int k = dal.SaveContextChanges();
                }

                foreach (T_OA_VEHICLEDISPATCHDETAIL obj in vddList)
                {
                    Utility.RefreshEntity(obj);
                    //entity.T_OA_VEHICLEDISPATCHDETAIL.Add(obj);
                    dal.AddToContext(obj);
                }

                //bool aa = Add(entity);
                //int aa = Update(entity);
                int aa = dal.SaveContextChanges();
                if (aa <= 0)
                {
                    RollbackTransaction();
                    return(-1);
                }
                else
                {
                    CommitTransaction();
                    return(1);
                }
            }
            catch (Exception ex)
            {
                Tracer.Debug("派车管理VehicleDispatchManageBll-UpdateVehicleDispatchAndDetail" + System.DateTime.Now.ToString() + " " + ex.ToString());
                return(-1);
            }
        }
Exemplo n.º 3
0
        private async Task <Result <Selector[]> > GetOrAddSelectorsAsync(
            Context context,
            Fingerprint weakFingerprint,
            Func <Fingerprint, Task <Result <Selector[]> > > getFunc,
            CancellationToken cancellationToken)
        {
            try
            {
                var cacheKey = _redisSerializer.ToRedisKey(weakFingerprint);

                RedisValue[] cacheSelectors;

                Stopwatch stopwatch = Stopwatch.StartNew();
                try
                {
                    _cacheTracer.GetDistributedSelectorsStart(context);
                    cacheSelectors = await GetSetMembersWithExpiryBumpAsync(context, cacheKey);
                }
                finally
                {
                    _cacheTracer.GetDistributedSelectorsStop(context, stopwatch.Elapsed);
                }

                if (cacheSelectors.Length == 0)
                {
                    _cacheTracer.RecordSelectorsFetchedFromBackingStore(context, weakFingerprint);
                    Result <Selector[]> selectorResults = await getFunc(weakFingerprint).ConfigureAwait(false);

                    if (!selectorResults || selectorResults.Value.Length == 0)
                    {
                        // Redis throws an error if set add is called without any values. Also, undefined keys are treated as empty sets.
                        // So currently skip trying to cache GetSelectors returning empty.
                        // If needed, we need to create a sentinel value to denote an known empty set v/s undefined.
                        return(selectorResults);
                    }

                    {
                        var selectors   = selectorResults.Value;
                        var cacheValues = _redisSerializer.ToRedisValues(selectors);

                        stopwatch = Stopwatch.StartNew();
                        try
                        {
                            _cacheTracer.AddSelectorsStart(context);
                            var addedCount = await AddSetMembersWithExpiryBumpAsync(context, cacheKey, cacheValues);

                            if (cacheValues.Length != addedCount)
                            {
                                _tracer.Warning(context, $"Expected to add {cacheValues.Length} members but actually added {addedCount}.");
                            }

                            _tracer.Debug(context, $"Added redis cache entry for {weakFingerprint}: {selectors.Length} selectors.");
                        }
                        finally
                        {
                            _cacheTracer.AddSelectorsStop(context, stopwatch.Elapsed);
                        }
                    }

                    return(selectorResults);
                }
                else
                {
                    Selector[] result = _redisSerializer.AsSelectors(cacheSelectors).ToArray();
                    _cacheTracer.RecordSelectorsFetchedDistributed(context, weakFingerprint, result.Length);
                    return(result);
                }
            }
            catch (Exception ex)
            {
                return(Result.FromException <Selector[]>(ex));
            }
        }
        public void Prepare(PreparingEnlistment preparingEnlistment)
        {
            lock (this.syncObject)
            {
                this.netTxState = TxState.Pending;

                try
                {
                    Tracer.Debug("Prepare notification received for TX id: " + this.transactionId);

                    BeforeEnd();

                    // Before sending the request to the broker, log the recovery bits, if
                    // this fails we can't prepare and the TX should be rolled back.
                    RecoveryLogger.LogRecoveryInfo(this.transactionId as XATransactionId,
                                                   preparingEnlistment.RecoveryInformation());

                    // Inform the broker that work on the XA'sh TX Branch is complete.
                    TransactionInfo info = new TransactionInfo();
                    info.ConnectionId  = this.connection.ConnectionId;
                    info.TransactionId = this.transactionId;
                    info.Type          = (int)TransactionType.End;

                    this.connection.CheckConnected();
                    this.connection.SyncRequest((TransactionInfo)info.Clone());

                    // Prepare the Transaction for commit.
                    info.Type = (int)TransactionType.Prepare;
                    IntegerResponse response = (IntegerResponse)this.connection.SyncRequest(info);
                    if (response.Result == XA_READONLY)
                    {
                        Tracer.Debug("Transaction Prepare done and doesn't need a commit, TX id: " + this.transactionId);

                        this.transactionId     = null;
                        this.currentEnlistment = null;

                        // Read Only means there's nothing to recover because there was no
                        // change on the broker.
                        RecoveryLogger.LogRecovered(this.transactionId as XATransactionId);

                        // if server responds that nothing needs to be done, then reply done.
                        // otherwise the DTC will call Commit or Rollback but another transaction
                        // can already be in progress and this one would be commited or rolled back
                        // immediately.
                        preparingEnlistment.Done();

                        // Done so commit won't be called.
                        AfterCommit();

                        // A Read-Only TX is considered closed at this point, DTC won't call us again.
                        this.dtcControlEvent.Set();
                    }
                    else
                    {
                        Tracer.Debug("Transaction Prepare succeeded TX id: " + this.transactionId);

                        // If work finished correctly, reply prepared
                        preparingEnlistment.Prepared();
                    }
                }
                catch (Exception ex)
                {
                    Tracer.DebugFormat("Transaction[{0}] Prepare failed with error: {1}",
                                       this.transactionId, ex.Message);

                    AfterRollback();
                    preparingEnlistment.ForceRollback();
                    try
                    {
                        this.connection.OnAsyncException(ex);
                    }
                    catch (Exception error)
                    {
                        Tracer.Error(error.ToString());
                    }

                    this.currentEnlistment = null;
                    this.transactionId     = null;
                    this.netTxState        = TxState.None;
                    this.dtcControlEvent.Set();
                }
            }
        }
        /// <summary>
        /// Should be called from NetTxSession when created to check if any TX
        /// data is stored for recovery and whether the Broker has matching info
        /// stored.  If an Transaction is found that belongs to this client and is
        /// still alive on the Broker it will be recovered, otherwise the stored
        /// data should be cleared.
        /// </summary>
        public void InitializeDtcTxContext()
        {
            string resourceManagerId = ResourceManagerId;

            // initialize the logger with the current Resource Manager Id
            RecoveryLogger.Initialize(resourceManagerId);

            lock (recoveredResourceManagerIds)
            {
                if (recoveredResourceManagerIds.ContainsKey(resourceManagerId))
                {
                    return;
                }

                recoveredResourceManagerIds[resourceManagerId] = true;

                KeyValuePair <XATransactionId, byte[]>[] localRecoverables = RecoveryLogger.GetRecoverables();
                if (localRecoverables.Length == 0)
                {
                    Tracer.Debug("Did not detect any open DTC transaction records on disk.");
                    // No local data so anything stored on the broker can't be recovered here.
                    return;
                }

                XATransactionId[] recoverables = TryRecoverBrokerTXIds();
                if (recoverables.Length == 0)
                {
                    Tracer.Debug("Did not detect any recoverable transactions at Broker.");
                    // Broker has no recoverable data so nothing to do here, delete the
                    // old recovery log as its stale.
                    RecoveryLogger.Purge();
                    return;
                }

                List <KeyValuePair <XATransactionId, byte[]> > matches = new List <KeyValuePair <XATransactionId, byte[]> >();

                foreach (XATransactionId recoverable in recoverables)
                {
                    foreach (KeyValuePair <XATransactionId, byte[]> entry in localRecoverables)
                    {
                        if (entry.Key.Equals(recoverable))
                        {
                            Tracer.DebugFormat("Found a matching TX on Broker to stored Id: {0} reenlisting.", entry.Key);
                            matches.Add(entry);
                        }
                    }
                }

                if (matches.Count != 0)
                {
                    this.recoveryComplete = new CountDownLatch(matches.Count);

                    foreach (KeyValuePair <XATransactionId, byte[]> recoverable in matches)
                    {
                        this.transactionId = recoverable.Key;
                        Tracer.Info("Reenlisting recovered TX with Id: " + this.transactionId);
                        this.currentEnlistment =
                            TransactionManager.Reenlist(ResourceManagerGuid, recoverable.Value, this);
                    }

                    this.recoveryComplete.await();
                    Tracer.Debug("All Recovered TX enlistments Reports complete, Recovery Complete.");
                    TransactionManager.RecoveryComplete(ResourceManagerGuid);
                    return;
                }

                // The old recovery information doesn't match what's on the broker so we
                // should discard it as its stale now.
                RecoveryLogger.Purge();
            }
        }
Exemplo n.º 6
0
        public void FailoverAfterCommitSentTest()
        {
            string             uri     = "failover:(tcpfaulty://${activemqhost}:61616?transport.useLogging=true)";
            IConnectionFactory factory = new ConnectionFactory(NMSTestSupport.ReplaceEnvVar(uri));

            using (connection = factory.CreateConnection() as Connection)
            {
                connection.ConnectionInterruptedListener +=
                    new ConnectionInterruptedListener(TransportInterrupted);
                connection.ConnectionResumedListener +=
                    new ConnectionResumedListener(TransportResumed);

                connection.Start();

                ITransport         transport = (connection as Connection).ITransport;
                TcpFaultyTransport tcpFaulty = transport.Narrow(typeof(TcpFaultyTransport)) as TcpFaultyTransport;
                Assert.IsNotNull(tcpFaulty);
                tcpFaulty.OnewayCommandPostProcessor += this.FailOnCommitTransportHook;

                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = session.GetQueue(destinationName);
                    DeleteQueue(connection, destination);
                }

                Tracer.Debug("Test is putting " + MSG_COUNT + " messages on the queue: " + destinationName);

                using (ISession session = connection.CreateSession(AcknowledgementMode.Transactional))
                {
                    IDestination destination = session.GetQueue(destinationName);
                    PutMsgIntoQueue(session, destination, false);

                    try
                    {
                        session.Commit();
                        Assert.Fail("Should have thrown a TransactionRolledBackException");
                    }
                    catch (TransactionRolledBackException)
                    {
                        Tracer.Info("TEST: Caught expected TransactionRolledBackException");
                    }
                    catch (Exception ex)
                    {
                        Assert.Fail("Should have thrown a TransactionRolledBackException, but was: " +
                                    ex.GetType().Name);
                    }
                }

                Assert.IsTrue(this.interrupted);
                Assert.IsTrue(this.resumed);

                Tracer.Debug("Test is attempting to read " + MSG_COUNT +
                             " messages from the queue: " + destinationName);

                using (ISession session = connection.CreateSession())
                {
                    IDestination     destination = session.GetQueue(destinationName);
                    IMessageConsumer consumer    = session.CreateConsumer(destination);
                    for (int i = 0; i < MSG_COUNT; ++i)
                    {
                        IMessage msg = consumer.Receive(TimeSpan.FromSeconds(5));
                        Assert.IsNotNull(msg, "Should receive message[" + (i + 1) + "] after commit failed once.");
                    }
                }
            }

            Assert.IsTrue(this.interrupted);
            Assert.IsTrue(this.resumed);
        }
        protected MemoizationPerformanceTests
        (
            ILogger logger,
            PerformanceResultsFixture resultsFixture,
            InitialDatabaseSize initialDatabaseSize,
            string databaseFileName,
            Func <DisposableDirectory, IMemoizationStore> createStoreFunc
        )
            : base(() => new PassThroughFileSystem(logger), logger)
        {
            _context = new Context(Logger);
            var itemCountEnvironmentVariable = Environment.GetEnvironmentVariable(ItemCountEnvironmentVariableName);

            _itemCount = itemCountEnvironmentVariable == null ? ItemCountDefault : int.Parse(itemCountEnvironmentVariable);
            _tracer.Debug(_context, $"Using itemCount=[{_itemCount}] (MaxRowCount=[{MaxRowCount}])");

            ResultsFixture       = resultsFixture;
            _initialDatabaseSize = initialDatabaseSize;
            CreateStoreFunc      = createStoreFunc;

            _prePopulatedRootPath = FileSystem.GetTempPath() / "CloudStore" / "MemoizationPerformanceTestsPrePopulated";
            if (!FileSystem.DirectoryExists(_prePopulatedRootPath))
            {
                FileSystem.CreateDirectory(_prePopulatedRootPath);
            }

            AbsolutePath databaseFilePath = _prePopulatedRootPath / databaseFileName;

            if (FileSystem.FileExists(databaseFilePath))
            {
                return;
            }

            _tracer.Always(_context, $"Creating prepopulated database at path={databaseFilePath}");

            using (var disposableDirectory = new DisposableDirectory(FileSystem))
            {
                using (var store = createStoreFunc(disposableDirectory))
                {
                    try
                    {
                        var startupStoreResult = store.StartupAsync(_context).Result;
                        startupStoreResult.ShouldBeSuccess();

                        var createSessionResult = store.CreateSession(_context, Name);
                        createSessionResult.ShouldBeSuccess();

                        using (var session = createSessionResult.Session)
                        {
                            try
                            {
                                var startupSessionResult = session.StartupAsync(_context).Result;
                                startupSessionResult.ShouldBeSuccess();

                                for (var i = 0; i < MaxRowCount; i++)
                                {
                                    var strongFingerprint = StrongFingerprint.Random();
                                    var contentHashList   = ContentHashList.Random();
                                    var r = session.AddOrGetContentHashListAsync(
                                        _context, strongFingerprint, new ContentHashListWithDeterminism(contentHashList, CacheDeterminism.None), Token).Result;
                                    r.Succeeded.Should().BeTrue();
                                    r.ContentHashListWithDeterminism.ContentHashList.Should().BeNull();
                                }
                            }
                            finally
                            {
                                var shutdownSessionResult = session.ShutdownAsync(_context).Result;
                                shutdownSessionResult.ShouldBeSuccess();
                            }
                        }
                    }
                    finally
                    {
                        var shutdownStoreResult = store.ShutdownAsync(_context).Result;
                        shutdownStoreResult.ShouldBeSuccess();
                    }
                }

                FileSystem.CopyFileAsync(disposableDirectory.Path / databaseFileName, databaseFilePath, false).Wait();
            }
        }
Exemplo n.º 8
0
        public string OutApplySetValue(string msg, T_HR_OUTAPPLYCONFIRM entity)
        {
            if (!entity.T_HR_OUTAPPLYRECORDReference.IsLoaded)
            {
                entity.T_HR_OUTAPPLYRECORDReference.Load();
            }

            #region 非当天往返或者实际返回未打卡,设置外出结束时间为当天下班时间
            if (entity.T_HR_OUTAPPLYRECORD.ISSAMEDAYRETURN == "0" ||
                entity.ENDDATE == new DateTime(2001, 1, 1))   //
            {
                if (GetAttendanceSolution(entity.EMPLOYEEID, entity.T_HR_OUTAPPLYRECORD.STARTDATE) == null)
                {
                    return("未获取到用户的考勤方案,保存失败");
                }

                AttendanceSolutionAsignBLL   bllAttendSolAsign = new AttendanceSolutionAsignBLL();
                T_HR_ATTENDANCESOLUTIONASIGN entAttendSolAsign = bllAttendSolAsign.GetAttendanceSolutionAsignByEmployeeIDAndDate(entity.EMPLOYEEID, entity.T_HR_OUTAPPLYRECORD.STARTDATE.Value);

                if (entAttendSolAsign.T_HR_ATTENDANCESOLUTION == null)
                {
                    //当前员工没有分配考勤方案,无法提交外出申请
                    msg = msg + "当前员工没有分配考勤方案,无法提交外出申请";
                    Tracer.Debug(msg);
                    return(msg);
                }
                else
                {
                    var entAttendSol = entAttendSolAsign.T_HR_ATTENDANCESOLUTION;

                    var tempMaster = from ent in dal.GetObjects <T_HR_SCHEDULINGTEMPLATEMASTER>()
                                     where ent.TEMPLATEMASTERID == entAttendSol.T_HR_SCHEDULINGTEMPLATEMASTER.TEMPLATEMASTERID
                                     select ent;

                    if (!entAttendSol.T_HR_SCHEDULINGTEMPLATEMASTERReference.IsLoaded)
                    {
                        entAttendSol.T_HR_SCHEDULINGTEMPLATEMASTERReference.Load();
                    }

                    var entsched = from a in dal.GetObjects <T_HR_SCHEDULINGTEMPLATEMASTER>()
                                   join b in dal.GetObjects <T_HR_SCHEDULINGTEMPLATEDETAIL>()
                                   on a.TEMPLATEMASTERID equals b.T_HR_SCHEDULINGTEMPLATEMASTER.TEMPLATEMASTERID
                                   join c in dal.GetObjects <T_HR_SHIFTDEFINE>()
                                   on b.T_HR_SHIFTDEFINE.SHIFTDEFINEID equals c.SHIFTDEFINEID
                                   where a.TEMPLATEMASTERID == entAttendSol.T_HR_SCHEDULINGTEMPLATEMASTER.TEMPLATEMASTERID
                                   select c;
                    if (entsched.Count() > 0)
                    {
                        var      defineTime          = entsched.FirstOrDefault();
                        DateTime ShiftFirstStartTime = new DateTime();
                        if (defineTime.NEEDTHIRDOFFCARD == "2" && !string.IsNullOrEmpty(defineTime.THIRDENDTIME))
                        {
                            ShiftFirstStartTime = DateTime.Parse(defineTime.THIRDENDTIME);//设置3段打卡,第2段下班打卡时间:一般为17:50
                        }
                        else if (defineTime.NEEDSECONDOFFCARD == "2" && !string.IsNullOrEmpty(defineTime.SECONDENDTIME))
                        {
                            ShiftFirstStartTime = DateTime.Parse(defineTime.SECONDENDTIME);//设置2段打卡,第2段下班打卡时间:一般为17:50
                        }
                        else
                        {
                            msg = msg + "外出申请班次定义设置错误,没有找到下班时间定义" + " 考勤方案名:" + entAttendSolAsign.T_HR_ATTENDANCESOLUTION.ATTENDANCESOLUTIONNAME;
                            Tracer.Debug(msg);
                            return(msg);
                        }
                        DateTime dtstar = entity.T_HR_OUTAPPLYRECORD.STARTDATE.Value;
                        DateTime ShiftstartDateAndTime = new DateTime(dtstar.Year, dtstar.Month, dtstar.Day
                                                                      , ShiftFirstStartTime.Hour, ShiftFirstStartTime.Minute, ShiftFirstStartTime.Second);
                        if (entity.ENDDATE == new DateTime(2001, 1, 1))//实际出发时间选择为未打卡不计算外出时长
                        {
                            entity.ENDDATE = ShiftstartDateAndTime;
                        }
                    }
                    else
                    {
                        msg = msg + "外出申请班次定义未找到" + " 考勤方案名:" + entAttendSolAsign.T_HR_ATTENDANCESOLUTION.ATTENDANCESOLUTIONNAME;
                        Tracer.Debug(msg);
                        return(msg);
                    }
                }

                if (entity.ENDDATE == null)
                {
                    msg = msg + "外出申请为非当天往返,但是结束时间未找到,请检查考勤方案排版设置是否正确。" + " 考勤方案名:" + entAttendSolAsign.T_HR_ATTENDANCESOLUTION.ATTENDANCESOLUTIONNAME;
                    Tracer.Debug(msg);
                    return(msg);
                }
            }
            #endregion

            #region 计算外出时长
            string strMsg = string.Empty;
            //
            string dTotalHours = string.Empty;
            if (entity.STARTDATE == new DateTime(2001, 1, 1))//实际出发时间选择为未打卡不计算外出时长
            {
                entity.OUTAPLLYTIMES = "外出确认实际出发时间未打卡";
            }
            else
            {
                strMsg = CalculateOverTimeHours(entity.EMPLOYEEID, entity.STARTDATE.Value, entity.ENDDATE.Value, ref dTotalHours);

                entity.OUTAPLLYTIMES = dTotalHours.ToString();
            }
            #endregion
            return(strMsg);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 审核外出确认记录
        /// </summary>
        /// <param name="strOverTimeRecordID">主键索引</param>
        /// <param name="strCheckState"></param>
        /// <returns></returns>
        public string AuditOutApplyConfirm(string strOverTimeRecordID, string strCheckState)
        {
            string strMsg = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(strOverTimeRecordID) || string.IsNullOrEmpty(strCheckState))
                {
                    return("{REQUIREDFIELDS}");
                }

                T_HR_OUTAPPLYCONFIRM entOTRd = GetOutApplyConfirmByID(strOverTimeRecordID);

                if (entOTRd == null)
                {
                    return("{NOTFOUND}");
                }

                entOTRd.CHECKSTATE = strCheckState;

                entOTRd.UPDATEDATE = DateTime.Now;

                //Utility.CloneEntity(entOTRd, ent);
                int i = dal.Update(entOTRd);
                if (i == 0)
                {
                    Tracer.Debug("更新T_HR_OUTAPPLYCONFIRM失败");
                    throw new Exception("更新T_HR_OUTAPPLYCONFIRM失败");
                }
                SaveMyRecord(entOTRd);


                if (entOTRd.CHECKSTATE != Convert.ToInt32(CheckStates.Approved).ToString())
                {
                    return("{SAVESUCCESSED}");
                }
                else
                {
                    DateTime dtstart = DateTime.Now;
                    DateTime dtEnd   = DateTime.Now;
                    if (entOTRd.STARTDATE == new DateTime(2001, 1, 1) ||
                        entOTRd.ENDDATE == new DateTime(2001, 1, 1))//实际出发时间选择为未打卡不计算外出时长
                    {
                        var q = (from ent in dal.GetObjects <T_HR_OUTAPPLYRECORD>()
                                 where ent.OUTAPPLYID == entOTRd.T_HR_OUTAPPLYRECORD.OUTAPPLYID
                                 select ent).FirstOrDefault();
                        if (q == null)
                        {
                            string msg = "外出确认未全部选择时间且未找到相关的外出申请单时间,检查考勤异常退出";
                            Tracer.Debug(msg);
                            return(msg);
                        }
                        else
                        {
                            dtstart = q.STARTDATE.Value;
                            dtEnd   = q.ENDDATE.Value;
                        }
                    }
                    else
                    {
                        dtstart = entOTRd.STARTDATE.Value;
                        dtEnd   = entOTRd.ENDDATE.Value;
                    }
                    #region  启动处理考勤异常的线程

                    string attState = (Convert.ToInt32(Common.AttendanceState.OutApplyConfirm) + 1).ToString();
                    Dictionary <string, object> d = new Dictionary <string, object>();
                    d.Add("EMPLOYEEID", entOTRd.EMPLOYEEID);
                    d.Add("STARTDATETIME", dtstart);
                    d.Add("ENDDATETIME", dtEnd);
                    d.Add("ATTSTATE", attState);
                    Thread thread = new Thread(dealAttend);
                    thread.Start(d);

                    Tracer.Debug("外出申请启动消除异常的线程,外出申请开始时间:" + entOTRd.STARTDATE.Value.ToString("yyyy-MM-dd HH:mm:ss")
                                 + " 结束时间:" + entOTRd.ENDDATE.Value.ToString("yyyy-MM-dd HH:mm:ss") + "员工id:" + entOTRd.EMPLOYEEID);

                    #endregion
                }
                return("{SAVESUCCESSED}");
            }
            catch (Exception ex)
            {
                strMsg = "{AUDITERROR}";
                Utility.SaveLog(ex.ToString());
            }

            return(strMsg);
        }
Exemplo n.º 10
0
        protected void DoClientAcknowledge(MQTTMessage message)
        {
            this.CheckClosed();
            Tracer.Debug("Sending Client Ack:");
//			this.session.Acknowledge();
        }
Exemplo n.º 11
0
        public T_FB_EXTENSIONALORDER UpdateExtensionOrder(string strModelCode, string orderID, string strCheckStates, ref string strMsg)
        {
            string travelCode = string.Empty;

            using (FBCommonBLL fbCommonBLL = new FBCommonBLL())
            {
                try
                {
                    SystemBLL.Debug("UpdateExtensionOrder方法已被调用,参数:strModelCode: " + strModelCode + ", orderID: " + orderID + ", strCheckStates: " + strCheckStates);

                    QueryExpression queryExpression = QueryExpression.Equal("ORDERID", orderID);

                    if (strModelCode == "Travel")
                    {
                        travelCode = strMsg;
                        strMsg     = string.Empty;
                        QueryExpression tempQE = QueryExpression.Equal("TravelSubject", "1");

                        tempQE.RelatedExpression          = QueryExpression.Equal("EXTENSIONALTYPECODE", "CCPX");
                        queryExpression.RelatedExpression = tempQE;
                    }
                    //查出保存的外部单据
                    queryExpression.QueryType    = typeof(T_FB_EXTENSIONALORDER).Name;
                    queryExpression.IsNoTracking = true;
                    List <FBEntity> listDetail = fbCommonBLL.QueryFBEntities(queryExpression);
                    //如果存在外部单据
                    if (listDetail.Count > 0)
                    {
                        var saveFBEntity = listDetail[0];
                        saveFBEntity.Entity.SetValue("CHECKSTATES", Decimal.Parse(strCheckStates));
                        saveFBEntity.Entity.SetValue("INNERORDERCODE", travelCode);
                        Tracer.Debug("出差更新预算单据,传入的单据编号为:" + travelCode);
                        saveFBEntity.FBEntityState = FBEntityState.Modified;
                        //var temp = fbCommonBLL.FBCommSaveEntity(listDetail[0]);
                        SaveResult temp = new SaveResult();
                        try
                        {
                            temp.FBEntity   = fbCommonBLL.SaveT_FB_EXTENSIONALORDER(listDetail[0]);
                            temp.Successful = true;
                        }
                        catch (Exception ex)
                        {
                            temp.Exception  = ex.Message;
                            temp.Successful = false;
                        }

                        if (temp.Successful)
                        {
                            return(temp.FBEntity.Entity as T_FB_EXTENSIONALORDER);
                        }
                        else
                        {
                            strMsg = temp.Exception;
                        }
                    }
                    else
                    {
                        strMsg = "没有可操作的数据";
                    }
                }
                catch (Exception ex)
                {
                    strMsg = ex.Message;
                    if (!(ex is FBBLLException))
                    {
                        // strMsg = "单据审核异常,请联系管理员";
                        Tracer.Debug("审核" + strModelCode + "的单据[" + orderID + "]出现异常,错误消息为:" + ex.ToString());
                    }
                }
                return(null);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// 参与的员工调查
        /// </summary>
        public IQueryable <V_MyEusurvey> Get_MyVisistedSurvey(int pageIndex, int pageSize, string sort, string filterString, object[] paras, ref int pageCount, string userId, List <string> guidStringList, string checkState, string postID, string companyID, string departmentID)
        {
            try
            {
                string _checkState = Convert.ToInt32(CheckStates.Approved).ToString();
                var    ents        = from require in dal.GetObjects <T_OA_REQUIRE>()
                                     .Include("T_OA_REQUIREMASTER")
                                     .Include("T_OA_REQUIRERESULT")
                                     join users in dal.GetObjects <T_OA_DISTRIBUTEUSER>()
                                     on require.REQUIREID equals users.FORMID
                                     // where require.STARTDATE <= DateTime.Now && require.CHECKSTATE == _checkState && require.ENDDATE >= DateTime.Now
                                     select new V_MyEusurvey
                {
                    OWNERCOMPANYID    = require.OWNERCOMPANYID,
                    OWNERID           = require.OWNERID,
                    OWNERDEPARTMENTID = require.OWNERDEPARTMENTID,
                    OWNERPOSTID       = require.OWNERPOSTID,
                    OARequire         = require,
                    OAResult          = require.T_OA_REQUIRERESULT,
                    OAMaster          = require.T_OA_REQUIREMASTER,
                    distrbuteuser     = users
                };

                if (ents.Count() > 0)
                {
                    //ents = ents.Where(s =>
                    //    s.distrbuteuser.VIEWER == userId
                    //    || s.distrbuteuser.VIEWER == postID
                    //    || s.distrbuteuser.VIEWER == departmentID
                    //    || s.distrbuteuser.VIEWER == companyID);
                    List <object> queryParas = new List <object>();
                    if (paras != null && paras.Count() > 0)
                    {
                        queryParas.AddRange(paras);
                    }

                    if (!string.IsNullOrEmpty(filterString))
                    {
                        ents = ents.ToList().AsQueryable().Where(filterString, queryParas);
                    }

                    //List<V_MyEusurvey> _delList = ents.ToList();
                    //foreach (var data in _delList)//如果已经参与过调查,则在结果中去除这条数据
                    //{
                    //    if (data.OAResult.Count() > 0)
                    //    {
                    //        _delList.Remove(data);
                    //    }
                    //}
                    ents = ents.AsQueryable().OrderBy(sort);
                    ents = Utility.Pager <V_MyEusurvey>(ents, pageIndex, pageSize, ref pageCount);
                    return(ents);
                }
                return(null);
            }
            catch (Exception ex)
            {
                Tracer.Debug("调查申请EmployeeSurveyViewBll-Get_MyVisistedSurvey" + System.DateTime.Now.ToString() + " " + ex.ToString());
                return(null);

                throw (ex);
            }
        }
Exemplo n.º 13
0
        //EmployeeSurveyViewDal esvDal = new EmployeeSurveyViewDal();
        //更新方案 旧
        public int UpdateEmployeeSurveyView(V_EmployeeSurvey infoView)
        {
            try
            {
                EmployeeSurveyViewDal esvDal = new EmployeeSurveyViewDal();
                masterBll.BeginTransaction();
                if (esvDal.UpdateRequireMaster(infoView.RequireMaster) == -1)
                {
                    masterBll.RollbackTransaction();
                    return(-1);
                }
                //题目 添加、更新
                List <V_EmployeeSurveySubject> subjectViewList = GetSubjectViewListByMasterID(infoView.RequireMaster.REQUIREMASTERID).ToList();

                //////删除
                IEnumerable <V_EmployeeSurveySubject> lstsub = infoView.SubjectViewList;
                foreach (V_EmployeeSurveySubject i in lstsub)
                {
                    bool isAdd = true;

                    foreach (V_EmployeeSurveySubject v in subjectViewList)
                    {
                        if (i.SubjectInfo.REQUIREDETAIL2ID == v.SubjectInfo.REQUIREDETAIL2ID)
                        {
                            isAdd = false;
                        }
                        break;
                    }
                    if (isAdd)
                    {      //添加   题目   答案
                        if (subjectViewBll.AddEmployeeSurveySubjectView(i) < 1)
                        {
                            masterBll.RollbackTransaction();
                            return(-1);
                        }
                    }
                    else
                    {
                        //更新题目
                        if (esvDal.UpdateSurveySubject(i.SubjectInfo) < 1)
                        {
                            masterBll.RollbackTransaction();
                            return(-1);
                        }
                        //更新答案
                        if (UpdataAnswerList(i.SubjectInfo, i.AnswerList.ToList()) < 1)
                        {
                            masterBll.RollbackTransaction();
                            return(-1);
                        }
                    }
                }
                masterBll.CommitTransaction();
                return(1);
            }
            catch (Exception ex)
            {
                Tracer.Debug("调查方案EmployeeSurveyViewBll-UpdateEmployeeSurveyView" + System.DateTime.Now.ToString() + " " + ex.ToString());
                return(-1);
            }
        }
Exemplo n.º 14
0
        /// <inheritdoc />
        public Task <AddOrGetContentHashListResult> AddOrGetContentHashListAsync(
            Context context,
            StrongFingerprint strongFingerprint,
            ContentHashListWithDeterminism contentHashListWithDeterminism,
            CancellationToken cts,
            UrgencyHint urgencyHint)
        {
            return(AddOrGetContentHashListCall.RunAsync(Tracer.MemoizationStoreTracer, new OperationContext(context, cts), strongFingerprint, async() =>
            {
                // TODO: Split this out into separate implementations for WriteThrough vs. WriteBehind (bug 1365340)
                if (WriteThroughContentSession == null)
                {
                    // Guaranteed content is currently only available for BlobSessions. (bug 144396)
                    ContentAvailabilityGuarantee guarantee =
                        BackingContentSession is BlobContentSession
                                ? ContentAvailabilityGuarantee.AllContentBackedByCache
                                : ContentAvailabilityGuarantee.NoContentBackedByCache;

                    return await AddOrGetContentHashListAsync(
                        context,
                        strongFingerprint,
                        contentHashListWithDeterminism,
                        guarantee).ConfigureAwait(false);
                }

                // Ensure that the content exists somewhere before trying to add
                if (!await EnsureContentIsAvailableAsync(
                        context, contentHashListWithDeterminism.ContentHashList.Hashes, cts, urgencyHint).ConfigureAwait(false))
                {
                    return new AddOrGetContentHashListResult(
                        "Referenced content must exist in the cache before a new content hash list is added.");
                }

                DateTime expirationUtc = FingerprintTracker.GenerateNewExpiration();
                var valueToAdd = new ContentHashListWithCacheMetadata(
                    contentHashListWithDeterminism,
                    expirationUtc,
                    ContentAvailabilityGuarantee.NoContentBackedByCache);

                DateTime?rawExpiration = null;
                const int addLimit = 3;
                for (int addAttempts = 0; addAttempts < addLimit; addAttempts++)
                {
                    var debugString = $"Adding contentHashList=[{valueToAdd.ContentHashListWithDeterminism.ContentHashList}] " +
                                      $"determinism=[{valueToAdd.ContentHashListWithDeterminism.Determinism}] to VSTS with " +
                                      $"contentAvailabilityGuarantee=[{valueToAdd.ContentGuarantee}] and expirationUtc=[{expirationUtc}]";
                    Tracer.Debug(context, debugString);
                    ObjectResult <ContentHashListWithCacheMetadata> responseObject =
                        await ContentHashListAdapter.AddContentHashListAsync(
                            context,
                            CacheNamespace,
                            strongFingerprint,
                            valueToAdd).ConfigureAwait(false);

                    if (!responseObject.Succeeded)
                    {
                        return new AddOrGetContentHashListResult(responseObject);
                    }

                    ContentHashListWithCacheMetadata response = responseObject.Data;
                    var inconsistencyErrorMessage = CheckForResponseInconsistency(response);
                    if (inconsistencyErrorMessage != null)
                    {
                        return new AddOrGetContentHashListResult(inconsistencyErrorMessage);
                    }

                    rawExpiration = response.GetRawExpirationTimeUtc();

                    ContentHashList contentHashListToReturn =
                        UnpackContentHashListAfterAdd(contentHashListWithDeterminism.ContentHashList, response);
                    CacheDeterminism determinismToReturn = UnpackDeterminism(response, CacheId);

                    bool needToUpdateExistingValue = await CheckNeedToUpdateExistingValueAsync(
                        context,
                        response,
                        contentHashListToReturn,
                        cts,
                        urgencyHint).ConfigureAwait(false);
                    if (!needToUpdateExistingValue)
                    {
                        SealIfNecessaryAfterUnbackedAddOrGet(context, strongFingerprint, contentHashListWithDeterminism, response);
                        FingerprintTracker.Track(strongFingerprint, rawExpiration);
                        return new AddOrGetContentHashListResult(
                            new ContentHashListWithDeterminism(contentHashListToReturn, determinismToReturn));
                    }

                    var hashOfExistingContentHashList = response.HashOfExistingContentHashList;
                    Tracer.Debug(context, $"Attempting to replace unbacked value with hash {hashOfExistingContentHashList.ToHex()}");
                    valueToAdd = new ContentHashListWithCacheMetadata(
                        contentHashListWithDeterminism,
                        expirationUtc,
                        ContentAvailabilityGuarantee.NoContentBackedByCache,
                        hashOfExistingContentHashList
                        );
                }

                Tracer.Warning(
                    context,
                    $"Lost the AddOrUpdate race {addLimit} times against unbacked values. Returning as though the add succeeded for now.");
                FingerprintTracker.Track(strongFingerprint, rawExpiration);
                return new AddOrGetContentHashListResult(new ContentHashListWithDeterminism(null, CacheDeterminism.None));
            }));
        }
Exemplo n.º 15
0
        private async Task LoadHibernatedSessionsAsync(OperationContext context)
        {
            try
            {
                if (FileSystem.HibernatedSessionsExists(Config.DataRootPath))
                {
                    try
                    {
                        var stopWatch          = Stopwatch.StartNew();
                        var hibernatedSessions = await FileSystem.ReadHibernatedSessionsAsync(Config.DataRootPath);

                        stopWatch.Stop();
                        Tracer.Debug(
                            context, $"Read hibernated sessions from root=[{Config.DataRootPath}] in {stopWatch.Elapsed.TotalMilliseconds}ms");

                        if (hibernatedSessions.Sessions != null && hibernatedSessions.Sessions.Any())
                        {
                            foreach (HibernatedSessionInfo s in hibernatedSessions.Sessions)
                            {
                                Tracer.Debug(context, $"Restoring hibernated session {DescribeHibernatedSessionInfo(s)}.");

                                // If there was no expiration stored, then default to the longer timeout
                                // Otherwise, default to at least the shorter timeout
                                var newExpirationTicks = s.ExpirationUtcTicks == default(long)
                                    ? (DateTime.UtcNow + Config.UnusedSessionTimeout).Ticks
                                    : Math.Max(s.ExpirationUtcTicks, (DateTime.UtcNow + Config.UnusedSessionHeartbeatTimeout).Ticks);

                                var sessionResult = await CreateTempDirectoryAndSessionAsync(
                                    context,
                                    s.Id,
                                    s.Session,
                                    s.Cache,
                                    s.Pin,
                                    s.Capabilities,
                                    newExpirationTicks);

                                if (sessionResult.Succeeded)
                                {
                                    var session = sessionResult.Value.session;
                                    if (s.Pins != null && s.Pins.Any())
                                    {
                                        // Restore pins
                                        var contentHashes = s.Pins.Select(x => new ContentHash(x)).ToList();
                                        if (session is IHibernateContentSession hibernateSession)
                                        {
                                            await hibernateSession.PinBulkAsync(context, contentHashes);
                                        }
                                        else
                                        {
                                            foreach (var contentHash in contentHashes)
                                            {
                                                // Failure should be logged. We can ignore the error in this case.
                                                await session.PinAsync(context, contentHash, CancellationToken.None).IgnoreFailure();
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    Tracer.Warning(context, $"Failed to restore hibernated session, error=[{sessionResult.ErrorMessage}]");
                                }
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        Tracer.Warning(context, $"Failed to read hibernated sessions root=[{Config.DataRootPath}]: {exception}");
                        Tracer.Error(context, exception);
                    }
                    finally
                    {
                        // Done reading hibernated sessions. No matter what happened, remove the file so we don't attempt to load later.
                        Tracer.Debug(context, $"Deleting hibernated sessions from root=[{Config.DataRootPath}].");
                        await FileSystem.DeleteHibernatedSessions(Config.DataRootPath);
                    }

                    _lastSessionId = _sessionHandles.Any() ? _sessionHandles.Keys.Max() : 0;
                }
            }
            catch (Exception exception)
            {
                Tracer.Error(context, exception, "Failed to load hibernated sessions");
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// 删除出差方案
        /// 先删除出差乘坐工具、飞机线路
        /// </summary>
        /// <param name="SolutionID">方案ID</param>
        /// <returns></returns>
        public bool DeleteTravleSolution(string SolutionID)
        {
            try
            {
                dal.BeginTransaction();
                var entitys = (from ent in dal.GetObjects <T_OA_TRAVELSOLUTIONS>()
                               where ent.TRAVELSOLUTIONSID == SolutionID
                               select ent);
                //获取交通工具标准
                var entstandard = from ent in dal.GetObjects <T_OA_TAKETHESTANDARDTRANSPORT>().Include("T_OA_TRAVELSOLUTIONS")
                                  where ent.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == SolutionID
                                  select ent;
                //方案设置
                var apps = from ent in dal.GetObjects <T_OA_PROGRAMAPPLICATIONS>().Include("T_OA_TRAVELSOLUTIONS")
                           where ent.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == SolutionID
                           select ent;

                //删除补贴
                if (entitys.Count() > 0)
                {
                    foreach (var a in entitys)
                    {
                        //删除地区补贴
                        var EntPlane = from ent in dal.GetObjects <T_OA_AREAALLOWANCE>().Include("T_OA_TRAVELSOLUTIONS")
                                       where ent.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == a.TRAVELSOLUTIONSID
                                       select ent;

                        foreach (var k in EntPlane)
                        {
                            dal.DeleteFromContext(k);
                        }
                    }
                }

                //删除交通工具
                if (entstandard.Count() > 0)
                {
                    entstandard.ToList().ForEach(item =>
                    {
                        dal.DeleteFromContext(item);
                    }
                                                 );
                }
                //删除方案设置
                if (apps.Count() > 0)
                {
                    apps.ToList().ForEach(item =>
                    {
                        dal.DeleteFromContext(item);
                    }
                                          );
                }
                dal.SaveContextChanges();
                if (entitys.Count() > 0)
                {
                    var entity = entitys.FirstOrDefault();
                    dal.DeleteFromContext(entity);
                    int i = dal.SaveContextChanges();
                    if (i > 0)
                    {
                        dal.CommitTransaction();
                        return(true);
                    }
                    else
                    {
                        dal.RollbackTransaction();
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                Tracer.Debug("出差方案TravleSolutionBLL-DeleteTravleSolution" + System.DateTime.Now.ToString() + " " + ex.ToString());
                return(false);

                throw (ex);
            }
        }
Exemplo n.º 17
0
        private async Task HandleShutdownDanglingSessionsAsync(Context context)
        {
            try
            {
                if (_sessionHandles.Any())
                {
                    var sessionInfoList = new List <HibernatedSessionInfo>(_sessionHandles.Count);

                    foreach (var(sessionId, handle) in _sessionHandles)
                    {
                        TSession session = handle.Session;

                        if (session is IHibernateContentSession hibernateSession)
                        {
                            var pinnedContentHashes = hibernateSession.EnumeratePinnedContentHashes().Select(x => x.Serialize()).ToList();
                            Tracer.Debug(context, $"Hibernating session {DescribeSession(sessionId, handle)}.");
                            sessionInfoList.Add(new HibernatedSessionInfo(
                                                    sessionId,
                                                    handle.SessionName,
                                                    handle.ImplicitPin,
                                                    handle.CacheName,
                                                    pinnedContentHashes,
                                                    handle.SessionExpirationUtcTicks,
                                                    handle.SessionCapabilities));
                        }
                        else
                        {
                            Tracer.Warning(context, $"Shutdown of non-hibernating dangling session id={sessionId}");
                        }

                        await session.ShutdownAsync(context).ThrowIfFailure();

                        session.Dispose();
                    }

                    if (sessionInfoList.Any())
                    {
                        var hibernatedSessions = new HibernatedSessions(sessionInfoList);

                        try
                        {
                            var sw = Stopwatch.StartNew();
                            await hibernatedSessions.WriteAsync(FileSystem, Config.DataRootPath);

                            sw.Stop();
                            Tracer.Debug(
                                context, $"Wrote hibernated sessions to root=[{Config.DataRootPath}] in {sw.Elapsed.TotalMilliseconds}ms");
                        }
                        catch (Exception exception)
                        {
                            Tracer.Warning(context, $"Failed to write hibernated sessions root=[{Config.DataRootPath}]: {exception.ToString()}");
                            Tracer.Error(context, exception);
                        }
                    }

                    _sessionHandles.Clear();
                }
            }
            catch (Exception exception)
            {
                Tracer.Error(context, exception, "Failed to store hibernated sessions");
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// 修改出差方案
        /// </summary>
        /// <param name="EntTravle"></param>
        /// <param name="TransportObj">交通工具列表</param>
        /// <param name="PlaneObj">飞机路线列表</param>
        /// <param name="IsChange">如果为假 则表示交通工具、飞机路线没做改动 为真则做了改动</param>
        /// <returns></returns>
        public int UpdateTravleSolutionInfo(T_OA_TRAVELSOLUTIONS EntTravle, List <T_OA_TAKETHESTANDARDTRANSPORT> TransportObj, List <string> companyids, bool IsChange)
        {
            try
            {
                bool IsAdd = false;//是否添加动作
                BeginTransaction();
                int result = 0;
                EntTravle.UPDATEDATE = DateTime.Now;
                var users = from ent in dal.GetObjects <T_OA_TRAVELSOLUTIONS>()
                            where ent.TRAVELSOLUTIONSID == EntTravle.TRAVELSOLUTIONSID
                            select ent;
                if (EntTravle.EntityKey == null)
                {
                    if (users.Count() > 0)
                    {
                        var user = users.FirstOrDefault();
                        EntTravle.EntityKey = user.EntityKey;
                    }
                }
                if (!IsChange)
                {
                    int i = dal.Update(EntTravle);
                    if (i > 0)
                    {
                        CommitTransaction();
                        return(i);
                    }
                    else
                    {
                        RollbackTransaction();
                        return(-1);
                    }
                }
                else
                {
                    int ed = Update(EntTravle);
                    if (ed > 0)
                    {
                        IsAdd = true;
                    }
                    var standards = from ent in dal.GetObjects <T_OA_TAKETHESTANDARDTRANSPORT>().Include("T_OA_TRAVELSOLUTIONS")
                                    where ent.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == EntTravle.TRAVELSOLUTIONSID
                                    select ent;
                    var EntObjs = from ent in dal.GetObjects <T_OA_PROGRAMAPPLICATIONS>().Include("T_OA_TRAVELSOLUTIONS")
                                  where ent.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == EntTravle.TRAVELSOLUTIONSID
                                  select ent;
                    List <string> AllCompanyids       = new List <string>();
                    List <string> AllDeleteCompanyids = new List <string>();//删除的公司ID
                    //删除不存在的  公司ID
                    if (EntObjs != null)
                    {
                        if (EntObjs.Count() > 0)
                        {
                            EntObjs.ToList().ForEach(item =>
                            {
                                var ents = from id in companyids
                                           where id == item.COMPANYID
                                           select id;
                                if (ents != null)
                                {
                                    if (!(ents.Count() > 0))
                                    {
                                        AllDeleteCompanyids.Add(item.COMPANYID);//添加删除的公司ID
                                        dal.DeleteFromContext(item);
                                    }
                                }
                            });
                        }
                    }

                    //删除被删除或修改的数据
                    if (TransportObj.Count() > 0)
                    {
                        TransportObj.ForEach(item =>
                        {
                            if (item.ENDPOSTLEVEL == "" && item.TYPEOFTRAVELTOOLS == "" && item.TAKETHETOOLLEVEL == "")
                            {
                                dal.DeleteFromContext(item);
                            }
                        });
                    }

                    int m = dal.SaveContextChanges();

                    if (TransportObj.Count() > 0)
                    {
                        TransportObj.ForEach(item =>
                        {
                            //三个都不为空则表示不是被删除的对象
                            if (item.TAKETHETOOLLEVEL != "" && item.TYPEOFTRAVELTOOLS != "" && item.ENDPOSTLEVEL != "")
                            {
                                if (item.T_OA_TRAVELSOLUTIONS != null)
                                {
                                    if (item.T_OA_TRAVELSOLUTIONS.EntityKey == null)
                                    {
                                        item.T_OA_TRAVELSOLUTIONS.EntityKey = EntTravle.EntityKey;
                                    }
                                }
                                Utility.RefreshEntity(item);
                                dal.AddToContext(item);
                                IsAdd = true;
                            }
                        }
                                             );
                    }

                    if (companyids.Count() > 0)
                    {
                        for (int i = 0; i < companyids.Count(); i++)
                        {
                            string id = companyids[i];
                            //同出差方案下,增加原记录里没有的城市
                            var ents = from a in dal.GetObjects <T_OA_PROGRAMAPPLICATIONS>().Include("T_OA_TRAVELSOLUTIONS")
                                       where a.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == EntTravle.TRAVELSOLUTIONSID && a.COMPANYID == id
                                       select a;
                            if (!(ents.Count() > 0))
                            {
                                T_OA_PROGRAMAPPLICATIONS ent = new T_OA_PROGRAMAPPLICATIONS();
                                ent.PROGRAMAPPLICATIONSID = System.Guid.NewGuid().ToString();
                                ent.T_OA_TRAVELSOLUTIONSReference.EntityKey =
                                    new System.Data.EntityKey("SMT_OA_EFModelContext.T_OA_TRAVELSOLUTIONS", "TRAVELSOLUTIONSID", EntTravle.TRAVELSOLUTIONSID);
                                ent.COMPANYID         = id;
                                ent.OWNERCOMPANYID    = EntTravle.OWNERCOMPANYID;
                                ent.OWNERDEPARTMENTID = EntTravle.OWNERDEPARTMENTID;
                                ent.OWNERPOSTID       = EntTravle.OWNERPOSTID;
                                ent.CREATEUSERID      = EntTravle.CREATEUSERID;
                                ent.CREATEDATE        = System.DateTime.Now;

                                Utility.RefreshEntity(ent);
                                dal.AddToContext(ent);
                                IsAdd = true;
                            }
                        }
                        //同出差方案下,删除已经不需要的城市
                        //var delEnts = from a in dal.GetObjects<T_OA_PROGRAMAPPLICATIONS>()
                        //              where a.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == EntTravle.TRAVELSOLUTIONSID && !companyids.Contains(a.COMPANYID)
                        //              select a;
                        //var delEnts1 = from a in dal.GetObjects<T_OA_PROGRAMAPPLICATIONS>().Include("T_OA_TRAVELSOLUTIONID")
                        //              where a.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == EntTravle.TRAVELSOLUTIONSID
                        //              select a;
                        //var delEnts2 = from a in dal.GetObjects<T_OA_PROGRAMAPPLICATIONS>()
                        //              where !companyids.Contains(a.COMPANYID)
                        //              select a;
                        //if (delEnts.Count() > 0)
                        //{
                        //    foreach (var de in delEnts)
                        //    {
                        //        dal.DeleteFromContext(de);
                        //    }
                        //    IsAdd = true;
                        //}
                    }
                    if (IsAdd)
                    {
                        result = dal.SaveContextChanges();
                        if (result > 0 || m > 0)
                        {
                            dal.CommitTransaction();
                            result = result == 0 ? m : result;
                        }
                        else
                        {
                            dal.RollbackTransaction();
                        }
                    }
                    else
                    {
                        //只删除了数据  给没有添加数据
                        if (m > 0)
                        {
                            result = m;//将结果传递出来
                            dal.CommitTransaction();
                        }
                        else
                        {
                            dal.RollbackTransaction();
                        }
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                Tracer.Debug("出差方案TravleSolutionBLL-UpdateTravleSolutionInfo" + System.DateTime.Now.ToString() + " " + ex.ToString());
                RollbackTransaction();
                return(-1);
            }
        }
Exemplo n.º 19
0
 public void AfterRollback()
 {
     Tracer.Debug("SessionCloseSynchronization AfterRollback called for Session: " + session.SessionId);
     session.DoClose();
 }
Exemplo n.º 20
0
        /// <summary>
        /// 添加解决方案
        /// 先添加解决方案然后再添加交通工具、飞机线路
        /// 必须使用事务处理
        /// </summary>
        /// <param name="EntObj">解决方案实体</param>
        /// <param name="ListTransport">交通工具标准列表</param>
        /// <param name="ListPlane">飞机线路列表</param>
        /// <returns></returns>
        public string AddTravleSolution(T_OA_TRAVELSOLUTIONS EntObj, List <T_OA_TAKETHESTANDARDTRANSPORT> ListTransport, List <string> companyids)
        {
            string StrReturn = "";

            try
            {
                dal.BeginTransaction();
                //添加出差方案
                int k = dal.Add(EntObj);
                EntObj.CREATEDATE = DateTime.Now;
                EntObj.CREATEDATE = DateTime.Now;

                ListTransport.ForEach(item =>
                {
                    item.CREATEDATE = System.DateTime.Now;
                    //EntObj.T_OA_TAKETHESTANDARDTRANSPORT.Add(item);
                    item.T_OA_TRAVELSOLUTIONS = null;
                    item.T_OA_TRAVELSOLUTIONSReference.EntityKey =
                        new System.Data.EntityKey("SMT_OA_EFModelContext.T_OA_TRAVELSOLUTIONS", "TRAVELSOLUTIONSID", EntObj.TRAVELSOLUTIONSID);

                    Utility.RefreshEntity(item);
                    dal.AddToContext(item);
                });

                //int k = dal.Add(EntObj);
                if (companyids.Count() > 0)
                {
                    for (int i = 0; i < companyids.Count(); i++)
                    {
                        string id   = companyids[i];
                        var    ents = from a in dal.GetObjects <T_OA_PROGRAMAPPLICATIONS>().Include("T_OA_TRAVELSOLUTIONS")
                                      where a.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == EntObj.TRAVELSOLUTIONSID && a.COMPANYID == id
                                      select a;
                        var solution = from b in dal.GetObjects <T_OA_TRAVELSOLUTIONS>()
                                       where b.TRAVELSOLUTIONSID == EntObj.TRAVELSOLUTIONSID
                                       select b;
                        if (!(ents.Count() > 0))
                        {
                            T_OA_PROGRAMAPPLICATIONS ent = new T_OA_PROGRAMAPPLICATIONS();


                            ent.PROGRAMAPPLICATIONSID = System.Guid.NewGuid().ToString();
                            ent.T_OA_TRAVELSOLUTIONSReference.EntityKey =
                                new System.Data.EntityKey("SMT_OA_EFModelContext.T_OA_TRAVELSOLUTIONS", "TRAVELSOLUTIONSID", EntObj.TRAVELSOLUTIONSID);

                            ent.COMPANYID         = id;
                            ent.CREATEUSERID      = EntObj.CREATEUSERID;
                            ent.OWNERCOMPANYID    = EntObj.OWNERCOMPANYID;
                            ent.OWNERDEPARTMENTID = EntObj.OWNERDEPARTMENTID;
                            ent.OWNERPOSTID       = EntObj.OWNERPOSTID;
                            ent.CREATEDATE        = System.DateTime.Now;
                            dal.AddToContext(ent);
                        }
                    }
                }

                int n = dal.SaveContextChanges();
                StrReturn = (k > 0 && n > 0) ? "" : "ERROR";

                dal.CommitTransaction();
            }
            catch (Exception ex)
            {
                dal.RollbackTransaction();
                Tracer.Debug("出差方案TravleSolutionBLL-AddTravleSolution" + System.DateTime.Now.ToString() + " " + ex.ToString());
                StrReturn = "ERROR";
            }
            return(StrReturn);
        }
        public void Begin(Transaction transaction)
        {
            lock (syncObject)
            {
                dtcControlEvent.Reset();

                Tracer.Debug("Begin notification received");

                if (InNetTransaction)
                {
                    throw new TransactionInProgressException("A Transaction is already in Progress");
                }

                try
                {
                    Guid rmId = ResourceManagerGuid;

                    // Enlist this object in the transaction.
                    this.currentEnlistment =
                        transaction.EnlistDurable(rmId, this, EnlistmentOptions.None);

                    // In case of a exception in the current method the transaction will be rolled back.
                    // Until Begin Transaction is completed we consider to be in a rollback scenario.
                    this.netTxState = TxState.Pending;

                    Tracer.Debug("Enlisted in Durable Transaction with RM Id: " + rmId);

                    TransactionInformation txInfo = transaction.TransactionInformation;

                    XATransactionId xaId = new XATransactionId();
                    this.transactionId = xaId;

                    if (txInfo.DistributedIdentifier != Guid.Empty)
                    {
                        xaId.GlobalTransactionId = txInfo.DistributedIdentifier.ToByteArray();
                        xaId.BranchQualifier     = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
                    }
                    else
                    {
                        xaId.GlobalTransactionId = Encoding.UTF8.GetBytes(txInfo.LocalIdentifier);
                        xaId.BranchQualifier     = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
                    }

                    // Now notify the broker that a new XA'ish transaction has started.
                    TransactionInfo info = new TransactionInfo();
                    info.ConnectionId  = this.connection.ConnectionId;
                    info.TransactionId = this.transactionId;
                    info.Type          = (int)TransactionType.Begin;

                    this.session.Connection.Oneway(info);

                    // Begin Transaction is completed successfully. Change to transaction active state now.
                    this.netTxState = TxState.Active;

                    SignalTransactionStarted();

                    if (Tracer.IsDebugEnabled)
                    {
                        Tracer.Debug("Began XA'ish Transaction:" + xaId);
                    }
                }
                catch (Exception)
                {
                    // When in pending state the rollback will signal that a new transaction can be started. Otherwise do it here.
                    if (netTxState != TxState.Pending)
                    {
                        netTxState = TxState.None;
                        dtcControlEvent.Set();
                    }
                    throw;
                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// 复制出差方案
        /// </summary>
        /// <param name="EntObj">方案实体</param>
        /// <param name="OldtravleSolutionId">旧方案ID</param>
        /// <param name="companyids">公司ID</param>
        /// <returns></returns>
        public string GetCopyTravleSolution(T_OA_TRAVELSOLUTIONS EntObj, string OldtravleSolutionId)
        {
            string StrReturn = string.Empty;

            try
            {
                dal.BeginTransaction();

                //添加方案信息
                int i = dal.Add(EntObj);

                if (i > 0)
                {
                    //根据出差方案ID查询出交通工具标准
                    var ents = from a in dal.GetObjects <T_OA_TAKETHESTANDARDTRANSPORT>().Include("T_OA_TRAVELSOLUTIONS")
                               where a.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == OldtravleSolutionId
                               select a;

                    if (ents.Count() > 0)
                    {
                        foreach (T_OA_TAKETHESTANDARDTRANSPORT obj in ents)
                        {
                            T_OA_TAKETHESTANDARDTRANSPORT tent = new T_OA_TAKETHESTANDARDTRANSPORT();

                            tent.TAKETHESTANDARDTRANSPORTID = System.Guid.NewGuid().ToString();
                            tent.T_OA_TRAVELSOLUTIONSReference.EntityKey =
                                new System.Data.EntityKey("SMT_OA_EFModelContext.T_OA_TRAVELSOLUTIONS", "TRAVELSOLUTIONSID", EntObj.TRAVELSOLUTIONSID);

                            tent.ENDPOSTLEVEL      = obj.ENDPOSTLEVEL;
                            tent.TYPEOFTRAVELTOOLS = obj.TYPEOFTRAVELTOOLS;
                            tent.TAKETHETOOLLEVEL  = obj.TAKETHETOOLLEVEL;
                            tent.OWNERCOMPANYID    = EntObj.OWNERCOMPANYID;
                            tent.OWNERDEPARTMENTID = EntObj.OWNERDEPARTMENTID;
                            tent.OWNERPOSTID       = EntObj.OWNERPOSTID;
                            tent.CREATEUSERID      = EntObj.CREATEUSERID;
                            tent.CREATEDATE        = System.DateTime.Now;
                            dal.AddToContext(tent);
                        }

                        //将出差方案应用到当前公司
                        T_OA_PROGRAMAPPLICATIONS pent = new T_OA_PROGRAMAPPLICATIONS();

                        pent.PROGRAMAPPLICATIONSID = System.Guid.NewGuid().ToString();
                        pent.T_OA_TRAVELSOLUTIONSReference.EntityKey =
                            new System.Data.EntityKey("SMT_OA_EFModelContext.T_OA_TRAVELSOLUTIONS", "TRAVELSOLUTIONSID", EntObj.TRAVELSOLUTIONSID);
                        pent.COMPANYID         = EntObj.OWNERCOMPANYID;
                        pent.CREATEUSERID      = EntObj.CREATEUSERID;
                        pent.OWNERCOMPANYID    = EntObj.CREATECOMPANYID;
                        pent.OWNERDEPARTMENTID = EntObj.CREATEDEPARTMENTID;
                        pent.OWNERPOSTID       = EntObj.CREATEPOSTID;
                        pent.CREATEDATE        = System.DateTime.Now;

                        dal.Add(pent);
                    }

                    //根据出差方案ID查询城市分类
                    var area = from a in dal.GetObjects <T_OA_AREADIFFERENCE>().Include("T_OA_TRAVELSOLUTIONS")
                               where a.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == OldtravleSolutionId
                               select a;

                    if (area.Count() > 0)
                    {
                        foreach (T_OA_AREADIFFERENCE obj in area)
                        {
                            //    T_OA_AREADIFFERENCE aread = new T_OA_AREADIFFERENCE();

                            //    aread.AREADIFFERENCEID = System.Guid.NewGuid().ToString();//城市分类ID
                            //    aread.T_OA_TRAVELSOLUTIONSReference.EntityKey =
                            //    new System.Data.EntityKey("SMT_OA_EFModelContext.T_OA_TRAVELSOLUTIONS", "TRAVELSOLUTIONSID", EntObj.TRAVELSOLUTIONSID);//方案ID

                            //    aread.AREACATEGORY = obj.AREACATEGORY;//城市分类名
                            //    aread.AREAINDEX = obj.AREAINDEX;//分类序号
                            //    aread.OWNERCOMPANYID = EntObj.OWNERCOMPANYID;//所属公司
                            //    aread.OWNERDEPARTMENTID = EntObj.OWNERDEPARTMENTID;//所属部门
                            //    aread.OWNERPOSTID = EntObj.OWNERPOSTID;//所属岗位
                            //    aread.OWNERID = EntObj.OWNERID;//所属人ID
                            //    aread.CREATEUSERID = EntObj.CREATEUSERID;//创建人
                            //    aread.CREATEUSERNAME = EntObj.CREATEUSERNAME;//创建人姓名
                            //    aread.CREATECOMPANYID = EntObj.CREATECOMPANYID;//创建公司
                            //    aread.CREATEDEPARTMENTID = EntObj.CREATEDEPARTMENTID;//创建部门
                            //    aread.CREATEPOSTID = EntObj.CREATEPOSTID;//创建岗位
                            //    aread.CREATEDATE = System.DateTime.Now;//创建时间

                            //    int add = dal.Add(aread);

                            //if (add > 0)
                            //{
                            //根据城市分类ID、方案ID查询补贴标准
                            var areace = from a in dal.GetObjects <T_OA_AREAALLOWANCE>().Include("T_OA_AREADIFFERENCE").Include("T_OA_TRAVELSOLUTIONS")
                                         where a.T_OA_AREADIFFERENCE.AREADIFFERENCEID == obj.AREADIFFERENCEID &&
                                         a.T_OA_TRAVELSOLUTIONS.TRAVELSOLUTIONSID == OldtravleSolutionId
                                         select a;

                            foreach (T_OA_AREAALLOWANCE obje in areace)
                            {
                                T_OA_AREAALLOWANCE areadce = new T_OA_AREAALLOWANCE();

                                areadce.AREAALLOWANCEID = System.Guid.NewGuid().ToString();                                                                 //分类补贴ID
                                areadce.T_OA_AREADIFFERENCEReference.EntityKey =
                                    new System.Data.EntityKey("SMT_OA_EFModelContext.T_OA_AREADIFFERENCE", "AREADIFFERENCEID", obj.AREADIFFERENCEID);       //分类ID
                                areadce.T_OA_TRAVELSOLUTIONSReference.EntityKey =
                                    new System.Data.EntityKey("SMT_OA_EFModelContext.T_OA_TRAVELSOLUTIONS", "TRAVELSOLUTIONSID", EntObj.TRAVELSOLUTIONSID); //方案ID
                                areadce.POSTLEVEL               = obje.POSTLEVEL;                                                                           //岗位等级
                                areadce.ACCOMMODATION           = obje.ACCOMMODATION;                                                                       //住宿补贴
                                areadce.TRANSPORTATIONSUBSIDIES = obje.TRANSPORTATIONSUBSIDIES;                                                             //交通伙食补贴
                                areadce.OWNERCOMPANYID          = EntObj.OWNERCOMPANYID;                                                                    //所属公司
                                areadce.OWNERDEPARTMENTID       = EntObj.OWNERDEPARTMENTID;                                                                 //所属部门
                                areadce.OWNERPOSTID             = EntObj.OWNERPOSTID;                                                                       //所属岗位
                                areadce.OWNERID      = EntObj.OWNERID;                                                                                      //所属人ID
                                areadce.CREATEUSERID = EntObj.CREATEUSERID;                                                                                 //创建人
                                areadce.CREATEDATE   = System.DateTime.Now;                                                                                 //创建时间

                                dal.AddToContext(areadce);
                            }

                            ////根据城市分类ID查询分类城市
                            //var areacity = from a in dal.GetObjects<T_OA_AREACITY>().Include("T_OA_AREADIFFERENCE")
                            //               where a.T_OA_AREADIFFERENCE.AREADIFFERENCEID == obj.AREADIFFERENCEID
                            //               select a;

                            //foreach (T_OA_AREACITY objc in areacity)
                            //{
                            //    T_OA_AREACITY arctiy = new T_OA_AREACITY();

                            //    arctiy.AREACITYID = System.Guid.NewGuid().ToString();//分类城市ID
                            //    arctiy.T_OA_AREADIFFERENCEReference.EntityKey =
                            //    new System.Data.EntityKey("SMT_OA_EFModelContext.T_OA_AREADIFFERENCE", "AREADIFFERENCEID", aread.AREADIFFERENCEID);//分类ID

                            //    arctiy.CITY = objc.CITY;//所在地城市
                            //    arctiy.CREATEUSERID = EntObj.CREATEUSERID;//创建人
                            //    arctiy.CREATEDATE = System.DateTime.Now;//创建时间

                            //    dal.AddToContext(arctiy);
                            //}
                        }
                        //}
                    }
                    int n = dal.SaveContextChanges();
                    if (i > 0 && n > 0)
                    {
                        dal.CommitTransaction();
                    }
                    else
                    {
                        StrReturn = "ERROR";
                        dal.RollbackTransaction();
                    }
                }
            }
            catch (Exception ex)
            {
                dal.RollbackTransaction();
                Tracer.Debug("出差方案TravleSolutionBLL-AddTravleSolution" + System.DateTime.Now.ToString() + " " + ex.ToString());
                StrReturn = "ERROR";
            }
            return(StrReturn);
        }
        public void Rollback(Enlistment enlistment)
        {
            lock (this.syncObject)
            {
                try
                {
                    Tracer.Debug("Rollback notification received for TX id: " + this.transactionId);

                    if (this.transactionId != null)
                    {
                        BeforeEnd();

                        // Now notify the broker that a new XA'ish transaction has started.
                        TransactionInfo info = new TransactionInfo();
                        info.ConnectionId  = this.connection.ConnectionId;
                        info.TransactionId = this.transactionId;
                        info.Type          = (int)TransactionType.End;

                        this.connection.CheckConnected();
                        this.connection.SyncRequest((TransactionInfo)info.Clone());

                        info.Type = (int)TransactionType.Rollback;
                        this.connection.CheckConnected();
                        this.connection.SyncRequest((TransactionInfo)info.Clone());

                        Tracer.Debug("Transaction Rollback Done TX id: " + this.transactionId);

                        RecoveryLogger.LogRecovered(this.transactionId as XATransactionId);

                        // if server responds that nothing needs to be done, then reply done.
                        enlistment.Done();

                        AfterRollback();
                    }
                }
                catch (Exception ex)
                {
                    Tracer.DebugFormat("Transaction[{0}] Rollback failed with error: {1}",
                                       this.transactionId, ex.Message);
                    AfterRollback();
                    try
                    {
                        this.connection.OnAsyncException(ex);
                    }
                    catch (Exception error)
                    {
                        Tracer.Error(error.ToString());
                    }
                }
                finally
                {
                    this.currentEnlistment = null;
                    this.transactionId     = null;
                    this.netTxState        = TxState.None;

                    CountDownLatch latch = this.recoveryComplete;
                    if (latch != null)
                    {
                        latch.countDown();
                    }

                    this.dtcControlEvent.Set();
                }
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// 删除地区分类,可同时删除多行记录
        /// </summary>
        /// <param name="AreaCategoryIDs">AreaCategoryIDs</param>
        /// <returns></returns>
        public int AreaCategoryDelete(string[] AreaCategoryIDs)
        {
            try
            {
                int i = -1;
                dal.BeginTransaction();
                foreach (string id in AreaCategoryIDs)
                {
                    bool citysign      = true;
                    bool allowancesign = true;
                    var  cityent       = from a in dal.GetObjects <T_OA_AREACITY>().Include("T_OA_AREADIFFERENCE")
                                         where a.T_OA_AREADIFFERENCE.AREADIFFERENCEID == id
                                         select a;
                    if (cityent.Count() > 0)
                    {
                        foreach (T_OA_AREACITY city in cityent)
                        {
                            dal.DeleteFromContext(city);
                        }
                        citysign = dal.SaveContextChanges() >= 0 ? true : false;
                    }

                    if (citysign)
                    {
                        var allowanceent = from a in dal.GetObjects <T_OA_AREAALLOWANCE>().Include("T_OA_AREADIFFERENCE")
                                           where a.T_OA_AREADIFFERENCE.AREADIFFERENCEID == id
                                           select a;
                        if (allowanceent.Count() > 0)
                        {
                            foreach (T_OA_AREAALLOWANCE allowance in allowanceent)
                            {
                                dal.DeleteFromContext(allowance);
                            }
                            allowancesign = dal.SaveContextChanges() >= 0 ? true : false;
                        }
                    }

                    if (allowancesign)
                    {
                        var ents = from e in dal.GetObjects()
                                   where e.AREADIFFERENCEID == id
                                   select e;
                        var ent = ents.Count() > 0 ? ents.FirstOrDefault() : null;

                        if (ent != null)
                        {
                            i += dal.Delete(ent);
                            //dal.DeleteFromContext(ent);
                        }
                    }
                }
                //int i= dal.SaveContextChanges();
                dal.CommitTransaction();
                return(i);
            }
            catch (Exception ex)
            {
                dal.RollbackTransaction();
                Tracer.Debug("城市分类AreaCategoryBLL-AreaCategoryDelete" + System.DateTime.Now.ToString() + " " + ex.ToString());
                throw ex;
            }
        }
        private bool DoConnect()
        {
            lock (reconnectMutex)
            {
                if (ConnectedTransport != null || disposed || connectionFailure != null)
                {
                    return(false);
                }
                else
                {
                    List <Uri> connectList = ConnectList;
                    if (connectList.Count == 0)
                    {
                        Failure = new NMSConnectionException("No URIs available for connection.");
                    }
                    else
                    {
                        if (!UseExponentialBackOff)
                        {
                            ReconnectDelay = InitialReconnectDelay;
                        }

                        try
                        {
                            backupMutex.WaitOne();
                            if (Backup && backups.Count != 0)
                            {
                                BackupTransport bt = backups[0];
                                backups.RemoveAt(0);
                                ITransport t   = bt.Transport;
                                Uri        uri = bt.Uri;
                                t.Command   = new CommandHandler(OnCommand);
                                t.Exception = new ExceptionHandler(OnException);
                                try
                                {
                                    if (started)
                                    {
                                        RestoreTransport(t);
                                    }
                                    ReconnectDelay            = InitialReconnectDelay;
                                    failedConnectTransportURI = null;
                                    ConnectedTransportURI     = uri;
                                    ConnectedTransport        = t;
                                    connectFailures           = 0;
                                    connected = true;
                                    if (this.Resumed != null)
                                    {
                                        this.Resumed(t);
                                    }
                                    Tracer.InfoFormat("Successfully reconnected to backup {0}", uri.ToString());
                                    return(false);
                                }
                                catch (Exception e)
                                {
                                    Tracer.DebugFormat("Backup transport failed: {0}", e.Message);
                                }
                            }
                        }
                        finally
                        {
                            backupMutex.ReleaseMutex();
                        }

                        ManualResetEvent allDone   = new ManualResetEvent(false);
                        ITransport       transport = null;
                        Uri    chosenUri           = null;
                        object syncLock            = new object();

                        try
                        {
                            foreach (Uri uri in connectList)
                            {
                                if (ConnectedTransport != null || disposed)
                                {
                                    break;
                                }

                                Tracer.DebugFormat("Attempting connect to: {0}", uri);

                                if (asyncConnect)
                                {
                                    // set connector up
                                    Connector connector = new Connector(
                                        delegate(ITransport transportToUse, Uri uriToUse) {
                                        if (transport == null)
                                        {
                                            lock (syncLock)
                                            {
                                                if (transport == null)
                                                {
                                                    //the transport has not yet been set asynchronously so set it
                                                    transport = transportToUse;
                                                    chosenUri = uriToUse;
                                                }
                                                //notify issuing thread to move on
                                                allDone.Set();
                                            }
                                        }
                                    }, uri, this);

                                    // initiate a thread to try connecting to broker
                                    Thread thread = new Thread(connector.DoConnect);
                                    thread.Name = uri.ToString();
                                    thread.Start();
                                }
                                else
                                {
                                    // synchronous connect
                                    try
                                    {
                                        Tracer.DebugFormat("Attempting connect to: {0}", uri.ToString());
                                        transport = TransportFactory.CompositeConnect(uri);
                                        chosenUri = transport.RemoteAddress;
                                        break;
                                    }
                                    catch (Exception e)
                                    {
                                        Failure = e;
                                        Tracer.DebugFormat("Connect fail to: {0}, reason: {1}", uri, e.Message);
                                    }
                                }
                            }

                            if (asyncConnect)
                            {
                                // now wait for transport to be populated, but timeout eventually
                                allDone.WaitOne(asyncTimeout, false);
                            }

                            if (transport != null)
                            {
                                transport.Command   = new CommandHandler(OnCommand);
                                transport.Exception = new ExceptionHandler(OnException);
                                transport.Start();

                                if (started)
                                {
                                    RestoreTransport(transport);
                                }

                                if (this.Resumed != null)
                                {
                                    this.Resumed(transport);
                                }

                                Tracer.Debug("Connection established");
                                ReconnectDelay        = InitialReconnectDelay;
                                ConnectedTransportURI = chosenUri;
                                ConnectedTransport    = transport;
                                connectFailures       = 0;
                                connected             = true;

                                if (firstConnection)
                                {
                                    firstConnection = false;
                                    Tracer.InfoFormat("Successfully connected to: {0}", chosenUri.ToString());
                                }
                                else
                                {
                                    Tracer.InfoFormat("Successfully reconnected to: {0}", chosenUri.ToString());
                                }

                                return(false);
                            }

                            if (asyncConnect)
                            {
                                Tracer.DebugFormat("Connect failed after waiting for asynchronous callback.");
                            }
                        }
                        catch (Exception e)
                        {
                            Failure = e;
                            Tracer.DebugFormat("Connect attempt failed.  Reason: {0}", e.Message);
                        }
                    }

                    if (MaxReconnectAttempts > 0 && ++connectFailures >= MaxReconnectAttempts)
                    {
                        Tracer.ErrorFormat("Failed to connect to transport after {0} attempt(s)", connectFailures);
                        connectionFailure = Failure;
                        this.Exception(this, connectionFailure);
                        return(false);
                    }
                }
            }

            if (!disposed)
            {
                Tracer.DebugFormat("Waiting {0}ms before attempting connection.", ReconnectDelay);
                lock (sleepMutex)
                {
                    try
                    {
                        Thread.Sleep(ReconnectDelay);
                    }
                    catch (ThreadInterruptedException)
                    {
                    }
                }

                if (UseExponentialBackOff)
                {
                    // Exponential increment of reconnect delay.
                    ReconnectDelay *= ReconnectDelayExponent;
                    if (ReconnectDelay > MaxReconnectDelay)
                    {
                        ReconnectDelay = MaxReconnectDelay;
                    }
                }
            }
            return(!disposed);
        }
        public Task <Module[]> GetInstalledAircraftModulesAsync()
        {
            Tracer.Info("Searching DCS for installed modules.");

            var settingsService = _container.Resolve <ISettingsService>();
            var install         = settingsService.SelectedInstall;

            if (!install.IsValidInstall)
            {
                Tracer.Info("Current install is invalid, aborting...");
                return(Task.FromResult(_modules.Values.ToArray()));
            }

            return(Task.Run(() =>
            {
                var autoUpdateModules = new List <string>(install.Modules)
                {
                    "Su-25T",
                    "TF-51D"
                };

                var aircraftFolders = Directory.GetDirectories(Path.Combine(install.Directory, "Mods//aircraft"));

                foreach (var folder in aircraftFolders)
                {
                    using (var lua = new NLua.Lua())
                    {
                        lua.State.Encoding = Encoding.UTF8;

                        var entryPath = Path.Combine(folder, "entry.lua");

                        lua.DoString(
                            @"function _(s) return s end
                                function _(s) return s end
                                function mount_vfs_liveries_path() end
                                function mount_vfs_texture_path() end
                                function mount_vfs_sound_path() end
                                function mount_vfs_model_path() end
                                function make_view_settings() end
                                function set_manual_path() end
                                function dofile() end
                                function plugin_done() end
                                function make_flyable() end
                                function MAC_flyable() end
                                function turn_on_waypoint_panel() end
                                AV8BFM = {}
                                F86FM = {}
                                F5E = {}
                                FA18C = {}
                                F15FM = {}
                                F16C = {}
                                FM = {}
                                M2KFM = {}
                                Mig15FM = {}
                                MIG19PFM = {}
                                SA342FM = {}
                                JF17_FM = {}
                                function add_plugin_systems() end
                                " + $"__DCS_VERSION__ = \"{install.Version}\"");

                        var directoryName = Path.GetDirectoryName(folder);

                        lua.DoString($"current_mod_path = \"{folder.Replace("\\", "\\\\")}\"");

                        var moduleId = string.Empty;
                        var skinsPath = string.Empty;
                        var displayName = string.Empty;

                        lua["declare_plugin"] = new Action <string, LuaTable>((id, description) =>
                        {
                            if (description.Keys.OfType <string>().All(k => k != "installed" && k != "update_id"))
                            {
                                return;
                            }

                            moduleId =
                                description.Keys.OfType <string>().All(k => k != "update_id")
                                    ? description["fileMenuName"]?.ToString()
                                    : description["update_id"]?.ToString();

                            var skinsTable = description["Skins"] as LuaTable;

                            if (skinsTable != null)
                            {
                                skinsPath = ((LuaTable)skinsTable[1])["dir"].ToString();
                            }

                            var missionsTable = description["Missions"] as LuaTable;

                            if (missionsTable != null)
                            {
                                displayName = ((LuaTable)missionsTable[1])["name"].ToString();
                            }
                        });

                        var makeFlyableAction = new Action <string, string, LuaTable, string>((a, b, c, d) =>
                        {
                            if (displayName.Contains("_hornet"))
                            {
                                displayName = displayName.Split('_')[0];
                            }

                            if (_modules.ContainsKey($"{moduleId}_{a}"))
                            {
                                return;
                            }

                            if (!string.IsNullOrEmpty(moduleId) && autoUpdateModules.Contains(moduleId) && moduleId != "FC3")
                            {
                                var module = new Module
                                {
                                    ModuleId = moduleId,
                                    DisplayName = displayName,
                                    LoadingImagePath = Path.Combine(folder, skinsPath, "ME", "loading-window.png"),
                                    MainMenuLogoPath = Path.Combine(folder, skinsPath, "ME", "MainMenulogo.png"),
                                    BaseFolderPath = folder,
                                    IconPath = Path.Combine(folder, skinsPath, "icon.png"),
                                };

                                _modules.Add($"{moduleId}_{a}", module);

                                Tracer.Debug($"Found module {displayName}.");
                            }
                            else if (moduleId == "FC3")
                            {
                                //fc3Added = true;

                                var module = new Module
                                {
                                    ModuleId = moduleId,
                                    DisplayName = displayName,
                                    IsFC3 = true,
                                    FC3ModuleId = a,
                                    LoadingImagePath = Path.Combine(folder, skinsPath, "ME", "loading-window.png"),
                                    MainMenuLogoPath = Path.Combine(folder, skinsPath, "ME", "MainMenulogo.png"),
                                    BaseFolderPath = folder,
                                    IconPath = Path.Combine(folder, skinsPath, "icon.png"),
                                };

                                _modules.Add($"{moduleId}_{a}", module);

                                Tracer.Debug($"Found module {displayName} {a}.");
                            }
                            else
                            {
                                Tracer.Debug($"Not loading module '{moduleId} - {displayName}' parameters ('{a}', '{b}', '{d}'.");
                            }
                        });

                        lua["make_flyable"] = makeFlyableAction;
                        lua["MAC_flyable"] = makeFlyableAction;

                        try
                        {
                            lua.DoFile(entryPath);
                        }
                        catch (Exception e)
                        {
                            Tracer.Error(e.Message);
                        }
                    }
                }

                return _modules.Values.ToArray();
            }));
        }
Exemplo n.º 27
0
 private void Trace(ResultBase result, Context context, string message)
 {
     _tracer.Error(context, $"{message}, result=[{result}]");
     _tracer.Debug(context, $"{result.Diagnostics}");
 }
        private void DoRestoreTransactions(ITransport transport, ConnectionState connectionState)
        {
            AtomicCollection <TransactionState> transactionStates = connectionState.TransactionStates;
            List <TransactionInfo> toRollback = new List <TransactionInfo>();

            foreach (TransactionState transactionState in transactionStates)
            {
                // rollback any completed transactions - no way to know if commit got there
                // or if reply went missing
                if (transactionState.Commands.Count != 0)
                {
                    Command lastCommand = transactionState.Commands[transactionState.Commands.Count - 1];
                    if (lastCommand.IsTransactionInfo)
                    {
                        TransactionInfo transactionInfo = lastCommand as TransactionInfo;
                        if (transactionInfo.Type == TransactionInfo.COMMIT_ONE_PHASE)
                        {
                            if (Tracer.IsDebugEnabled)
                            {
                                Tracer.Debug("rolling back potentially completed tx: " +
                                             transactionState.Id);
                            }
                            toRollback.Add(transactionInfo);
                            continue;
                        }
                    }
                }

                // replay the add and remove of short lived producers that may have been
                // involved in the transaction
                foreach (ProducerState producerState in transactionState.ProducerStates)
                {
                    if (Tracer.IsDebugEnabled)
                    {
                        Tracer.Debug("tx replay producer :" + producerState.Info);
                    }
                    transport.Oneway(producerState.Info);
                }

                foreach (Command command in transactionState.Commands)
                {
                    if (Tracer.IsDebugEnabled)
                    {
                        Tracer.Debug("tx replay: " + command);
                    }
                    transport.Oneway(command);
                }

                foreach (ProducerState producerState in transactionState.ProducerStates)
                {
                    if (Tracer.IsDebugEnabled)
                    {
                        Tracer.Debug("tx remove replayed producer :" + producerState.Info);
                    }

                    RemoveInfo producerRemove = new RemoveInfo();
                    producerRemove.ObjectId = producerState.Info.ProducerId;
                    transport.Oneway(producerRemove);
                }
            }

            foreach (TransactionInfo command in toRollback)
            {
                // respond to the outstanding commit
                ExceptionResponse response = new ExceptionResponse();
                response.Exception         = new BrokerError();
                response.Exception.Message =
                    "Transaction completion in doubt due to failover. Forcing rollback of " + command.TransactionId;
                response.Exception.ExceptionClass = (new TransactionRolledBackException()).GetType().FullName;
                response.CorrelationId            = command.CommandId;
                transport.CommandAsync(transport, response).GetAsyncResult();
            }
        }
Exemplo n.º 29
0
 //[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 public List <V_BumfCompanySendDoc> GetSendDocInfosListByWorkFlowForMVC(int pageIndex, int pageSize, string sort, string filterString, object[] paras, ref int pageCount, string checkState, LoginUserInfo loginUserInfo, ref int recordsTotal)
 {
     try
     {
         using (BumfCompanySendDocManagementBll SendDocBll = new BumfCompanySendDocManagementBll())
         {
             //HouseInfoManagerBll bll = new HouseInfoManagerBll();
             //List<string> postIDs = new List<string>();
             //postIDs.Add("0c7a189f-fdbe-4632-a092-52c3463e0c7b");
             //postIDs.Add("6dbed528-5d9f-42f9-8278-178c4e5d8b1c");
             //postIDs.Add("9e0bf63a-023f-4b6a-a18e-fa5dbe057d8b");
             //List<string> postID1s = new List<string>();
             //postID1s.Add("c1f72286-eee5-45bd-bded-5993e8a317c9");
             //postID1s.Add("06aa0d8b-b32e-4eee-9d3c-db08b6a3b1fd");
             //List<string> postID2s = new List<string>();
             //postID2s.Add("cafdca8a-c630-4475-a65d-490d052dca36");
             //postID2s.Add("bac05c76-0f5b-40ae-b73b-8be541ed35ed");
             //int aa = 99999;
             //bll.GetHouseAndNoticeInfoToMobile(pageIndex, pageSize, ref pageCount, ref aa, "6ba49ec8-feb0-4f78-b801-2b8ea5387ab3", postID1s, postID2s, postID1s, string.Empty, null,string.Empty);
             List <V_BumfCompanySendDoc> CompanyDocList = null;
             if (checkState != ((int)CheckStates.WaittingApproval).ToString())  //获取用户的公司文档信息
             {
                 //List<V_ArchivesLending> CompanyDocList = archivesLendingBll.GetArchivesLendingInfo(userID, searchObj, null, checkState);
                 if (checkState != ((int)CheckStates.ALL).ToString())
                 {
                     CompanyDocList = SendDocBll.GetSendDocInfosListByTypeCompanyDepartmentSearchForMVC(pageIndex, pageSize, sort, filterString, paras, ref pageCount, null, checkState, loginUserInfo.userID, ref recordsTotal);
                 }
                 else
                 {
                     CompanyDocList = SendDocBll.GetSendDocInfosListByTypeCompanyDepartmentSearchForMVC(pageIndex, pageSize, sort, filterString, paras, ref pageCount, null, "", loginUserInfo.userID, ref recordsTotal);
                 }
             }
             else                    //通过工作流获取公司文档信息
             {
                 ServiceClient             workFlowWS = new ServiceClient();
                 V_BumfCompanySendDoc      a          = new V_BumfCompanySendDoc();
                 FLOW_FLOWRECORDDETAIL_T   flowInfo   = new FLOW_FLOWRECORDDETAIL_T(); //审核人 操作
                 FLOW_FLOWRECORDDETAIL_T[] flowList   = workFlowWS.GetFlowInfo("", "", "", "0", "T_OA_SENDDOC", loginUserInfo.companyID, loginUserInfo.userID);
                 if (flowList == null)
                 {
                     return(null);
                 }
                 List <V_FlowAPP> flowAppList = new List <V_FlowAPP>();
                 for (int i = 0; i < flowList.Length; i++)
                 {
                     V_FlowAPP App = new V_FlowAPP();
                     App.Guid         = flowList[i].FLOWRECORDDETAILID;
                     App.FormID       = flowList[i].FLOW_FLOWRECORDMASTER_T.FORMID;
                     App.EditUserID   = flowList[i].EDITUSERID;
                     App.EditUserName = flowList[i].EDITUSERNAME;
                     flowAppList.Add(App);
                 }
                 checkState     = ((int)CheckStates.Approving).ToString();
                 CompanyDocList = SendDocBll.GetSendDocInfosListByTypeCompanyDepartmentSearchForMVC(pageIndex, pageSize, sort, filterString, paras, ref pageCount, flowAppList, checkState, loginUserInfo.userID, ref recordsTotal);
             }
             return(CompanyDocList != null ? CompanyDocList : null);
         }
     }
     catch (Exception ex)
     {
         Tracer.Debug("CompanySendDoc:" + System.DateTime.Now.ToString("d") + " " + ex.ToString());
         return(null);
     }
 }
Exemplo n.º 30
0
        private bool DoConnect()
        {
            lock (reconnectMutex)
            {
                if (ConnectedTransport != null || disposed || connectionFailure != null)
                {
                    return(false);
                }
                else
                {
                    List <Uri> connectList = ConnectList;
                    if (connectList.Count == 0)
                    {
                        Failure = new NMSConnectionException("No URIs available for connection.");
                    }
                    else
                    {
                        if (!UseExponentialBackOff)
                        {
                            ReconnectDelay = InitialReconnectDelay;
                        }

                        ITransport transport = null;
                        Uri        chosenUri = null;

                        try
                        {
                            foreach (Uri uri in connectList)
                            {
                                if (ConnectedTransport != null || disposed)
                                {
                                    break;
                                }

                                Tracer.DebugFormat("Attempting connect to: {0}", uri);

                                // synchronous connect
                                try
                                {
                                    Tracer.DebugFormat("Attempting connect to: {0}", uri.ToString());
                                    transport = TransportFactory.CompositeConnect(uri);
                                    chosenUri = transport.RemoteAddress;
                                    break;
                                }
                                catch (Exception e)
                                {
                                    Failure = e;
                                    Tracer.DebugFormat("Connect fail to: {0}, reason: {1}", uri, e.Message);
                                }
                            }

                            if (transport != null)
                            {
                                transport.Command   = new CommandHandler(OnCommand);
                                transport.Exception = new ExceptionHandler(OnException);
                                transport.Start();

                                if (started)
                                {
                                    RestoreTransport(transport);
                                }

                                if (this.Resumed != null)
                                {
                                    this.Resumed(transport);
                                }

                                Tracer.Debug("Connection established");
                                ReconnectDelay        = InitialReconnectDelay;
                                ConnectedTransportURI = chosenUri;
                                ConnectedTransport    = transport;
                                connectFailures       = 0;
                                connected             = true;

                                if (firstConnection)
                                {
                                    firstConnection = false;
                                    Tracer.InfoFormat("Successfully connected to: {0}", chosenUri.ToString());
                                }
                                else
                                {
                                    Tracer.InfoFormat("Successfully reconnected to: {0}", chosenUri.ToString());
                                }

                                return(false);
                            }
                        }
                        catch (Exception e)
                        {
                            Failure = e;
                            Tracer.DebugFormat("Connect attempt failed.  Reason: {0}", e.Message);
                        }
                    }

                    if (MaxReconnectAttempts > 0 && ++connectFailures >= MaxReconnectAttempts)
                    {
                        Tracer.ErrorFormat("Failed to connect to transport after {0} attempt(s)", connectFailures);
                        connectionFailure = Failure;
                        this.Exception(this, connectionFailure);
                        return(false);
                    }
                }
            }

            if (!disposed)
            {
                Tracer.DebugFormat("Waiting {0}ms before attempting connection.", ReconnectDelay);
                lock (sleepMutex)
                {
                    try
                    {
                        Thread.Sleep(ReconnectDelay);
                    }
                    catch (Exception)
                    {
                    }
                }

                if (UseExponentialBackOff)
                {
                    // Exponential increment of reconnect delay.
                    ReconnectDelay *= ReconnectDelayExponent;
                    if (ReconnectDelay > MaxReconnectDelay)
                    {
                        ReconnectDelay = MaxReconnectDelay;
                    }
                }
            }
            return(!disposed);
        }