Beispiel #1
0
        /// <inheritdoc />
        public async Task CommitTransactionAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction));

            try
            {
                _isCommitTransactionInProgress = true;
                if (_currentTransaction.IsEmpty)
                {
                    return;
                }

                try
                {
                    var firstAttempt = CreateCommitTransactionOperation(IsFirstCommitAttemptRetry());
                    await ExecuteEndTransactionOnPrimaryAsync(firstAttempt, cancellationToken).ConfigureAwait(false);

                    return;
                }
                catch (Exception exception) when(ShouldRetryEndTransactionException(exception))
                {
                    // unpin server if needed, then ignore exception and retry
                    TransactionHelper.UnpinServerIfNeededOnRetryableCommitException(_currentTransaction, exception);
                }

                var secondAttempt = CreateCommitTransactionOperation(isCommitRetry: true);
                await ExecuteEndTransactionOnPrimaryAsync(secondAttempt, cancellationToken).ConfigureAwait(false);
            }
            finally
            {
                _isCommitTransactionInProgress = false;
                _currentTransaction.SetState(CoreTransactionState.Committed);
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (args.Length > 0)
            {
                var firstArgs = args[0];

                if (firstArgs == "--calc-all-transaction")
                {
                    TransactionHelper.CalculateSubtotal(true);
                    return;
                }
                else if (firstArgs == "--calc-transaction")
                {
                    TransactionHelper.CalculateSubtotal();
                    TransactionHelper.ClosingTransaction();
                    return;
                }
                else if (firstArgs == "--calc-booking")
                {
                    TransactionHelper.CalculateBooking();
                    return;
                }
                else if (firstArgs == "--setup")
                {
                    InitApp("http://assets.app.local/index.html#/setup/db");
                    return;
                }
            }

            InitApp();
        }
Beispiel #3
0
        public static void InCline()
        {
            var sset = Input.Objects("Выберите объекты для преобразования"); if (Input.StatusBad)
            {
                return;
            }
            Point3d basePnt = Input.Point("Укажите базовую точку преобразования."); if (Input.StatusBad)
            {
                return;
            }
            //elevation divided by horisontal longtitude или по-русски уклон, тангенс угла наклона
            double tangent = Input.Double("Введите величину уклона. Положительный уклон повышается вправо (Х+ У+)"); if (Input.StatusBad)
            {
                return;
            }


            var matrix = Matrix3d.AlignCoordinateSystem(
                basePnt, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis,
                basePnt, Vector3d.XAxis + Vector3d.YAxis * tangent, Vector3d.YAxis, Vector3d.ZAxis);


            using (var th = new TransactionHelper())
            {
                sth = th;

                var objects = th.EditObjects(sset);
                TransformObjects(objects, matrix);

                sth = null;
            }
        }
Beispiel #4
0
        public object OpenReceipt(int id)
        {
            try
            {
                SystemDealLog dealLog = SystemDealLogService.GetById(id);
                if (dealLog != null && !dealLog.HasReceipt && dealLog.DealType == SystemDealLogTypes.Recharge && dealLog.Amount > 0 && dealLog.State == SystemDealLogStates.Normal)
                {
                    dealLog.HasReceipt = true;

                    TransactionHelper.BeginTransaction();

                    SystemDealLogService.Update(dealLog);
                    LogHelper.LogWithSerialNo(LogTypes.SystemDealLogOpenReceipt, SerialNoHelper.Create(), dealLog.SystemDealLogId, dealLog.SerialNo);
                    AddMessage(Localize("OpenReceipt.success"), dealLog.SystemDealLogId);

                    SendMessage(dealLog);
                    return(TransactionHelper.CommitAndReturn(new SimpleAjaxResult()));
                }
                return(new SimpleAjaxResult(Localize("OpenReceipt.failed", "原交易不存在")));
            }
            catch (Exception ex)
            {
                Logger.Error(LogTypes.SystemDealLogOpenReceipt, ex);
                return(new SimpleAjaxResult(ex.Message));
            }
        }
Beispiel #5
0
        public IMessageProvider Create()
        {
            var serialNo = SerialNoHelper.Create();

            TransactionHelper.BeginTransaction();
            string str = "S" + DateTime.Now.ToString("yyyyMMdd");

            InnerObject.OrderId   = str + "-" + OrderService.GetOrderSerialnumber();
            InnerObject.AccountId = AccountId;
            InnerObject.Phone     = Phone;
            var user = SecurityHelper.GetCurrentUser();

            InnerObject.Creater    = user.CurrentUser.DisplayName;
            InnerObject.CreaterId  = user.CurrentUser.UserId;
            InnerObject.createDate = DateTime.Now;
            base.OnSave(InnerObject);
            OrderService.CreateOrder(InnerObject);
            foreach (var item in this.Detials)
            {
                item.OrderId = InnerObject.OrderId;
                OrderService.AddOrderDetial(item);
            }
            AddMessage("success", InnerObject.OrderId);
            Logger.LogWithSerialNo(LogTypes.AddOrder, serialNo, 0);
            return(TransactionHelper.CommitAndReturn(this));
        }
Beispiel #6
0
        string ReadText(Entity text)
        {
            text.UpgradeOpen();
            if (text is MText)
            {
                MText mt = (MText)text;

                //TODO:тут можно вынуть существующий текст и обработать форматирование
                //и запихать уже подготовленную строку
                return(mt.Contents);
            }
            if (text is DBText)
            {
                DBText dt = (DBText)text;

                dt.TextString = content;
            }
            if (text is MLeader)
            {
                MLeader ml = (MLeader)text;
                return(ml.MText.Contents);
            }
            if (text is Leader)
            {
                Leader ld = (Leader)text;

                using (TransactionHelper th = new TransactionHelper())
                {
                    MText ann = th.EditObject(ld.Annotation) as MText;

                    return(ann.Contents);
                }
            }
            return("");
        }
        /// <summary>
        /// 路线地图选择终端
        /// </summary>
        /// <param name="routeid"></param>
        /// <param name="mappingEntity"></param>
        /// <param name="deletelist">删除的ID集合(不要含用户后来又选择的)</param>
        public void EditUserCDPPOPMap_Store(CallDayPlanningViewEntity_POP infoEntity, List <DefindControlEntity> pSearch, CallDayPlanningViewEntity_POP[] mappingEntity, string deletelist)
        {
            IDbTransaction tran = new TransactionHelper(this.CurrentUserInfo).CreateTransaction();

            using (tran.Connection)
            {
                try
                {
                    List <CallDayPlanningEntity> oldList = this._currentDAO.GetCallDayPlanning(infoEntity).ToList();

                    for (int i = 0; i < mappingEntity.Length; i++)
                    {
                        CallDayPlanningViewEntity_POP entity = mappingEntity[i];

                        if (entity.MappingID != null && !string.IsNullOrEmpty(entity.MappingID.ToString()))
                        {
                            //修改
                            CallDayPlanningEntity uEntity = oldList.Where(m => m.PlanningID == entity.MappingID).ToArray()[0];
                            uEntity.Sequence = (i + 1);
                            this._currentDAO.Update(uEntity, tran);
                        }
                        else
                        {
                            //新增
                            CallDayPlanningEntity uEntity = new CallDayPlanningEntity();

                            uEntity.CallDate     = infoEntity.CallDate;
                            uEntity.POPID        = entity.StoreID.ToString().ToLower();
                            uEntity.POPType      = 1;
                            uEntity.ClientUserID = infoEntity.ClientUserID;
                            uEntity.Sequence     = (i + 1);
                            uEntity.PlanningType = 2;

                            uEntity.ClientID            = Convert.ToInt32(CurrentUserInfo.ClientID);
                            uEntity.ClientDistributorID = Convert.ToInt32(CurrentUserInfo.ClientDistributorID);
                            this._currentDAO.Create(uEntity, tran);
                        }
                    }
                    //删除
                    if (deletelist != null && !string.IsNullOrEmpty(deletelist))
                    {
                        foreach (string mapid in deletelist.Split(','))
                        {
                            if (!string.IsNullOrEmpty(mapid))
                            {
                                this._currentDAO.Delete(Guid.Parse(mapid), tran);
                            }
                        }
                    }

                    tran.Commit();
                }
                catch
                {
                    tran.Rollback();
                    throw;
                }
            }
        }
Beispiel #8
0
        public ResultMessage UpdShoppingCartQuantity(int commodityId, int shoppingCartId, int quantity)
        {
            try
            {
                //TransactionHelper.BeginTransaction();
                var ShoppingCart = ShoppingCartService.GetById(shoppingCartId);
                if (ShoppingCart != null)
                {
                    var commodity = JuMeiMallService.GetById(commodityId);
                    if (commodity != null)//检测商品信息
                    {
                        if (commodity.commodityState == CommodityStates.soldOut)
                        {
                            return new ResultMessage()
                                   {
                                       Code = -1, Msg = "商品已下架,请重新生成订单!"
                                   }
                        }
                        ;
                    }
                    else
                    {
                        return(new ResultMessage()
                        {
                            Code = -1, Msg = "商品不存在,请重新生成购物车!"
                        });
                    }



                    if (commodity.commodityInventory < quantity)
                    {
                        ShoppingCart.quantity = commodity.commodityInventory;
                        ShoppingCartService.Update(ShoppingCart);
                        TransactionHelper.Commit();
                        return(new ResultMessage()
                        {
                            Code = -1, Msg = string.Format("{0}库存不足,此商品库存剩余{1}件", commodity.commodityName, commodity.commodityInventory), quantity = commodity.commodityInventory
                        });
                    }

                    ShoppingCart.quantity = quantity;
                    ShoppingCartService.Update(ShoppingCart);
                }
                // TransactionHelper.Commit();
                return(new ResultMessage()
                {
                    Code = 0, Msg = "购物车修改数量成功"
                });
            }
            catch (Exception ex)
            {
                logService.Insert(ex);
                return(new ResultMessage()
                {
                    Code = -1, Msg = "购物车数量修改-网络错误,请稍后重试..."
                });
            }
        }
Beispiel #9
0
        public ResultMessage Refund(string orderNo)
        {
            Load();
            if (UserInformation == null)
            {
                return new ResultMessage()
                       {
                           Code = -1, Msg = "请重新登录"
                       }
            }
            ;
            TransactionHelper.BeginTransaction();
            var order = OrderService.GetOrderNo(orderNo);

            if (order == null)
            {
                return new ResultMessage()
                       {
                           Code = -1, Msg = "订单不存在"
                       }
            }
            ;
            if (order.orderState != OrderStates.complete && order.orderState != OrderStates.paid)
            {
                return new ResultMessage()
                       {
                           Code = -1, Msg = "订单状态不正确"
                       }
            }
            ;
            order.orderState = OrderStates.applyRefund;
            //if (Account != null)
            //{
            //    if (Account.salerId > 0)
            //    {
            //        var salerAccount = AccountService.GetByUserId(Account.salerId);
            //        if (salerAccount != null)
            //        {
            //            var amount = order.payAmount * RebateRatio;
            //            salerAccount.activatePoint += amount;
            //            OperationPointLog log = new OperationPointLog();
            //            log.account = "activatePoint";
            //            log.point = amount;
            //            log.remark = string.Format("{0}消费", UserInformation.Name);
            //            log.submitTime = DateTime.Now;
            //            log.userId = UserInformation.UserId;
            //            OperationPointLogService.Insert(log);
            //        }
            //    }
            //}
            OrderService.Update(order);
            TransactionHelper.Commit();
            return(new ResultMessage()
            {
                Code = 0
            });
        }
    }
}
        /// <summary>
        /// 导入路线及详细信息
        /// </summary>
        /// <param name="pRouteImportEntityList"></param>
        /// <param name="pDataRow"></param>
        /// <param name="pUser"></param>
        /// <param name="oResult"></param>
        /// <param name="pTran"></param>
        /// <param name="pProjectID"></param>
        /// <returns></returns>
        public bool Process(List <VipEntity> pRouteImportEntityList, IETCLDataItem[] pDataRow, LoggingSessionInfo pUser, out IETCLResultItem[] oResult, IDbTransaction pTran, string pProjectID)
        {
            if (pTran == null)
            {
                pTran = new TransactionHelper(pUser).CreateTransaction();
            }
            bool isPass = true;

            //V routeDao = new RouteDAO(pUser);
            List <TenantPlatformETCLResultItem> lstErrorCell = new List <TenantPlatformETCLResultItem>();
            StringBuilder sql = new StringBuilder();

            //foreach (var item in pRouteImportEntityList)
            //{
            //    sql.AppendLine(" insert into Route(RouteID,RouteName,Status,StartDate,POPType,TripMode,Remark,ClientID,ClientDistributorID,CreateBy,CreateTime)");
            //    sql.AppendFormat(@"values('{0}','{1}',{2},'{3}',{4},{5},'{6}',{7},{8},{9},'{10}')", item.RouteID, item.RouteName, item.Status, item.StartDate, item.POPType
            //        , (item.TripMode == null ? "NULL" : item.TripMode.ToString()), item.Remark, item.ClientID, item.ClientDistributorID, item.CreateBy, item.CreateTime);
            //    sql.AppendLine("");
            //    sql.AppendLine(" insert into RouteCycleMapping(MappingID,RouteID,CycleDetailID,ClientID,ClientDistributorID,CreateBy,CreateTime)");
            //    sql.AppendFormat(@"values('{0}','{1}','{2}',{3},{4},{5},'{6}')", item.RouteCycleMappingEntity.MappingID, item.RouteCycleMappingEntity.RouteID, item.RouteCycleMappingEntity.CycleDetailID
            //                                , item.ClientID, item.ClientDistributorID, item.RouteCycleMappingEntity.CreateBy, item.RouteCycleMappingEntity.CreateTime);
            //    sql.AppendLine("");
            //    sql.AppendLine("insert into RouteUserMapping(MappingID,RouteID,ClientUserID,ClientID,ClientDistributorID,CreateBy,CreateTime)");
            //    sql.AppendFormat(@"values('{0}','{1}','{2}',{3},{4},{5},'{6}')", item.RouteUserMappingEntity.MappingID, item.RouteUserMappingEntity.RouteID, item.RouteUserMappingEntity.ClientUserID
            //                                , item.ClientID, item.ClientDistributorID, item.RouteUserMappingEntity.CreateBy, item.RouteUserMappingEntity.CreateTime);

            //    foreach (var routePopItem in item.RoutePopMappingEntity)
            //    {
            //        sql.AppendLine("");
            //        sql.AppendLine("insert into RoutePOPMapping(MappingID,RouteID,POPID,Sequence,ClientID,ClientDistributorID,CreateBy,CreateTime)");
            //        sql.AppendFormat(@"values('{0}','{1}','{2}',{3},{4},{5},{6},'{7}')", routePopItem.MappingID, routePopItem.RouteID, routePopItem.POPID, routePopItem.Sequence
            //                                    , routePopItem.ClientID, routePopItem.ClientDistributorID, routePopItem.CreateBy, routePopItem.CreateTime);
            //    }
            //}
            //UtilityEntity uEntity = new UtilityEntity();
            //uEntity.CustomSql = sql.ToString();
            //using (pTran.Connection)
            //{
            //    try
            //    {
            //        new UtilityDAO(pUser).Query(uEntity, pTran);
            //        foreach (var item in pRouteImportEntityList)
            //        {
            //            routeDao.GenerateCallDayPlanning((Guid)item.RouteID, pUser.UserID, pTran);
            //        }
            //        pTran.Commit();
            //    }
            //    catch (Exception)
            //    {
            //        pTran.Rollback();
            //        isPass = false;
            //        TenantPlatformETCLResultItem errorItem = new TenantPlatformETCLResultItem();
            //        errorItem.Message = "路线导入时调用存储过程spCallDayPlanning出现异常";
            //        lstErrorCell.Add(errorItem);
            //    }
            //}
            oResult = lstErrorCell.ToArray();
            return(isPass);
        }
Beispiel #11
0
        /// <summary>
        /// запускаем функцию
        /// </summary>
        public override void Execute()
        {
            using (var lm = new PKLayerManager())
            {
                lm.CommandLayer = "ПК_С_ЛинииРазрыва";

                base.Execute();
                var sset = Input.Objects(

                    keywords:  new string[] { "OFfset", "СМещение", },
                    message:  "Выберите 2 отрезка на углу или полилинии проемов.",
                    keywordinput: new SelectionTextInputEventHandler(LengthInput)
                    );
                if (Input.StatusBad)
                {
                    return;
                }
                List <Entity> input = new List <Entity>();

                using (TransactionHelper th = new TransactionHelper())
                {
                    input = th.ReadObjects(sset);
                }
                if (input == null || input.Count < 1)
                {
                    Tweet("Не удалось прочитать объекты");
                    return;
                }

                SortLinesAndPolylines(input);
                using (TransactionHelper th = new TransactionHelper())
                {
                    for (int i = 0; i < lines.Count - 1; i += 2)
                    {
                        Make(lines[i], lines[i + 1]);
                        if (!status_ok)
                        {
                            continue;
                        }

                        Tweet("Записываем линии в базу данных");
                        th.WriteObject(first);
                        th.WriteObject(second);
                    }
                    foreach (Polyline pl in polylines)
                    {
                        Make(pl);
                        if (!status_ok)
                        {
                            continue;
                        }

                        Tweet("Записываем линии в базу данных");
                        th.WriteObject(first);
                        th.WriteObject(second);
                    }
                }
            }
        }
        /// <summary>
        /// 路线地图选择终端
        /// </summary>
        /// <param name="routeid"></param>
        /// <param name="mappingEntity"></param>
        /// <param name="deletelist">删除的ID集合(不要含用户后来又选择的)</param>
        public void EditRoutePOPMap_Distributor(Guid routeid, RoutePOPMappingViewEntity[] mappingEntity, string deletelist)
        {
            IDbTransaction tran = new TransactionHelper(this.CurrentUserInfo).CreateTransaction();

            using (tran.Connection)
            {
                try
                {
                    for (int i = 0; i < mappingEntity.Length; i++)
                    {
                        RoutePOPMappingViewEntity entity = mappingEntity[i];

                        if (entity.MappingID != null && !string.IsNullOrEmpty(entity.MappingID.ToString()))
                        {
                            //修改
                            RoutePOPMappingEntity uEntity = new RoutePOPMappingEntity();
                            uEntity.MappingID           = entity.MappingID;
                            uEntity.RouteID             = routeid;
                            uEntity.POPID               = entity.DistributorID.ToString();
                            uEntity.Sequence            = (i + 1);
                            uEntity.ClientID            = Convert.ToInt32(CurrentUserInfo.ClientID);
                            uEntity.ClientDistributorID = Convert.ToInt32(CurrentUserInfo.ClientDistributorID);
                            this._currentDAO.Update(uEntity, tran);
                        }
                        else
                        {
                            //新增
                            RoutePOPMappingEntity uEntity = new RoutePOPMappingEntity();
                            uEntity.RouteID             = routeid;
                            uEntity.POPID               = entity.DistributorID.ToString();
                            uEntity.Sequence            = (i + 1);
                            uEntity.ClientID            = Convert.ToInt32(CurrentUserInfo.ClientID);
                            uEntity.ClientDistributorID = Convert.ToInt32(CurrentUserInfo.ClientDistributorID);
                            this._currentDAO.Create(uEntity, tran);
                        }
                    }
                    //删除
                    if (deletelist != null && !string.IsNullOrEmpty(deletelist))
                    {
                        foreach (string mapid in deletelist.Split(','))
                        {
                            if (!string.IsNullOrEmpty(mapid))
                            {
                                this._currentDAO.Delete(Guid.Parse(mapid), tran);
                            }
                        }
                    }

                    tran.Commit();
                }
                catch
                {
                    tran.Rollback();
                    throw;
                }
            }

            new RouteBLL(CurrentUserInfo).GenerateCallDayPlanning(routeid);
        }
Beispiel #13
0
 //这个方法的契约待定
 public Result ValidateRegisterInfoAndAccomplish(UserInfoDTO userInfoDTO)
 {
     return(TransactionHelper.Transaction <Result>(() =>
     {
         //先校验注册校验信息
         return Result.Error();
     }));
 }
Beispiel #14
0
 public JsonProtoObjectConverterTests()
 {
     _jsonProtoObjectConverter = new JsonProtoObjectConverter <TransactionBroadcast>();
     _transaction     = TransactionHelper.GetContractTransaction(ByteString.CopyFromUtf8("test"), 10, 10, 10);
     _transactionJson = "{ \"publicEntry\": { \"receiverAddress\": \"AAAAAAAAAAAAAAAAAAAAAAAAAAA=\", \"senderAddress\": \"AAAAAAAAAAAAAAAAAAAAAAAAAAA=\", \"amount\": \"Cg==\", \"data\": \"dGVzdA==\", \"gasPrice\": \"Cg==\", \"gasLimit\": \"10\", \"signature\": { \"signingContext\": { \"networkType\": \"DEVNET\", \"signatureType\": \"TRANSACTION_PUBLIC\" }, \"rawBytes\": \"c2lnbmF0dXJl\" } } }";
     _transactionJson = "{ \"publicEntry\": { \"receiverAddress\": \"AAAAAAAAAAAAAAAAAAAAAAAAAAA=\", \"senderAddress\": \"AAAAAAAAAAAAAAAAAAAAAAAAAAA=\", \"amount\": \"Cg==\", \"data\": \"dGVzdA==\", \"gasPrice\": \"Cg==\", \"gasLimit\": \"10\", \"signature\": { \"signingContext\": { \"networkType\": \"DEVNET\", \"signatureType\": \"TRANSACTION_PUBLIC\" }, \"rawBytes\": \"c2lnbmF0dXJl\" } } }";
     _transactionJson = "{ \"publicEntry\": { \"receiverAddress\": \"AAAAAAAAAAAAAAAAAAAAAAAAAAA=\", \"senderAddress\": \"AAAAAAAAAAAAAAAAAAAAAAAAAAA=\", \"amount\": \"Cg==\", \"data\": \"dGVzdA==\", \"gasPrice\": \"Cg==\", \"gasLimit\": \"10\", \"signature\": { \"signingContext\": { \"networkType\": \"DEVNET\", \"signatureType\": \"TRANSACTION_PUBLIC\" }, \"rawBytes\": \"c2lnbmF0dXJl\" } } }";
 }
        /// <summary>
        /// Action method to display a button that when clicked will generate the mess bill
        /// </summary>
        /// <returns>view</returns>
        public ActionResult GenerateMessBill()
        {
            TransactionHelper helper = new TransactionHelper();

            ViewBag.canGenerateMessBill = helper.CanGenerateMessBill();

            return(View());
        }
Beispiel #16
0
 public BankAccountController()
 {
     DbContext         = new ApplicationDbContext();
     HouseholdHelper   = new HouseholdHelper(DbContext);
     BankAccountHelper = new BankAccountHelper(DbContext);
     TransactionHelper = new TransactionHelper(DbContext);
     BankAccountHelper = new BankAccountHelper(DbContext);
 }
Beispiel #17
0
        // GET: Transaction/Details/5
        public ActionResult SubscriptionDetails()
        {
            Authorize();
            string userId = HttpContext.Session.GetObject("coviduserid");
            IList <TransactionViewModel> transList = new TransactionHelper().GetAllByUserId(Convert.ToInt32(userId));

            return(View("~/Views/Transaction/Subscription.cshtml", transList));
        }
        public static void Info(this Log log, string description, string summary, params object[] values)
        {
            int? userId        = UserHelper.TryGetId();
            Guid transactionId = TransactionHelper.GetId();

            summary = summary.Format(values);
            log.WriteAsync <EventLogger>(logger => logger.WriteAsync(summary, description, EventType.Info, userId, transactionId));
        }
        static async Task DoClientWork()
        {
            // basic configuration
            var clientconfig = new Orleans.Runtime.Configuration.ClientConfiguration();

            clientconfig.Gateways.Add(new IPEndPoint(IPAddress.Loopback, 30000));

            GrainClient.Initialize(clientconfig);

            var idE1 = "5ad92744-a0b1-487b-a9e7-e6b91e9a9826";
            var idE2 = "2eef0ac5-540f-4421-b9a9-79d89400f7ab";
            var e1   = GrainClient.GrainFactory.GetGrain <IEmployee>(Guid.Parse(idE1));
            var e2   = GrainClient.GrainFactory.GetGrain <IEmployee>(Guid.Parse(idE2));

            Console.WriteLine("Current State:");
            await e1.Print();

            await e2.Print();

            if (!await e1.SpendCurrency(10))
            {
                Console.WriteLine("Employee {0} does not have 10 currency to spend", idE1);
            }

            if (!await e2.SpendCurrency(10))
            {
                Console.WriteLine("Employee {0} does not have 10 currency to spend", idE2);
            }

            await e1.AddCurrency(20);

            await e2.AddGoods(10);

            await e1.Print();

            await e2.Print();

            var transaction = new TransactionHelper <EmployeeStateTransfer>();

            transaction.Add(e1, new EmployeeStateTransfer()
            {
                Currency = -5, Goods = 5
            });
            transaction.Add(e2, new EmployeeStateTransfer()
            {
                Currency = 5, Goods = -5
            });
            Console.WriteLine("Executing transaction to trade 5 currency for 5 goods... ");
            await transaction.Execute();

            Console.WriteLine("Transaction complete.");

            await e1.Print();

            await e2.Print();

            Console.WriteLine("Done!");
        }
Beispiel #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="trHlpr"></param>
        public Objects(TransactionHelper trHlpr)
        {
            InitializeComponent();

            m_db     = MgdDbg.Utils.Db.GetCurDwg();
            m_trHlpr = trHlpr;

            InitializeTreeView();
        }
        public ActionResult Add(MyClinic.Infrastructure.EmployeeAdd objFrm)
        {
            bool checkError = true;

            try
            {
                if (ModelState.IsValid)
                {
                    Employee employee = new Employee();
                    Dictionary <string, string> dictItem = TransactionHelper.processGenerateArray(employee);
                    employee = TransactionHelper.TransDict <Employee>(dictItem, employee);
                    var objSession = Session["user"] as MyClinic.Infrastructure.SessUser;
                    employee.Image  = employee.Id + "jpg";
                    employee.Status = 1;

                    employeeRepository.Add(employee);

                    var fileName = employee.Id + ".jpg";
                    var savePath = Server.MapPath("~/Uploads/employee/") + employee.Id;
                    ImageHelper.SaveImage(savePath, employee.Id + ".jpg", objFrm.ImageStream);
                    Employee newEmployee = Utilities.ObjectCopier.Copy <Employee>(employee);
                    newEmployee.Image = employee.Id + ".jpg";
                    employeeRepository.UpdateFieldChangedOnly(employee, newEmployee);

                    /*For Add New Record to LogTable*/
                    int userId = objSession.UserId;
                    logTran.UserId      = userId;
                    logTran.ProcessType = "Add Employee";
                    logTran.Description = "Add Employee Name : " + employee.Name;
                    logTran.LogDate     = DateTime.Now;
                    logRepository.Add(logTran);
                    checkError = false;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                ModelState.AddModelError(string.Empty, Translator.UnexpectedError);
            }

            if (checkError == true)
            {
                var objPosition = employeeRepository.GetPosition();
                //objFrm.Dob = objFrm.DateOfBirth;
                employeeModel = new EmployeeModels
                {
                    employeeAdd = objFrm,
                    checkPost   = true,
                    positions   = objPosition
                };
                return(View(employeeModel));
            }
            else
            {
                return(RedirectToAction("Index", "Employee"));
            }
        }
Beispiel #22
0
 public RollbackType Rollback(int id)
 {
     try
     {
         using (var tran = TransactionHelper.BeginTransaction())
         {
             var serialNo    = SerialNoHelper.Create();
             var shopDealLog = this.ShopDealLogService.GetById(id);
             if (shopDealLog == null)
             {
                 throw new Exception(Localize("nofoundDeal"));
             }
             var dealLog = this.DealLogService.GetById(shopDealLog.Addin);
             if (dealLog == null)
             {
                 throw new Exception(Localize("nofoundDeal"));
             }
             var account = AccountService.GetById(dealLog.AccountId);
             if (account == null)
             {
                 throw new Exception(Localize("nofoundAccount"));
             }
             AccountServiceResponse rsp = null;
             RollbackType           r   = RollbackType.None;
             if (dealLog.SubmitTime.Date != DateTime.Now.Date)
             {
                 rsp = AccountDealService.CancelPay(new CancelPayRequest(dealLog.AccountName, "", dealLog.SourcePosName, Math.Abs(dealLog.Amount), serialNo, dealLog.SerialNo, account.AccountToken,
                                                                         dealLog.SourceShopName)
                 {
                     IsForce = true
                 });
                 r = RollbackType.Cancel;
             }
             else
             {
                 rsp = AccountDealService.Roolback(new PayRequest_(dealLog.AccountName, "", dealLog.SourcePosName, Math.Abs(dealLog.Amount), serialNo, dealLog.SerialNo, account.AccountToken,
                                                                   dealLog.SourceShopName)
                 {
                     IsForce = true
                 });
                 r = RollbackType.Undo;
             }
             if (rsp.Code != ResponseCode.Success)
             {
                 throw new Exception(string.Format("{0}", ModelHelper.GetBoundText(rsp, x => x.Code)));
             }
             LogHelper.LogWithSerialNo(LogTypes.DealLogRollback, serialNo, dealLog.DealLogId, dealLog.SerialServerNo, dealLog.SerialNo);
             tran.Commit();
             return(r);
         }
     }
     catch (Exception ex)
     {
         Logger.Error(LogTypes.DealLogRollback, ex);
         return(RollbackType.None);
     }
 }
        /// <summary>
        /// 撤销轧钢计划(中间表撤回)
        /// </summary>
        /// <param name="strID">trp_plan_roll_item_info表主键</param>
        public string BackPlan(string strID)
        {
            try
            {
                string result = "1";

                TransactionHelper.BeginTransaction();

                Mod_TRP_PLAN_ROLL_ITEM_INFO modItemInfo = dal.GetModel(strID);
                if (modItemInfo != null)
                {
                    if (modItemInfo.N_STATUS != 1)
                    {
                        TransactionHelper.RollBack();
                        return("撤销失败!");
                    }

                    if (!dal.Delete_Trans(strID))
                    {
                        TransactionHelper.RollBack();
                        return("撤销失败!");
                    }

                    Mod_TRP_PLAN_ROLL modPlan = dalTrpPlanRoll.GetModel(modItemInfo.C_PLAN_ROLL_ID);
                    if (modPlan == null)
                    {
                        TransactionHelper.RollBack();
                        return("撤销失败!");
                    }
                    else
                    {
                        modPlan.N_STATUS    = 0;
                        modPlan.N_ISSUE_WGT = modPlan.N_ISSUE_WGT - Convert.ToDecimal(modItemInfo.N_ISSUE_WGT);

                        if (!dalTrpPlanRoll.Update_Trans(modPlan))
                        {
                            TransactionHelper.RollBack();
                            return("撤销失败!");
                        }
                    }
                }
                else
                {
                    TransactionHelper.RollBack();
                    return("撤销失败!");
                }

                TransactionHelper.Commit();

                return(result);
            }
            catch
            {
                TransactionHelper.RollBack();
                return("撤销失败!");
            }
        }
Beispiel #24
0
        public void GetPrettyFullName()
        {
            Type   type   = typeof(TransactionHelperPretty <TransactionHelperTest>);
            string result = TransactionHelper.GetPrettyFullName(type);

            Assert.AreEqual(result, "Shamana.Tracing.Core.Tests.TransactionHelperTest.TransactionHelperPretty<Shamana.Tracing.Core.Tests.TransactionHelperTest>");
            result = TransactionHelper.GetPrettyFullName(null);
            Assert.AreEqual(result, string.Empty);
        }
        /// <summary>
        /// 拜访计划终端选择
        /// </summary>
        /// <param name="infoEntity">clientuserid,calldate 必传</param>
        /// <param name="pSearch"></param>
        /// <param name="mappingEntity"></param>
        public void EditUserCDPPOPList_Store(
            CallDayPlanningViewEntity_POP infoEntity,
            List <DefindControlEntity> pSearch,
            CallDayPlanningViewEntity_POP[] mappingEntity)
        {
            IDbTransaction tran = new TransactionHelper(this.CurrentUserInfo).CreateTransaction();

            using (tran.Connection)
            {
                try
                {
                    List <CallDayPlanningEntity> oldList = this._currentDAO.GetCallDayPlanning(infoEntity).ToList();

                    foreach (CallDayPlanningViewEntity_POP entity in mappingEntity)
                    {
                        if (entity.MappingID != null && !string.IsNullOrEmpty(entity.MappingID.ToString()))
                        {
                            if (entity.IsDelete == 1)
                            {
                                //删除
                                this._currentDAO.Delete(entity.MappingID, tran);
                            }
                            else
                            {
                                //修改
                                CallDayPlanningEntity uEntity = oldList.Where(m => m.PlanningID == entity.MappingID).ToArray()[0];
                                uEntity.Sequence = entity.Sequence;
                                this._currentDAO.Update(uEntity, tran);
                            }
                        }
                        else
                        {
                            //新增
                            CallDayPlanningEntity uEntity = new CallDayPlanningEntity();

                            uEntity.CallDate     = infoEntity.CallDate;
                            uEntity.POPID        = entity.StoreID.ToString().ToLower();
                            uEntity.POPType      = 1;
                            uEntity.ClientUserID = infoEntity.ClientUserID;
                            uEntity.Sequence     = entity.Sequence;
                            uEntity.PlanningType = 2;

                            uEntity.ClientID            = Convert.ToInt32(CurrentUserInfo.ClientID);
                            uEntity.ClientDistributorID = Convert.ToInt32(CurrentUserInfo.ClientDistributorID);
                            this._currentDAO.Create(uEntity, tran);
                        }
                    }

                    tran.Commit();
                }
                catch
                {
                    tran.Rollback();
                    throw;
                }
            }
        }
Beispiel #26
0
        public RebarDrawing()
        {
            Tweet("Начинаем распознавать слои");

            if (!InitLayers())
            {
                Tweet("Не хватает слоев! Программа не будет продолжена. Для корректной работы необходим полный шаблон ПК");
                return;
            }
            if (!InitLinetype())
            {
                return;
            }

            Tweet("Пробуем нарисовать плиту");
            using (var th = new TransactionHelper())
            {
                var sset_line1 = Input.Objects("Выберите линию сечения нижней арматуры", new string[]
                                               { "SEttings", "ПАраметры", "LAyers", "cЛОи" },
                                               SetParams
                                               ); if (Input.StatusBad)
                {
                    return;
                }
                var sset_lines1 = Input.Objects("Выберите нижние арматурные стержни"); if (Input.StatusBad)
                {
                    return;
                }
                var sset_line2 = Input.Objects("Выберите линию сечения верхней арматуры"); if (Input.StatusBad)
                {
                    return;
                }
                var sset_lines2 = Input.Objects("Выберите верхние арматурные стержни"); if (Input.StatusBad)
                {
                    return;
                }

                var ln1    = th.ReadObject(sset_line1[0].ObjectId) as Line;
                var ln2    = th.ReadObject(sset_line2[0].ObjectId) as Line;
                var lines1 = th.ReadObjects(sset_lines1);
                var lines2 = th.ReadObjects(sset_lines2);

                var colors1 = lines1.Select((ln) => ln.Color).ToList();
                var colors2 = lines2.Select((ln) => ln.Color).ToList();

                dot_data1 = lines1.Select((ln) => {
                    return(new Tuple <double, Color>(UT.IntersectWith(ln, ln1)[0].X, ln.Color));
                }
                                          ).ToList();
                dot_data2 = lines2.Select((ln) => {
                    return(new Tuple <double, Color>(UT.IntersectWith(ln, ln2)[0].X, ln.Color));
                }
                                          ).ToList();

                th.WriteObjects(Slab(thickness, ln1.StartPoint.X, ln1.EndPoint.X, offset_up, offset_down, dots_up, dots_down));
            }
        }
Beispiel #27
0
        /// <summary>
        /// 设置自审信息
        /// </summary>
        /// <param name="cityId">城市</param>
        /// <param name="companyId">企业</param>
        /// <param name="allotId">任务ID</param>
        /// <param name="datType">任务数据类型</param>
        /// <param name="userName">自审人</param>
        /// <param name="pass">是否通过</param>
        /// <param name="remark">自审说明</param>
        /// <param name="message"></param>
        /// <param name="_db"></param>
        /// <param name="tx"></param>
        /// <returns></returns>
        public static int SetMyCheckInfo(int cityId, int companyId, long allotId, long datId, int datType, string userName, bool pass, string remark, out string message, DataBase _db = null, ITransaction tx = null)
        {
            message = "";
            DataBase          db = new DataBase(_db);
            TransactionHelper tr = new TransactionHelper(db.DB, tx);

            try
            {
                bool     add = false;
                DatCheck obj = GetCheckByAllotId(allotId, db);
                //是否存在数据
                if (obj == null)
                {
                    add              = true;
                    obj              = new DatCheck();
                    obj.CityId       = cityId;
                    obj.FxtCompanyId = companyId;
                    obj.AllotId      = allotId;
                    obj.DatType      = datType;
                    obj.DatId        = datId;
                }
                obj.CheckUserName1 = userName;
                obj.CheckState1    = SYSCodeManager.STATECODE_7;
                if (pass)
                {
                    obj.CheckState1 = SYSCodeManager.STATECODE_6;
                }
                obj.CheckRemark1 = remark;
                obj.CheckDate1   = DateTime.Now;
                bool upResult = false;
                if (add)
                {
                    upResult = db.DB.Create(obj, tx);
                }
                else
                {
                    upResult = db.DB.Update(obj, tx);
                }
                if (!upResult)
                {
                    tr.Rollback();
                    db.Close();
                    return(0);
                }
                tr.Commit();
                db.Close();
            }
            catch (Exception ex)
            {
                tr.Rollback();
                db.Close();
                message = "系统异常";
                log.Error("SetMyCheckInfo:系统异常", ex);
                return(-1);
            }
            return(1);
        }
Beispiel #28
0
 public MempoolTests()
 {
     _hashProvider   = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("blake2b-256"));
     _memPool        = new Mempool(Substitute.For <IMempoolService <PublicEntryDao> >());
     _mapperProvider = new TestMapperProvider();
     _mempoolItem    = TransactionHelper
                       .GetPublicTransaction().PublicEntry
                       .ToDao <PublicEntry, PublicEntryDao>(_mapperProvider);
 }
        public static void LoginActivity(this Log log, string status, HttpRequestMessage request)
        {
            int? userId        = UserHelper.TryGetId();
            Guid transactionId = TransactionHelper.GetId();
            var  summary       = status;
            var  description   = request.Headers.UserAgent.ToString();

            log.WriteAsync <EventLogger>(logger => logger.WriteAsync(summary, description, EventType.LoginActivity, userId, transactionId));
        }
        public static void UserActivity(this Log log, HttpResponseMessage response)
        {
            int? userId        = UserHelper.TryGetId();
            Guid transactionId = TransactionHelper.GetId();
            var  summary       = String.Format("{0} {1} {2}", response.RequestMessage.RequestUri.AbsolutePath, (int)response.StatusCode, response.ReasonPhrase);
            var  description   = response.Content != null?String.Format("{1}{0}{2}", Environment.NewLine, response.Content.Headers, response.Content.ReadAsStringAsync().Result) : String.Empty;

            log.WriteAsync <EventLogger>(logger => logger.WriteAsync(summary, description, EventType.UserActivity, userId, transactionId));
        }
        public async Task LessThanTwoTransactionItemsTest()
        {
            var e1 = GrainFactory.GetGrain<IEmployee>(Guid.NewGuid());
            await e1.AddCurrency(5);

            var transaction = new TransactionHelper<EmployeeStateTransfer>();
            transaction.Add(e1, new EmployeeStateTransfer() { Currency = -5, Goods = 5 });

            // Executing transaction with only one item, two or more are required.
            Assert.IsFalse(await transaction.Execute());
            Assert.AreEqual(5, await e1.GetCurrency());
            Assert.AreEqual(0, await e1.GetGoods());
        }
        public async Task InsufficientGoodsTest()
        {
            var e1 = GrainFactory.GetGrain<IEmployee>(Guid.NewGuid());
            var e2 = GrainFactory.GetGrain<IEmployee>(Guid.NewGuid());
            await e1.AddCurrency(5);
            await e2.AddGoods(1);

            var transaction = new TransactionHelper<EmployeeStateTransfer>();
            transaction.Add(e1, new EmployeeStateTransfer() { Currency = -5, Goods = 5 });
            transaction.Add(e2, new EmployeeStateTransfer() { Currency = 5, Goods = -5 });

            // Executing transaction to trade 5 currency for 5 goods, but 5 Goods is not available...
            Assert.IsFalse(await transaction.Execute());
            Assert.AreEqual(5, await e1.GetCurrency());
            Assert.AreEqual(1, await e2.GetGoods());
        }
        static async Task DoClientWork()
        {
            // basic configuration
            var clientconfig = new Orleans.Runtime.Configuration.ClientConfiguration();
            clientconfig.Gateways.Add(new IPEndPoint(IPAddress.Loopback, 30000));

            GrainClient.Initialize(clientconfig);

            var idE1 = "5ad92744-a0b1-487b-a9e7-e6b91e9a9826";
            var idE2 = "2eef0ac5-540f-4421-b9a9-79d89400f7ab";
            var e1 = GrainClient.GrainFactory.GetGrain<IEmployee>(Guid.Parse(idE1));
            var e2 = GrainClient.GrainFactory.GetGrain<IEmployee>(Guid.Parse(idE2));

            Console.WriteLine("Current State:");
            await e1.Print();
            await e2.Print();

            if (!await e1.SpendCurrency(10))
            {
                Console.WriteLine("Employee {0} does not have 10 currency to spend", idE1);
            }

            if (!await e2.SpendCurrency(10))
            {
                Console.WriteLine("Employee {0} does not have 10 currency to spend", idE2);
            }

            await e1.AddCurrency(20);
            await e2.AddGoods(10);

            await e1.Print();
            await e2.Print();

            var transaction = new TransactionHelper<EmployeeStateTransfer>();
            transaction.Add(e1, new EmployeeStateTransfer() { Currency = -5, Goods = 5 });
            transaction.Add(e2, new EmployeeStateTransfer() { Currency = 5, Goods = -5 });
            Console.WriteLine("Executing transaction to trade 5 currency for 5 goods... ");
            await transaction.Execute();
            Console.WriteLine("Transaction complete.");

            await e1.Print();
            await e2.Print();

            Console.WriteLine("Done!");
        }
        public async Task TradeGoodsForCurrencyTest()
        {
            var e1 = GrainFactory.GetGrain<IEmployee>(Guid.NewGuid());
            var e2 = GrainFactory.GetGrain<IEmployee>(Guid.NewGuid());
            await e1.AddCurrency(5);
            await e2.AddGoods(5);

            var transaction = new TransactionHelper<EmployeeStateTransfer>();
            transaction.Add(e1, new EmployeeStateTransfer() { Currency = -5, Goods = 5 });
            transaction.Add(e2, new EmployeeStateTransfer() { Currency = 5, Goods = -5 });
            
            // Executing transaction to trade 5 currency for 5 goods
            Assert.IsTrue(await transaction.Execute());
            Assert.AreEqual(5, await e1.GetGoods());
            Assert.AreEqual(0, await e1.GetCurrency());
            Assert.AreEqual(5, await e2.GetCurrency());
            Assert.AreEqual(0, await e2.GetGoods());
        }
 public DefaultMessageManager()
 {
     this._mValidator = new TransactionHelper(this);
 }