Ejemplo n.º 1
0
        //================================================================
        //データ削除処理  
        //================================================================
        public bool remove(int id, ref string resErrMsg)
        {
            DateTime regDate = DateTime.Now;
            bool     result  = false;

            try
            {
                using (umekoudbDataContext dc = new umekoudbDataContext())
                {
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                    {
                        var deleteItems = (from o in dc.GetTable <card_t>() where o.id == id select o);
                        if (deleteItems.Count() == 0)
                        {
                            resErrMsg = "削除しようとしたデータはすでに存在しませんでした";
                            return(false);
                        }
                        card_t deleteItem = deleteItems.Single();

                        //データ削除
                        dc.GetTable <card_t>().DeleteOnSubmit(deleteItem);
                        dc.SubmitChanges();
                        ts.Complete();
                    }
                }

                result = true;
            }
            catch (Exception e)
            {
                resErrMsg = e.Message;
                result    = false;
            }
            return(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public string ImportProCateData(List <SupplierEntity> list)
        {
            string msg = "";

            try
            {
                foreach (var entity in list)
                {
                    entity.IncludeAll();
                }
                var all = this.Supplier.GetList();
                if (all == null)
                {
                    all = new List <SupplierEntity>();
                }
                var ids = (from i in all select i.ID).ToList();
                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                {
                    this.Supplier.Delete(ids);
                    //先删除在添加
                    this.Supplier.Add(list);
                    ts.Complete();
                }
                CacheHelper.Remove(CacheKey.JOOSHOW_PRODUCT_CACHE);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }

            return(msg);
        }
Ejemplo n.º 3
0
        /// <summary>执行异步添加往来账
        /// </summary>
        /// <param name="readCount"></param>
        public void RunAsynAddTask(int readCount)
        {
            var asynList = _reckoningDao.GetAsynList(readCount);

            foreach (var asynInfo in asynList)
            {
                if (asynInfo.ReckoningFromType == Enum.ASYN.ASYNReckoningFromType.CompleteOrder.ToString())
                {
                    using (var tran = new System.Transactions.TransactionScope())
                    {
                        var orderInfo = _goodsOrder.GetGoodsOrder(asynInfo.IdentifyId);
                        if (orderInfo == null)
                        {
                            continue;
                        }
                        var    orderDetailList = _goodsOrderDetail.GetGoodsOrderDetailByOrderId(asynInfo.IdentifyId);
                        string errorMessage;
                        var    success = AddByCompleteOrder(orderInfo, orderDetailList, out errorMessage);
                        if (!success)
                        {
                            SAL.LogCenter.LogService.LogError(string.Format("异步添加往来帐失败! IdentifyId={0} {1}", asynInfo.IdentifyId, errorMessage), "往来账管理");
                            continue;
                        }
                        var successDel = _reckoningDao.DeleteAsyn(asynInfo.ID);
                        if (!successDel)
                        {
                            SAL.LogCenter.LogService.LogError(string.Format("删除异步往来帐数据失败! ID={0}", asynInfo.ID), "往来账管理");
                            continue;
                        }
                        tran.Complete();
                    }
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 复制角色应用
        /// </summary>
        /// <param name="fromID"></param>
        /// <param name="toID"></param>
        /// <returns></returns>
        public bool CopyRoleApp(Guid fromID, Guid toID)
        {
            var toRole = new Role().Get(toID);

            if (toRole == null)
            {
                return(false);
            }
            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                DeleteByRoleID(toID);//先删除要复制的角色
                var apps = GetAllByRoleID(fromID);
                var root = apps.Find(p => p.ParentID == Guid.Empty);
                if (root != null)
                {
                    Guid fID = root.ID;
                    root.ID     = Guid.NewGuid();
                    root.RoleID = toID;
                    Add(root);
                    insertChilds(fID, root.ID, toID, apps);
                }
                scope.Complete();
                return(true);
            }
        }
Ejemplo n.º 5
0
        public static void AddOrderInTransactionScope()
        {
            Console.WriteLine("Adding two orders using TransactionScope...");
            using (NorthwindEntities northwindEntities = new NorthwindEntities())
            {
                Order firstOrder = new Order();
                firstOrder.CustomerID = "TOMSP";
                firstOrder.ShipName = "First Order Ship Name";
                Order secondOrder = new Order();
                secondOrder.CustomerID = "OCEAN";
                secondOrder.ShipName = "Second Order Ship Name";

                using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
                {
                    northwindEntities.Orders.Add(firstOrder);
                    northwindEntities.SaveChanges();

                    northwindEntities.Orders.Add(secondOrder);
                    northwindEntities.SaveChanges();

                    scope.Complete();
                }

                firstOrder = northwindEntities.Orders.Find(firstOrder.OrderID);
                secondOrder = northwindEntities.Orders.Find(secondOrder.OrderID);
                Console.WriteLine("FirstOrder.ShipName={0}, SecondOrder.ShipName={1}", firstOrder.ShipName, secondOrder.ShipName);
            }
        }
Ejemplo n.º 6
0
 public int ManageDelete(Guid id)
 {
     using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
     {
         try
         {
             EnterpriseBLL enterpriseBLL = new EnterpriseBLL();
             #region 企业搬出
             BaseDb.Delete(id);
             //更新流程中的企业
             enterpriseBLL.MangeDelete(id);
             //new EnterpriseUpdateRecordBLL().MangeDeleteByEnterpriseID(id);变更记录不需要删。
             new EnterpriseTaxBLL().ManageDeleteByEnterpriseID(id);
             #endregion
             scope.Complete();
         }
         catch (Exception ex)
         {
             string       path = "D://log.txt";
             StreamWriter mySw = File.AppendText(path);
             mySw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " EnterpriseAndEnterpriseTaxBLL.ManageDelete:" + ex.Message);
             //关闭日志文件
             mySw.Close();
             return(0);
         }
     }
     return(1);
 }
Ejemplo n.º 7
0
        /// <summary>
        /// MergeSetsAndDoAction
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="uIPrivilegeIds">The u i privilege ids.</param>
        /// <param name="dbPrivilegeIDs">The database privilege i ds.</param>
        /// <param name="delAction">The delete action.</param>
        /// <param name="createAction">The create action.</param>
        /// <example><code>
        /// [Fact]
        ///public void MergePrivilegeIdsTests()
        ///{
        ///    var dbPrivilegeIDs = new int[] { 23, 1, 2, 3, 5, 6 };
        ///    var uIPrivilegeIDs = new int[] { 1, 2, 3, 5, 6 };
        ///    UtilTools.MergeSetsAndDoAction<int>(uIPrivilegeIDs, dbPrivilegeIDs, delSets =>
        ///    {
        ///        delSets.ToList().ForEach(dd => Console.WriteLine("for delete {0}", dd));
        ///    }
        ///     , createSets =>
        ///     {
        ///         createSets.ToList().ForEach(dd => Console.WriteLine("for add {0}", dd));
        ///     });
        ///}
        /// [Fact]
        ///public void TestToWithSameList()
        ///{
        ///    var dbPrivilegeIDs = new int[] { 23, 1, 2, 3, 5, 6 };
        ///    var uIPrivilegeIDs = new int[] { 23, 1, 2, 3, 5, 6 };
        ///    var DifferencesList = dbPrivilegeIDs.Where(x => !uIPrivilegeIDs.Any(x1 => x1 == x))
        ///                .Union(uIPrivilegeIDs.Where(x => !dbPrivilegeIDs.Any(x1 => x1 == x)));
        ///    Assert.True(DifferencesList.Count() == 0);
        ///}
        ///}
        /// </code></example>
        public static bool MergeSetsAndDoAction <T>(T[] uIPrivilegeIds, T[] dbPrivilegeIDs, Action <HashSet <T> > delAction, Action <HashSet <T> > createAction)
        {
            bool flag            = false;
            var  uIPrivilegeSets = new HashSet <T>(uIPrivilegeIds);
            var  dbPrivilegeSets = new HashSet <T>(dbPrivilegeIDs);

            uIPrivilegeSets.SymmetricExceptWith(dbPrivilegeSets);
            //uIPrivilegeIDs.ToList().ForEach(dd => Console.WriteLine(dd));

            dbPrivilegeSets.IntersectWith(uIPrivilegeSets);
            // dbPrivilegeIDs.ToList().ForEach(dd => Console.WriteLine("for delete {0}", dd));
            using (var tsCope = new System.Transactions.TransactionScope())
            {
                //delete action
                if (dbPrivilegeSets.Count != 0)
                {
                    delAction(dbPrivilegeSets);

                    uIPrivilegeSets.ExceptWith(dbPrivilegeSets);
                }

                //add action
                if (uIPrivilegeSets.Count != 0)
                {
                    createAction(uIPrivilegeSets);
                }
                tsCope.Complete();
            }
            flag = true;
            return(flag);
        }
Ejemplo n.º 8
0
        public ActionResult reject(int id)
        {
            int wfpid = id;

            //2.0 修改id对应的数据 中的 处理状态为 拒绝 处理理由,ext1字段为当前登录用户的uid
            string msg = Request.Form["msg"];

            if (msg.IsEmpty())
            {
                return(WriteError("处理理由非空"));
            }

            var process = processSer.QueryWhere(c => c.wfPID == wfpid).FirstOrDefault();

            if (process.wfRFStatus != (int)Enums.ERequestFormStatus.Processing)
            {
                return(WriteError("此单已经被您处理,请勿重复处理"));
            }

            //2.0 对实体进行更新操作
            process.wfRFStatus     = (int)Enums.ERequestFormStatus.Reject;
            process.wfPDescription = msg;
            process.wfPExt1        = UserMgr.GetCurrentUserInfo().uID.ToString();

            var endNode = process.wfWorkNodes.wfWork.wfWorkNodes.OrderBy(c => c.wfnOrderNo).LastOrDefault();

            //3.0 增加一条结束数据
            wfProcess endProcess = new wfProcess()
            {
                fUpdateTime    = DateTime.Now,
                fCreateTime    = DateTime.Now,
                fCreatorID     = UserMgr.GetCurrentUserInfo().uID,
                wfPExt1        = UserMgr.GetCurrentUserInfo().uID.ToString(),
                wfPDescription = "申请单已经结束",
                wfRFStatus     = (int)Enums.ERequestFormStatus.Pass,
                wfRFID         = process.wfRFID,
                wfnID          = endNode.wfnID
            };

            //新增一条结束明细数据
            processSer.Add(endProcess);

            //4.0 将当前提交单的状态修改拒绝状态
            wfRequestForm rfmodel = new wfRequestForm()
            {
                wfRFID     = process.wfRFID,
                wfRFStatus = (int)Enums.ERequestFormStatus.Reject
            };

            requestformSer.Edit(rfmodel, new string[] { "wfRFStatus" });

            using (System.Transactions.TransactionScope scop = new System.Transactions.TransactionScope())
            {
                processSer.SaveChanges();

                scop.Complete();
            }

            return(WriteSuccess("申请单已经拒绝"));
        }
Ejemplo n.º 9
0
        private static void editTitle(int index)
        {
            Task.Run(() =>
            {
                try
                {
                    Console.WriteLine("Start before " + index);
                    using (var trans = new System.Transactions.TransactionScope())
                    {
                        Console.WriteLine("Starting " + index);
                        using (var db = new IntelEntities())
                        {
                            var item     = db.tContents.FirstOrDefault();
                            item.CNTitle = item.CNTitle + "|" + index;
                            db.SaveChanges();
                            Console.WriteLine("Saved " + index);
                        }

                        Thread.Sleep(200);
                        trans.Complete();
                        Console.WriteLine("Completed " + index);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error " + index + " " + ex.Message);
                }
            });
        }
Ejemplo n.º 10
0
        private void btnCustomerDelete_Click(object sender, EventArgs e)
        {
            DataRowView drv = (DataRowView)customerBindingSource.Current;
            if (drv == null)
                return;

            DataRow dr = drv.Row;
            if (MessageBox.Show("確定要刪除顧客 " + DrGetStr(dr, gxxfDataSet.Customer.CustomerNameColumn) + " 和其所有的訂單?", "刪除顧客", MessageBoxButtons.YesNo) != DialogResult.Yes)
                return;
            if (!checkPassword())
                return;

            using (System.Transactions.TransactionScope updateTransaction = new System.Transactions.TransactionScope()) {
                String cid = DrGetStr(dr, this.gxxfDataSet.Customer.customeridColumn);

                dr.Delete();
                customerTableAdapter.Update(dr);

                DataRow[] rows = gxxfDataSet.Ticket.Select("CustomerId = '" + cid + "'");
                foreach (DataRow r in rows) {
                    deleteTicket(r);
                }

                updateTransaction.Complete();
            }
            MessageBox.Show("刪除成功");
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 提交流程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnApply_Click(object sender, EventArgs e)
        {
            try
            {
                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                {
                    using (BizDataContext db = new BizDataContext())
                    {
                        //保存表单实例得到FormInstanceId
                        int fiId = this.formPreview.SaveFormInstance(db);

                        //提交流程
                        string processName = (sender as LinkButton).CommandArgument;
                        Drision.Framework.WorkflowEngineCore.EngineProxy proxy = new WorkflowEngineCore.EngineProxy(db);
                        proxy.StartProcess(processName, this.LoginUserID, fiId);
                    }
                    ts.Complete();
                }
                this.AjaxAlertAndRedirect("提交成功", "FormInstanceQuery.aspx");
            }
            catch (Exception ex)
            {
                this.AjaxAlertAndEnableButton(ex);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 删除一个机构及其所有下级(包括下级人员)
        /// </summary>
        /// <param name="orgID"></param>
        /// <returns></returns>
        public int DeleteAndAllChilds(Guid orgID)
        {
            int i = 0;

            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                UsersRelation bur      = new UsersRelation();
                Users         user     = new Users();
                UsersInfo     userInfo = new UsersInfo();
                var           childs   = GetAllChilds(orgID);
                foreach (var child in childs)
                {
                    //删除人员及关系
                    var urs = bur.GetAllByOrganizeID(child.ID);
                    foreach (var ur in urs)
                    {
                        bur.Delete(ur.UserID, ur.OrganizeID);
                        user.Delete(ur.UserID);
                        i += userInfo.Delete(ur.UserID);
                    }
                    i += Delete(child.ID);
                }
                //删除人员及关系
                var urs1 = bur.GetAllByOrganizeID(orgID);
                foreach (var ur in urs1)
                {
                    bur.Delete(ur.UserID, ur.OrganizeID);
                    user.Delete(ur.UserID);
                    i += userInfo.Delete(ur.UserID);
                }
                i += Delete(orgID);
                scope.Complete();
            }
            return(i);
        }
Ejemplo n.º 13
0
        public void RecommendAFriend(int referrerId, NewAccount friendsAccountDetails)
        {
            Validate(friendsAccountDetails);

            using (var transaction = new System.Transactions.TransactionScope())
            {
                try
                {
                    var referrer = customerDirectory.Find(referrerId);
                    var friend = customerDirectory.Add(friendsAccountDetails);
                    referAFriendPolicy.Apply(referrer, friend);

                    transaction.Complete();

                    var msg = new CustomerRegisteredViaReferralPolicy
                    {
                        ReferrerId = referrerId,
                        FriendId = friend.Id
                    };
                    bus.Publish(msg);

                }
                catch (ReferralRejectedDueToLongTermOutstandingBalance)
                {
                    var msg = new ReferralSignupRejected
                    {
                        ReferrerId = referrerId,
                        FriendEmail = friendsAccountDetails.Email,
                        Reason = "Referrer has long term outstanding balance"
                    };
                    bus.Publish(msg);
                }
            }
        }
Ejemplo n.º 14
0
 public static List<Media_Albums> GetActiveListByTypeIdFixedNum(int TypeId, int iTotalItemCount)
 {
     using (System.Transactions.TransactionScope transScope = new System.Transactions.TransactionScope())
     {
         List<Media_Albums> lst = new List<Media_Albums>();
         using (MediaEntities dbContext = new MediaEntities())
         {
             try
             {
                 dbContext.CommandTimeout = 216000;
                 var query = from x in dbContext.Media_Albums where x.Status =="1" && x.TypeId ==TypeId orderby x.AlbumId descending select x;
                 int TotalItemCount = 0;
                 if (query.Count() > 0)
                 {
                     if (iTotalItemCount <= query.Count())
                         TotalItemCount = iTotalItemCount;
                     else
                         TotalItemCount = query.Count();
                 }                        
                 lst = query.Take(TotalItemCount).ToList();
                 transScope.Complete();
             }catch(Exception  ex){ex.InnerException.Message.ToString();}
             finally
             {
                 if (dbContext.Connection.State != System.Data.ConnectionState.Closed)                       
                     dbContext.Connection.Close();                       
             }
             return lst;
         }                
     }
 }
Ejemplo n.º 15
0
        public void AddToCart(Album album)
        {
            using (var scope = new System.Transactions.TransactionScope())
            {
                // Get the matching cart and album instances
                var cartItem = storeDB.Carts.SingleOrDefault(c => c.CartId == ShoppingCartId && c.AlbumId == album.AlbumId);

                if (cartItem == null)
                {
                    // Create a new cart item if no cart item exists
                    cartItem = new Cart
                    {
                        AlbumId = album.AlbumId,
                        CartId = ShoppingCartId,
                        Count = 1,
                        DateCreated = DateTime.Now
                    };

                    storeDB.Carts.Add(cartItem);
                }
                else
                {
                    // If the item does exist in the cart, then add one to the quantity
                    cartItem.Count++;
                }

                // Save changes
                storeDB.SaveChanges();

                scope.Complete();
            }
        }
Ejemplo n.º 16
0
 public static void AddSubscriber(Guid clientKey, string[] fixMsgsTypes, string callbackQueue)
 {
     lock (m_sessions)
     {
         if (!m_sessions.ContainsKey(clientKey))
         {
             string msgTypesString = string.Empty;
             foreach (string msgType in fixMsgsTypes)
             {
                 msgTypesString += string.Format("{0},", msgType);
                 if (!m_fixMsgType_SubscribersKeys.ContainsKey(msgType))
                 {
                     m_fixMsgType_SubscribersKeys.Add(msgType, new List <Guid>());
                 }
                 if (!m_fixMsgType_SubscribersKeys[msgType].Contains(clientKey))
                 {
                     m_fixMsgType_SubscribersKeys[msgType].Add(clientKey);
                 }
             }
             msgTypesString = msgTypesString.Remove(msgTypesString.Length - 1, 1);
             using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
             {
                 DateTime        dtNow = DateTime.Now;
                 DatabaseMethods db    = new DatabaseMethods();
                 db.AddReplicationSessionSubscriber(clientKey, msgTypesString, callbackQueue, dtNow);
                 m_sessions.Add(clientKey, new ReplicatedSessionSubscriberDetails()
                 {
                     SessionRemoteQueue = new MessageQueue(callbackQueue), SubscribedFixMsgsTypes = fixMsgsTypes, LastHeartBeatRequest = dtNow, LastHeartBeatResponse = dtNow, QueuePath = callbackQueue, SubscriberKey = clientKey, SubscriptionDateTime = dtNow
                 });
                 ts.Complete();
             }
         }
     }
 }
Ejemplo n.º 17
0
 public ActionResult ConfirmMail([Bind(Exclude = "AuthCode")] string uid, UserInfo userinfo)
 {
     try
     {
         using (System.Transactions.TransactionScope transaction = new System.Transactions.TransactionScope())
         {
             userinfo = db.UserInfo.FirstOrDefault(p => p.Uid == uid);
             userinfo.Email = Request["newmail"];
             userinfo.AuthCode = Guid.NewGuid().ToString();
             UpdateModel(userinfo);
             db.SubmitChanges();
             System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient("smtp.qq.com", 25);
             sc.Credentials = new System.Net.NetworkCredential("342354548", "0oO0oO");
             sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
             string verify_url = new Uri(Request.Url, System.Web.Routing.RouteTable.Routes.GetVirtualPath
                 (Request.RequestContext, new System.Web.Routing.RouteValueDictionary
                     (new { action = "Verify", authCode = userinfo.AuthCode })).VirtualPath).AbsoluteUri;
             sc.Send("*****@*****.**", userinfo.Email, "会员注册确认信", verify_url);
             transaction.Complete();
         }
         Session["CurrentUser"] = null;
         return Content("验证邮件已发出,请验证后重新登录!");
     }
     catch (Exception ex)
     {
         ex.ToString();
         return Content("验证邮箱不存在,请重新填写!");
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool Save()
        {
            var tradeJournal = TradeJournal.FindById(this.TradeCode);

            if (null == tradeJournal)
            {
                return(false);
            }

            if (tradeJournal.TradeStatus >= TradeStatus.Paid)
            {
                return(true);
            }

            this.OwnerId        = tradeJournal.OwnerId;
            this.CredentialSign = null;
            this.PaidTime       = DateTime.Now;
            this.CredentialSign = GenerateSign(tradeJournal, this);

            using (var scope = new System.Transactions.TransactionScope())
            {
                var repository = RepositoryManager.GetRepository <IPaymentCredentialRepository>(ModuleEnvironment.ModuleName);
                var saved      = repository.Save(this);

                if (saved)
                {
                    tradeJournal.PayWay      = this.PaidWay;
                    tradeJournal.TradeStatus = TradeStatus.Paid;
                    saved = tradeJournal.Save();
                    scope.Complete();
                }

                return(saved);
            }
        }
Ejemplo n.º 19
0
        public void RecommendAFriend(int referrerId, NewAccount friendsAccountDetails)
        {
            Validate(friendsAccountDetails);

            // most technologies have similar transaction APIs
            using (var transaction = new System.Transactions.TransactionScope())
            {
                try
                {
                    // customerDirectory is a domain repository
                    var referrer = customerDirectory.Find(referrerId);
                    var friend   = customerDirectory.Add(friendsAccountDetails);
                    // referAFriend policy is a domain policy
                    referAFriendPolicy.Apply(referrer, friend);

                    transaction.Complete();

                    // log here to keep to avoid cluttering domain
                    logger.Debug("Successful friend recommendation");
                    StatsdClient.Metrics.Counter("friendReferrals");
                }
                catch (ReferralRejectedDueToLongTermOutstandingBalance ex)
                {
                    logger.Error(ex);
                    StatsdClient.Metrics.Counter("ReferralRejected");
                    throw new ApplicationError(
                              "Sorry, this referral cannot be completed. The referrer " +
                              "currently has an outstanding balance. Please contact " +
                              "customer support"
                              );
                    // transaction will roll back if Complete() not called
                }
            }
        }
Ejemplo n.º 20
0
        public void Delete(int itemid)
        {
            var transactionOptions = new System.Transactions.TransactionOptions();

            transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;

            using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions))
            {
                using (dotnetnukeEntities db = new dotnetnukeEntities())
                {
                    try
                    {
                        dnn_YourCompany_LogEntry _logEntry = db.dnn_YourCompany_LogEntry
                                                             .Where(e => e.ItemID == itemid).FirstOrDefault();
                        if (_logEntry != null)
                        {
                            db.Configuration.ProxyCreationEnabled = false;
                            db.Set <dnn_YourCompany_LogEntry>().Remove(_logEntry);
                            db.SaveChanges();
                        }
                    }
                    catch (Exception e)
                    {
                        string error = e.Message;
                    }
                }
                transactionScope.Complete();
            }
        }
Ejemplo n.º 21
0
        public int Post(dnn_YourCompany_LogEntry logEntry)
        {
            var transactionOptions = new System.Transactions.TransactionOptions();

            transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            int newItemid = 0;

            using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions))
            {
                using (dotnetnukeEntities db = new dotnetnukeEntities())
                {
                    try
                    {
                        db.Configuration.ProxyCreationEnabled = false;
                        logEntry.CreatedDate = DateTime.Now;
                        logEntry.EntryDate   = DateTime.Now;
                        logEntry.ModuleID    = 380;
                        db.Set <dnn_YourCompany_LogEntry>().Add(logEntry);
                        db.SaveChanges();
                        newItemid = logEntry.ItemID;
                    }
                    catch (Exception e)
                    {
                        string error = e.Message;
                    }
                }
                transactionScope.Complete();
            }
            return(newItemid);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// IP登记表删除服务,传入对象进行删除操作
        /// </summary>20170117XCQ
        /// <param name="model"></param>
        /// <returns></returns>
        public CommonResult <IPRegistForm> DeleteRegistFormById(IPRegistForm model)
        {
            var result = new CommonResult <IPRegistForm>();

            try
            {
                var dbSession = new DBService <IPRegistForm>().DbSession;
                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                {
                    var ServerModel = dbSession.GetQueryable(t => t.ID == model.ID).FirstOrDefault();
                    if (ServerModel != null)
                    {
                        dbSession.Delete(ServerModel);
                        ts.Complete();
                        result.IsSuccess = true;
                    }
                    else
                    {
                        result.IsSuccess = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.Logger.Error(ex.Message);
                throw ex;
            }
            return(result);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 收回任务
        /// </summary>
        /// <param name="taskID"></param>
        /// <returns></returns>
        public bool WithdrawTask(Guid taskID)
        {
            var taskList1 = GetTaskList(taskID);

            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                foreach (var task in taskList1)
                {
                    var taskList2 = GetNextTaskList(task.ID);
                    foreach (var task2 in taskList2)
                    {
                        if (task2.Status == 0 || task2.Status == 1 || task2.Status == 5)
                        {
                            Delete(task2.ID);
                        }
                    }

                    if (task.ID == taskID || task.Status == 4)
                    {
                        Completed(task.ID, "", false, 1, "");
                    }
                }
                scope.Complete();
                return(true);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 运营信息录入
        /// </summary>
        /// <param name="operatingInfo">运营</param>
        /// <returns>添加结果</returns>
        public bool Add(OperatingInfo operatingInfo)
        {
            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                var result = true;

                // 添加BinkInfos
                BankInfoMapper.Insert(operatingInfo.BankInfos[0]);
                result &= operatingInfo.BankInfos[0].FinanceId > 0;
                BankInfoMapper.Insert(operatingInfo.BankInfos[1]);
                result &= operatingInfo.BankInfos[1].FinanceId > 0;

                // 更新融资信息
                var finance = BinanceInfoMapper.Find(operatingInfo.Finance.FinanceId.Value);
                if (finance != null)
                {
                    finance.MarginMoney         = operatingInfo.Finance.MarginMoney;
                    finance.PaymonthlyMoney     = operatingInfo.Finance.PaymonthlyMoney;
                    finance.OnepayInterestMoney = operatingInfo.Finance.OnepayInterestMoney;
                    finance.ActualcashMoney     = operatingInfo.Finance.ActualcashMoney;

                    result &= BinanceInfoMapper.Update(finance) > 0;
                }

                // 跟新融资扩展信息
                var financeExtra = BinanceExtraInfoMapper.Find(operatingInfo.Finance.FinanceId.Value);
                if (financeExtra != null)
                {
                    financeExtra.ActualVehiclePrice                   = operatingInfo.FinanceExtra.ActualVehiclePrice;
                    financeExtra.ActualPurchaseTaxPrice               = operatingInfo.FinanceExtra.ActualPurchaseTaxPrice;
                    financeExtra.ActualBusinessInsurancePrice         = operatingInfo.FinanceExtra.ActualBusinessInsurancePrice;
                    financeExtra.ActualTafficCompulsoryInsurancePrice = operatingInfo.FinanceExtra.ActualTafficCompulsoryInsurancePrice;
                    financeExtra.ActualVehicleVesselTaxPrice          = operatingInfo.FinanceExtra.ActualVehicleVesselTaxPrice;
                    financeExtra.ActualExtendedWarrantyInsurancePrice = operatingInfo.FinanceExtra.ActualExtendedWarrantyInsurancePrice;
                    financeExtra.ActualOtherPrice = operatingInfo.FinanceExtra.ActualOtherPrice;

                    result &= BinanceExtraInfoMapper.Update(financeExtra) > 0;
                }

                // 跟新车辆信息
                var vehicle = VehicleInfoMapper.Find(operatingInfo.Finance.FinanceId.Value);
                if (vehicle != null)
                {
                    vehicle.PlateNo      = operatingInfo.VehicleInfo.PlateNo;
                    vehicle.FrameNo      = operatingInfo.VehicleInfo.FrameNo;
                    vehicle.EngineNo     = operatingInfo.VehicleInfo.EngineNo;
                    vehicle.BuyCarPrice  = operatingInfo.VehicleInfo.BuyCarPrice;
                    vehicle.RegisterCity = operatingInfo.VehicleInfo.RegisterCity;

                    result &= VehicleInfoMapper.Update(operatingInfo.Finance.FinanceId.Value, vehicle) > 0;
                }

                if (result)
                {
                    scope.Complete();
                }
            }

            return(false);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 更新DeviceWorkingCondition设备状态信息,初期主要用于车号的状态更新,装车时将其WorkingStatus更新为1,卸料时将其更新为0,20170110XC1
        /// </summary>
        /// <param name="DevCode"></param>
        /// <param name="WorkingStatus"></param>
        /// <returns></returns>
        public CommonResult <DeviceWorkingCondition> UpdateDevWStatusByCode(string DevCode, int WorkingStatus)
        {
            var result = new CommonResult <DeviceWorkingCondition>();

            try
            {
                var dbSession = new DBService <DeviceWorkingCondition>().DbSession;
                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                {
                    var model = dbSession.GetQueryable(t => t.DevCode == DevCode).FirstOrDefault();
                    if (model == null)
                    {
                        result.IsSuccess = false;
                        result.Message   = "该设备信息已经不存在";
                    }
                    model.WorkingStatus = WorkingStatus;
                    result.Data         = dbSession.Update(model);
                    ts.Complete();
                }
            }
            catch (Exception ex)
            {
                Utils.Logger.Error(ex.Message);
                throw ex;
            }

            return(result);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 删除医院
        /// </summary>
        /// <param name="hospitalID">医院ID</param>
        /// <returns>是否删除成功</returns>
        public bool DeleteHospitalByHospitalID(int hospitalID)
        {
            bool isSuccess = false;

            try
            {
                using (System.Transactions.TransactionScope transactionScope = new System.Transactions.TransactionScope())
                {
                    using (MedicalBaseEntities context = new MedicalBaseEntities())
                    {
                        Hospital hospitalForDelete = (from p in context.Hospitals
                                                      where p.ID == hospitalID
                                                      select p).FirstOrDefault();
                        context.CascadingDeleteOnSubmit(hospitalForDelete);
                    }
                    transactionScope.Complete();
                }
                isSuccess = true;
            }
            catch
            {
                isSuccess = false;
            }
            return(isSuccess);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 清除所有日志信息
        /// </summary>
        /// <returns>是否清除成功</returns>
        public bool ClearLogs()
        {
            bool isSuccess = false;

            try
            {
                using (System.Transactions.TransactionScope transactionScope = new System.Transactions.TransactionScope())
                {
                    using (MedicalBaseEntities context = new MedicalBaseEntities())
                    {
                        foreach (var item in context.Log_Login)
                        {
                            context.DeleteObject(item);
                        }
                        context.SaveChanges();
                    }
                    transactionScope.Complete();
                }
                isSuccess = true;
            }
            catch
            {
                isSuccess = false;
            }
            return(isSuccess);
        }
Ejemplo n.º 28
0
        public void InsertTweets(IEnumerable<Tweet> tweets)
        {
            using (var scope = new System.Transactions.TransactionScope())
            {

                MasterEntities context = null;
                try
                {
                    context = CreateContext();

                    int count = 0;
                    foreach (var entityToInsert in tweets)
                    {
                        ++count;
                        entityToInsert.Id =Guid.NewGuid();
                        entityToInsert.Date = DateTime.Now;
                        context = AddToContext(context, entityToInsert, count, 50, false);
                    }

                    context.SaveChanges();
                }
                finally
                {
                    if (context != null)
                        context.Dispose();
                }

                scope.Complete();
            }
        }
Ejemplo n.º 29
0
        public void ProcessRequest(HttpContext context)
        {
            NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;
            NFMT.Common.ResultModel result = new NFMT.Common.ResultModel();

            context.Response.ContentType = "text/plain";
            int id = 0;
            int operateId = 0;

            if (!int.TryParse(context.Request.Form["id"], out id) || id <= 0)
            {
                context.Response.Write("序号错误");
                context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result));
                context.Response.End();
            }

            if (!int.TryParse(context.Request.Form["oi"], out operateId) || operateId <= 0)
            {
                context.Response.Write("操作错误");
                context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result));
                context.Response.End();
            }

            NFMT.Contract.BLL.ContractBLL contractBLL = new NFMT.Contract.BLL.ContractBLL();
            NFMT.WareHouse.BLL.ContractStockIn_BLL refBLL = new NFMT.WareHouse.BLL.ContractStockIn_BLL();

            NFMT.Common.OperateEnum operateEnum = (NFMT.Common.OperateEnum)operateId;
            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                switch (operateEnum)
                {
                    case NFMT.Common.OperateEnum.作废:
                        result = contractBLL.ContractInInvalid(user, id);
                        if (result.ResultStatus == 0)
                            result = refBLL.ContractInInvalidStockOperate(user, id);
                        break;
                    case NFMT.Common.OperateEnum.撤返:
                        result = contractBLL.ContractInGoBack(user, id);
                        break;
                    case NFMT.Common.OperateEnum.执行完成:
                        result = contractBLL.ContractInComplete(user, id);
                        if (result.ResultStatus == 0)
                            result = refBLL.ContractInCompleteStockOperate(user, id);
                        break;
                    case NFMT.Common.OperateEnum.执行完成撤销:
                        result = contractBLL.ContractInCompleteCancel(user, id);
                        if (result.ResultStatus == 0)
                            result = refBLL.ContractInCompleteCancelStockOperate(user, id);
                        break;
                }

                if (result.ResultStatus == 0)
                {
                    result.Message = string.Format("{0}成功", operateEnum.ToString());
                    scope.Complete();
                }
            }

            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result));
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Edita una Sucursal
        /// </summary>
        /// <param name="id_compania_emisor"></param>
        /// <param name="nombre"></param>
        /// <param name="id_direccion"></param>
        /// <param name="id_usuario"></param>
        /// <param name="habilitar"></param>
        /// <returns></returns>
        private RetornoOperacion editaSucursal(int id_compania_emisor, string nombre, int id_direccion, int id_usuario, bool habilitar)
        {
            //Declaramos Objeto resultado
            RetornoOperacion resultado = new RetornoOperacion();

            //Creamos la transacción
            using (System.Transactions.TransactionScope scope = Transaccion.InicializaBloqueTransaccional(System.Transactions.IsolationLevel.ReadCommitted))
            {
                //Validamo existencia de ubicación
                if (!Validacion.ValidaOrigenDatos(Comprobante.RecuperaComprobantesPorSucursal(this._id_sucursal)))
                {
                    //Inicializando arreglo de parámetros
                    object[] param = { 2, this._id_sucursal, id_compania_emisor, nombre, id_direccion, id_usuario, habilitar, "", "" };

                    //Realizando actualizacion
                    resultado = CapaDatos.m_capaDeDatos.EjecutaProcAlmacenadoObjeto(_nombre_stored_procedure, param);
                }
                else
                {
                    resultado = new RetornoOperacion("No puede ser editado el registro debido a que está ligado a un CFD.");
                }
                //Validamos Resultado
                if (resultado.OperacionExitosa)
                {
                    //Finalizamos Transacción
                    scope.Complete();
                }
            }

            //Devolvemos Resultado
            return(resultado);
        }
Ejemplo n.º 31
0
        public IBill CreateBill(long uid, string sender, string senderTel, string receiver, string receiverTel, string address, string post, decimal insurance, string goods, string remarks, long? agentUid, DateTime? created, string internalNo, string internalExpress)
        {
            var user = _UserManager.GetUser(uid);
            var creater = new BillUser(user, _BillRepository, _BillStateHistoryRepository);
            using (var scope = new System.Transactions.TransactionScope())
            {
                var bill = creater.CreateBill(new ContactInfo(sender, senderTel),
                    new ContactInfoWithAddress(receiver, receiverTel, new Address(address, post)),
                    insurance, goods, remarks);
                var authority = new BillAuthority(user, bill);
                if (authority.AllowSetAgent || authority.AllowFillAgentSelf)
                {
                    IBillManagerUser manager = creater;
                    manager.UpdateAgent(bill, authority.AllowSetAgent ? agentUid ?? uid : uid);
                    manager.UpdateBillState(bill, BillStates.到达分拣中心, String.Empty);
                }
                if (created.HasValue && authority.AllowSetCreateDate)
                {
                    IBillManagerUser manager = creater;
                    manager.UpdateCreated(bill, created.Value);
                }
                if((!String.IsNullOrWhiteSpace(internalNo) || !String.IsNullOrWhiteSpace(internalExpress)) && authority.AllowUpdateState)
                {
                    IBillManagerUser manager = creater;
                    manager.UpdateBillInternalState(bill, new InternalTrade(internalNo, internalExpress), String.Empty, null);
                }

                scope.Complete();

                return bill;
            }
        }
        public void CommitTest()
        {
            using (var session = Domain.OpenSession())
                using (var tx = session.OpenTransaction()) {
                    new DataRecord {
                        Name = "CommitTest", Value = "False"
                    };
                    tx.Complete();
                }

            //this behavior is not supported by netcore2.0
            using (var ts = new SystemTransactionScope()) {
                using (var session = Domain.OpenSession())
                    using (var tx = session.OpenTransaction()) {
                        var record = session.Query.All <DataRecord>().Single(e => e.Name == "CommitTest");
                        record.Value = "True";
                        tx.Complete();
                    }
                ts.Complete();
            }

            using (var session = Domain.OpenSession())
                using (var tx = session.OpenTransaction()) {
                    var record = session.Query.All <DataRecord>().Single(e => e.Name == "CommitTest");
                    Assert.That(record.Value, Is.EqualTo("True"));
                    tx.Complete();
                }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// 删除工艺参数设置
        /// </summary>
        /// <param name="ID">编号</param>
        /// <returns></returns>
        public CommonResult <bool> DelCLParamSet(int ID)
        {
            var result = new CommonResult <bool>();

            try
            {
                var dbSession  = new DBService <CraftsLineParamSet>().DbSession;
                var dbSession1 = new DBService <CraftsLineParamSetDetail>(dbSession.Context).DbSession;
                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                {
                    var model     = dbSession.GetQueryable(t => t.ID == ID).FirstOrDefault();
                    var modelList = dbSession1.GetQueryable(t => t.ID == ID).ToList();
                    if (modelList != null && modelList.Count > 0)
                    {
                        dbSession1.Delete(modelList);
                    }
                    dbSession.Delete(model);
                    ts.Complete();
                    result.Data = true;
                }
            }
            catch (Exception ex)
            {
                Utils.Logger.Error(ex.ToString());
                throw ex;
            }
            return(result);
        }
Ejemplo n.º 34
0
        public void ChangePassword(Guid userId, string olderPaswword, string newPassword)
        {
            using (System.Transactions.TransactionScope tr = new System.Transactions.TransactionScope())
            {
                ICollection <TakeDocModel.UserTk> users = this.GetBy(x => x.UserTkId == userId);
                if (users.Count != 1)
                {
                    base.CreateError("L'utilisateur est iconnu.");
                }

                TakeDocModel.UserTk user = users.First();
                // check older password
                if (user.UserTkPassword != servCrypto.Encrypt(olderPaswword))
                {
                    this.CreateError("Mot de passe erronné.");
                }
                user.UserTkPassword = servCrypto.Encrypt(newPassword);
                this.Check(user, false);

                // update password
                daoUserTk.Update(user);

                tr.Complete();
            }
        }
Ejemplo n.º 35
0
        public IQueryable <dnn_YourCompany_LogEntry> Get(string keyWord)
        {
            IQueryable <dnn_YourCompany_LogEntry> items = null;
            var transactionOptions = new System.Transactions.TransactionOptions();

            transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;

            using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions))
            {
                using (dotnetnukeEntities db = new dotnetnukeEntities())
                {
                    try
                    {
                        db.Configuration.ProxyCreationEnabled = false;
                        items = db.dnn_YourCompany_LogEntry.Where(e => e.Entry.Contains(keyWord))
                                .ToList().AsQueryable <dnn_YourCompany_LogEntry>();
                    }
                    catch (Exception e)
                    {
                        string error = e.Message;
                    }
                }
                transactionScope.Complete();
            }
            return(items);
        }
Ejemplo n.º 36
0
        /// <summary>
        /// 删除流程参与人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                long?id = (sender as LinkButton).CommandArgument.ToLongNullable();
                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                {
                    using (BizDataContext db = new BizDataContext())
                    {
                        SysProcessParticipant p = db.FindById <SysProcessParticipant>(id);
                        if (p != null)
                        {
                            //同步删除关联的活动参与人
                            var apList = db.Where <SysActivityParticipant>(x => x.ParticipantId == id);
                            foreach (var ap in apList)
                            {
                                db.Delete(ap);
                            }

                            db.Delete(p);
                        }
                    }
                    ts.Complete();
                }
                BindGrid();
            }
            catch (Exception ex)
            {
                this.AjaxAlert(ex);
            }
        }
Ejemplo n.º 37
0
 ////INSERT- UPDATE - DELETE 
 public int Insert(int PortalId, int ContentItemId, string CultureCode, string RouteName, string RouteUrl, string PhysicalFile,
 bool CheckPhysicalUrlAccess, string RouteValueDictionary, string Description, bool Discontinued)
 {
     int returnValue = 0;
     using (CommonEntities dbContext = new CommonEntities())
     {
         using (System.Transactions.TransactionScope transcope = new System.Transactions.TransactionScope())
         {
             int ListOrder = (from u in dbContext.aspnet_Routes select u.ListOrder).DefaultIfEmpty(0).Max() + 1;
             aspnet_Routes entity = new aspnet_Routes();
             entity.PortalId = PortalId;
             entity.ContentItemId = ContentItemId;
             entity.CultureCode = CultureCode;
             entity.RouteName = RouteName;
             entity.RouteUrl = RouteUrl;
             entity.PhysicalFile = PhysicalFile;
             entity.CheckPhysicalUrlAccess = CheckPhysicalUrlAccess;
             entity.RouteValueDictionary = RouteValueDictionary;
             entity.Description = Description;
             entity.ListOrder = ListOrder;
             entity.Discontinued = Discontinued;
             dbContext.AddToaspnet_Routes(entity);
             returnValue = dbContext.SaveChanges();
             dbContext.Connection.Close();
             transcope.Complete();
         }
     }
     return returnValue;
 }
Ejemplo n.º 38
0
        internal static void RemoveCallback(Guid clientKey)
        {
            lock (m_LockedObj)
            {
                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                {
                    DatabaseMethods db = new DatabaseMethods();
                    db.RemoveReplicationSessionSubscriber(clientKey);

                    if (m_sessions.ContainsKey(clientKey))
                    {
                        // remove subscriber from subscribed messages
                        string[] subscribedMsgs = m_sessions[clientKey].SubscribedFixMsgsTypes;
                        foreach (string msg in subscribedMsgs)
                        {
                            if (m_fixMsgType_SubscribersKeys.ContainsKey(msg))
                            {
                                m_fixMsgType_SubscribersKeys[msg].Remove(clientKey);
                                if (m_fixMsgType_SubscribersKeys[msg].Count == 0)
                                {
                                    m_fixMsgType_SubscribersKeys.Remove(msg);
                                }
                            }
                        }
                        // remove subscriiber from subscribers list
                        m_sessions.Remove(clientKey);
                    }
                    ts.Complete();
                }
            }
        }
Ejemplo n.º 39
0
        public JsonResult PackageWBSCopy(string ProjectInfoID, string TargetNodes, string DataSource)
        {
            var    targetNodes = JsonHelper.ToList(TargetNodes);
            var    sourceNodes = JsonHelper.ToList(DataSource);
            Action action      = () =>
            {
                var fo = FormulaHelper.CreateFO <WBSFO>();
                fo.ImportPackageNodes(targetNodes, sourceNodes);
            };

            if (System.Configuration.ConfigurationManager.AppSettings["UseMsdtc"].ToLower() == "true")
            {
                System.Transactions.TransactionOptions tranOp = new System.Transactions.TransactionOptions();
                tranOp.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                using (System.Transactions.TransactionScope ts =
                           new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, tranOp))
                {
                    action();
                    ts.Complete();
                }
            }
            else
            {
                action();
            }
            return(Json(""));
        }
Ejemplo n.º 40
0
        //================================================================
        //登録   今日のひとこと記事  
        //================================================================
        public bool add(CardContentData addData, ref int?insertedID, ref string resErrMsg)
        {
            DateTime regDate = DateTime.Now;
            bool     result  = false;

            try
            {
                using (umekoudbDataContext dc = new umekoudbDataContext())
                {
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                    {
                        addData.raw.reg_date = regDate;
                        dc.GetTable <card_t>().InsertOnSubmit(addData.raw);
                        dc.SubmitChanges();
                        insertedID = addData.raw.id;//主キーをセット
                        ts.Complete();
                    }
                }
                result = true;
            }
            catch (Exception e)
            {
                resErrMsg = e.Message;
                result    = false;
            }
            return(result);
        }
Ejemplo n.º 41
0
 public void GuardarCuConfigurarIgv(string valor)
 {
     using (var transaction = new System.Transactions.TransactionScope())
     {
         dominio.ActualizarValorConfigByCodigo("01",valor);
         transaction.Complete();
     }
 }
Ejemplo n.º 42
0
        public void ProcessRequest(HttpContext context)
        {
            NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            context.Response.ContentType = "text/plain";

            NFMT.Common.ResultModel result = new NFMT.Common.ResultModel();

            if (string.IsNullOrEmpty(context.Request.Form["source"]))
            {
                result.Message = "数据源为空";
                result.ResultStatus = -1;
                context.Response.Write(serializer.Serialize(result));
                context.Response.End();
            }

            bool isPass = false;
            if (string.IsNullOrEmpty(context.Request.Form["ispass"]) || !bool.TryParse(context.Request.Form["ispass"], out isPass))
            {
                result.Message = "审核结果错误";
                result.ResultStatus = -1;
                context.Response.Write(serializer.Serialize(result));
                context.Response.End();
            }

            try
            {
                string jsonData = context.Request.Form["source"];
                var obj = serializer.Deserialize<NFMT.WorkFlow.Model.DataSource>(jsonData);

                using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
                {
                    NFMT.Contract.BLL.ContractBLL bll = new NFMT.Contract.BLL.ContractBLL();
                    result = bll.ContractInAudit(user, obj, isPass);
                    if (result.ResultStatus == 0)
                    {
                        int contractId = (int)result.ReturnValue;
                        int subId = result.AffectCount;

                        NFMT.WareHouse.BLL.StockLogBLL stockLogBLL = new NFMT.WareHouse.BLL.StockLogBLL();
                        result = stockLogBLL.ContractInAuditStockLogOperate(user, contractId, subId);
                    }

                    if (result.ResultStatus == 0)
                        scope.Complete();
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                result.ResultStatus = -1;
            }

            context.Response.Write(serializer.Serialize(result));
            context.Response.End();
        }
Ejemplo n.º 43
0
 public static void Test2()
 {
     var mb = ConfigureMongoBus();
     using (var ts = new System.Transactions.TransactionScope())
     {
         for (int i = 0; i < 10000; i++)
         {
             mb.Notify(new TestMessage1 { Id = 101 + i });
         }
         ts.Complete();
     }
 }
Ejemplo n.º 44
0
 public IQueryable<vu_DashboardLogsLatest> Refresh()
 {
     IQueryable<vu_DashboardLogsLatest> data;
     var transactionOptions = new System.Transactions.TransactionOptions();
     transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
     using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions))
     {
         if (_bitsDashboardContext != null)
             _bitsDashboardContext.Connection.Close();
         _bitsDashboardContext = new DashboardEntities();
         data =  _bitsDashboardContext.vu_DashboardLogsLatest.OrderByDescending(logData => logData.StartTime);
         transactionScope.Complete();
         return data;
     }
 }
Ejemplo n.º 45
0
        //When this static class is first initialized, determine whether we can use the TransactionScope object (TransactionScopeOption.Required),
		// or not (TransactionScopeOption.Suppress).  
		static Common()
		{
			try
			{
				using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required))
				{
					Guid g = GetPersonId("");
					ts.Complete();
					_transactionScopeOption = System.Transactions.TransactionScopeOption.Required;
				}
			}
			catch
			{
				_transactionScopeOption = System.Transactions.TransactionScopeOption.Suppress;
			}
		}
Ejemplo n.º 46
0
        public void RecommendAFriend(int referrerId, NewAccount friendsAccountDetails)
        {
            Validate(friendsAccountDetails);

            // most technologies have similar transaction APIs
            using (var transaction = new System.Transactions.TransactionScope())
            {
                try
                {
                    // ... interact with domain multiple times
                    transaction.Complete();
                }
                catch
                {
                    // transaction will roll back if Complete() not called
                }
            }
        }
Ejemplo n.º 47
0
        //
        // GET: /Store/AddToCart/5
        public virtual ActionResult AddToCart(int id)
        {
            using (var scope = new System.Transactions.TransactionScope())
            {
                // Retrieve the album from the database
                var addedAlbum = storeDB.Albums
                    .Single(album => album.AlbumId == id);

                // Add it to the shopping cart
                var cart = ShoppingCart.GetCart(this.HttpContext);

                cart.AddToCart(addedAlbum);

                scope.Complete();

                // Go back to the main store page for more shopping
                return RedirectToAction("Index");
            }
        }
        protected Product Save()
        {
            Product product = null;
            //uncomment this line to support transactions
            using (var scope = new System.Transactions.TransactionScope())
            {
                product = ctrlProductInfoAdd.SaveInfo();
                ctrlProductSEO.SaveInfo(product.ProductId);
                ctrlProductCategory.SaveInfo(product.ProductId);

                this.CustomerActivityService.InsertActivity(
                    "AddNewProduct",
                    GetLocaleResourceString("ActivityLog.AddNewProduct"),
                    product.Name);

                //uncomment this line to support transactions
                scope.Complete();
            }

            return product;
        }
 public static int BatchInsert(List<Transaction> list, int? companyId, DbActionType action)
 {
     var res = -1;
     var commName = action == DbActionType.Insert ? "transaction_create" : "web.transaction_update";
     using (var scope = new System.Transactions.TransactionScope())
     {
         using (var holder = SqlConnectionHelper.GetConnection())
         {
             var cmd = holder.Connection.CreateSPCommand(commName);
             //SqlTransaction transaction = holder.Connection.BeginTransaction("BatchInsertTransactions");
             //cmd.Transaction = transaction;
             try
             {
                 foreach (var entity in list)
                 {
                     cmd.Parameters.Clear();
                     cmd.AddEntityParameters(entity, action);
                     if (action == DbActionType.Update)
                         cmd.Parameters.AddWithValue("@id_company", companyId);
                     cmd.ExecuteNonQuery();
                     if (action == DbActionType.Insert)
                         entity.Id = cmd.GetRowIdParameter();
                     int l_res = cmd.GetReturnParameter();
                     if (l_res != 0)
                         return l_res;
                 }
                 //transaction.Commit();
                 scope.Complete();
                 res = 0;
             }
             catch (SqlException e)
             {
                 //transaction.Rollback();
                 cmd.AddDetailsToException(e);
                 throw;
             }
         }
     }
     return res;
 }
Ejemplo n.º 50
0
 public void OnActionExecuting(ActionExecutingContext filterContext)
 {
     using (var transaction = new System.Transactions.TransactionScope())
     {
         using (var db = new ApplicationDBContext())
         {
             var url = filterContext.RequestContext.HttpContext.Request.RawUrl.ToString();
             VisitsTable vt = db.Visits.Find(url);
             if (vt == null)
             {
                 vt = new VisitsTable { Url = url, Count = 1 };
                 db.Visits.Add(vt);
             }
             else
             {
                 vt.Count = vt.Count+ 1;
             }
             db.SaveChanges();
         }
         transaction.Complete();
     }
 }
		private bool ImportData()
		{
			if (filUpload.PostedFile == null || filUpload.PostedFile.ContentLength == 0)
			{
				RegisterAlert("A valid input file must be selected.");
				return false;
			}
			else
			{
				using (System.Transactions.TransactionScope transScope = new System.Transactions.TransactionScope(Data.Common.TransactionScopeOption))
				{
					if (chkDeleteFirst.Checked)
					{
						Data.ITATSystem.DeleteSequenceNumbers(_itatSystem.ID);
					}
					StreamReader reader = new StreamReader(filUpload.PostedFile.InputStream);
					Data.ITATSystem.UpdateSequenceNumbers(_itatSystem.ID, reader.ReadToEnd());
					transScope.Complete();
					return true;
				}
			}
		}
Ejemplo n.º 52
0
        public IBill CreateBill(ContactInfo sender, ContactInfoWithAddress receiver, decimal insurance, string goods, string remarks)
        {
            ExceptionHelper.ThrowIfNull(sender, "sender");
            ExceptionHelper.ThrowIfNull(receiver, "receiver");

            goods = (goods ?? String.Empty).Trim();
            remarks = (remarks ?? String.Empty).Trim();

            using (var scope = new System.Transactions.TransactionScope())
            {
                var entity = new Data.Bill
                {
                    bill_date = DateTime.Now,
                    confirmed = _User.Role >= UserRoles.Agent,
                    created = DateTime.Now,
                    creater = _User.Uid,
                    enabled = true,
                    last_state_updated = DateTime.Now,
                    updated = DateTime.Now,
                    state = BillStates.None,
                };
                if (entity.confirmed)
                    entity.confirmer = _User.Uid;

                var bill = new BillService(entity);
                bill.UpdateInfo(sender, receiver);
                bill.UpdateInfo(insurance, goods, remarks);

                _BillRepository.Add(entity);
                _BillRepository.SaveChanges();

                bill.InitTradeNo();
                _BillRepository.SaveChanges();

                scope.Complete();

                return bill;
            }
        }
Ejemplo n.º 53
0
        public void RecommendAFriend(int referrerId, NewAccount friendsAccountDetails)
        {
            Validate(friendsAccountDetails);

            // most technologies have similar transaction APIs
            using (var transaction = new System.Transactions.TransactionScope())
            {
                try
                {
                    // ... interact with domain multiple times
                    transaction.Complete();
                }
                catch(ReferralRejectedDueToLongTermOutstandingBalance)
                {
                    throw new ApplicationError(
                        "Sorry, this referral cannot be completed. The referrer " +
                        "currently has an outstanding balance. Please contact " +
                        "Customer Services"
                    );
                    // transaction will roll back if Complete() not called
                }
            }
        }
        /// <summary>
        /// Change encryption private key
        /// </summary>
        /// <param name="newEncryptionPrivateKey">New encryption private key</param>
        public static void ChangeEncryptionPrivateKey(string newEncryptionPrivateKey)
        {
            if (String.IsNullOrEmpty(newEncryptionPrivateKey) || newEncryptionPrivateKey.Length != 16)
                throw new NopException("Encryption private key must be 16 characters long");

            string oldEncryptionPrivateKey = IoC.Resolve<ISettingManager>().GetSettingValue("Security.EncryptionPrivateKey");

            if (oldEncryptionPrivateKey == newEncryptionPrivateKey)
                return;

            var orders = IoC.Resolve<IOrderService>().LoadAllOrders();
            //uncomment this line to support transactions
            using (var scope = new System.Transactions.TransactionScope())
            {
                foreach (var order in orders)
                {
                    string decryptedCardType = Decrypt(order.CardType, oldEncryptionPrivateKey);
                    string decryptedCardName = Decrypt(order.CardName, oldEncryptionPrivateKey);
                    string decryptedCardNumber = Decrypt(order.CardNumber, oldEncryptionPrivateKey);
                    string decryptedMaskedCreditCardNumber = Decrypt(order.MaskedCreditCardNumber, oldEncryptionPrivateKey);
                    string decryptedCardCvv2 = Decrypt(order.CardCvv2, oldEncryptionPrivateKey);
                    string decryptedCardExpirationMonth = Decrypt(order.CardExpirationMonth, oldEncryptionPrivateKey);
                    string decryptedCardExpirationYear = Decrypt(order.CardExpirationYear, oldEncryptionPrivateKey);

                    string encryptedCardType = Encrypt(decryptedCardType, newEncryptionPrivateKey);
                    string encryptedCardName = Encrypt(decryptedCardName, newEncryptionPrivateKey);
                    string encryptedCardNumber = Encrypt(decryptedCardNumber, newEncryptionPrivateKey);
                    string encryptedMaskedCreditCardNumber = Encrypt(decryptedMaskedCreditCardNumber, newEncryptionPrivateKey);
                    string encryptedCardCvv2 = Encrypt(decryptedCardCvv2, newEncryptionPrivateKey);
                    string encryptedCardExpirationMonth = Encrypt(decryptedCardExpirationMonth, newEncryptionPrivateKey);
                    string encryptedCardExpirationYear = Encrypt(decryptedCardExpirationYear, newEncryptionPrivateKey);

                    order.CardType = encryptedCardType;
                    order.CardName = encryptedCardName;
                    order.CardNumber = encryptedCardNumber;
                    order.MaskedCreditCardNumber = encryptedMaskedCreditCardNumber;
                    order.CardCvv2 = encryptedCardCvv2;
                    order.CardExpirationMonth = encryptedCardExpirationMonth;
                    order.CardExpirationYear = encryptedCardExpirationYear;
                    IoC.Resolve<IOrderService>().UpdateOrder(order);
                }

                IoC.Resolve<ISettingManager>().SetParam("Security.EncryptionPrivateKey", newEncryptionPrivateKey);

                //uncomment this line to support transactions
                scope.Complete();
            }
        }
Ejemplo n.º 55
0
      public static void RunScheduledTasks()
      {
          
            var transactionOptions = new System.Transactions.TransactionOptions();
            transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
          
            using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions))
            {
                using (DashboardEntities ef = new DashboardEntities())
                {

                    IList<string> listConfig = GetDashboardLogConfigs(ef);
                    foreach (string config in listConfig)
                    {
                        string dir = config;
                        string ext = "*.*";
                        DataTable dt = GetDataTable();
                        DataTable dtStats = GetStatsDataTable();
                        List<string> listOfSupressedErrors = GetListOfSupressedErrors();
                        foreach (String file in Directory.GetFiles(dir, ext))
                        {

                            if (File.GetLastWriteTime(file) > DateTime.Now.AddDays(-1))
                            {

                                try
                                {
                                    using (var r = new StreamReader(file))
                                    {

                                        FileInfo fi = new FileInfo(file);
                                        _bitsList = file.Split('\\').ToList<string>();
                                        string record = "";


                                        string server = _bitsList[2];
                                        string bitsInstance = _bitsList[4];
                                        foreach (
                                            var source in
                                                ef.tbl_SLA_DashboardLogs.OrderByDescending(a => a.StartTime)
                                                    .Where(a => a.Server == server && a.BITSInstance == bitsInstance))
                                        {
                                            tbl_SLA_DashboardLogs logstemp = source;
                                            maxDateTime = (DateTime)logstemp.StartTime;
                                            break;
                                        }
                                        //  maxDateTime = maxDateTime.AddDays(-2);
                                        maxDateTime = maxDateTime.AddMinutes(-10);

                                        while ((record = r.ReadLine()) != null)
                                        {
                                            try
                                            {
                                                DateTime recDate;
                                                if (record.Length < 19 ||
                                                    !DateTime.TryParse(record.Substring(0, 19), out recDate))
                                                    continue;

                                                DataRow dr = dt.NewRow();
                                                dr["Date"] = Convert.ToDateTime(record.Substring(0, 19));
                                                dr["Level"] =
                                                    record.Substring(24, 6).Trim().ToString(CultureInfo.InvariantCulture);

                                                int idx1 = record.IndexOf("ID=", StringComparison.Ordinal);
                                                if (idx1 < 0)
                                                    continue;

                                                string kc = record.Substring(idx1);
                                                int idx2 = kc.IndexOf(" -", StringComparison.Ordinal);
                                                kc = kc.Substring(3, idx2 - 3);
                                                if (kc != "(null)")
                                                {
                                                    dr["KeyCode"] = kc;
                                                    dr["Message"] = record.Substring(idx1 + idx2);
                                                    if (dr["Level"].ToString() != "INFO")
                                                        dt.Rows.Add(dr);

                                                    if (record.Contains("Beginning executing job") &&
                                                        record.Contains("Execution mode"))
                                                    {
                                                        DataRow drStat = dtStats.NewRow();

                                                        drStat["KeyCode"] = kc;
                                                        drStat["Name"] =
                                                            record.Substring(record.IndexOf("Beginning executing job ",
                                                                StringComparison.Ordinal))
                                                                .Replace("Beginning executing job ", "")
                                                                .Replace("_Job in Execution mode.", "");
                                                        drStat["StartTime"] = dr["Date"];
                                                        try
                                                        {
                                                            if (maxDateTime <= (DateTime)drStat["StartTime"])
                                                                dtStats.Rows.Add(drStat);
                                                        }
                                                        catch
                                                        {
                                                        }
                                                    }

                                                    DataRow foundRow = dtStats.Rows.Find(kc);
                                                    if (foundRow != null)
                                                    {
                                                        foundRow.BeginEdit();
                                                        foundRow["EndTime"] = dr["Date"];
                                                        foundRow["Seconds"] =
                                                            ((DateTime)foundRow["EndTime"] - (DateTime)foundRow["StartTime"])
                                                                .Seconds;
                                                        foundRow["Server"] = _bitsList[2];
                                                        foundRow["BITSInstance"] = _bitsList[4];
                                                        foundRow["Message"] = dr["Message"].ToString().Replace(",", " ;");

                                                        // Todo:  
                                                        if (
                                                            dr["Message"].ToString()
                                                                .Contains("Beginning write to file"))
                                                        {
                                                            String[] data = record.Replace("  ", " ").Split(new char[] { ' ' });
                                                            tbl_SLA_FileChecker filesChecker = new tbl_SLA_FileChecker();

                                                            filesChecker.jobKeyCode = kc;
                                                            filesChecker.FileName = data[9];


                                                            if (Convert.ToDateTime(record.Substring(0, 19)) >= maxDateTime)
                                                                ef.AddTotbl_SLA_FileChecker(filesChecker);

                                                        }

                                                        foundRow.EndEdit();
                                                    }

                                                    else if (foundRow == null)
                                                    {

                                                        if (maxDateTime <= (DateTime)dr["Date"])
                                                        {
                                                            DataRow runRow = dtStats.NewRow();
                                                            runRow["KeyCode"] = kc;
                                                            runRow["BITSInstance"] = _bitsList[4];
                                                            runRow["Message"] = record.Substring(idx1 + idx2);
                                                            runRow["Name"] = record.Substring(
                                                                record.IndexOf("Beginning executing job ",
                                                                    System.StringComparison.Ordinal))
                                                                .Replace("Beginning executing job ", "")
                                                                .Replace("_Job in Execution mode.", "");
                                                            runRow["StartTime"] = dr["Date"];
                                                            dtStats.Rows.Add(runRow);

                                                        }
                                                    }

                                                }
                                                Console.WriteLine("KEycode=" + kc);


                                                String[] data1 = record.Replace("  ", " ").Split(new[] { ' ' });
                                                tbl_SLA_BITSJobRequest reuestRequest = new tbl_SLA_BITSJobRequest();
                                                reuestRequest.RequestTime = Convert.ToDateTime(record.Substring(0, 19));
                                                reuestRequest.JobName = data1[7].Replace("_Job.", "");
                                                reuestRequest.RequestedBy = data1[10].Replace("FOUNTAINHEAD\\", "");
                                                reuestRequest.MachineName = data1[12];
                                                foreach (var s in dtStats.Select("Name Like '%" + reuestRequest.JobName + "%'"))
                                                {
                                                    reuestRequest.KeyCode = s["KeyCode"].ToString();
                                                }

                                                if (Convert.ToDateTime(record.Substring(0, 19)) >= maxDateTime && reuestRequest.JobName.Contains("ADHOC") && reuestRequest.KeyCode != String.Empty)
                                                    ef.AddTotbl_SLA_BITSJobRequest(reuestRequest);

                                            }

                                            catch (Exception ex)
                                            {
                                                Console.Write(ex);
                                            }

                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    ;
                                }

                                foreach (DataRow drStat in dtStats.Rows)
                                {
                                    tbl_SLA_DashboardLogs logs = new tbl_SLA_DashboardLogs();
                                    logs.Server = drStat["Server"].ToString();
                                    logs.BITSInstance = drStat["BITSInstance"].ToString();
                                    logs.KeyCode = drStat["KeyCode"].ToString();
                                    logs.Name = drStat["Name"].ToString().Replace("_Job in Initialization mode.", "");
                                    logs.StartTime = (DateTime?)drStat["StartTime"];
                                    logs.EndTime = (DateTime?)drStat["EndTime"];
                                    TimeSpan diffTime = (TimeSpan)(logs.EndTime - logs.StartTime);
                                    logs.Seconds = (int?)diffTime.TotalMinutes;
                                    logs.Message = drStat["Message"].ToString().Replace("\n", "|").Replace("\t", " ");



                                    // Error handeling 

                                    if (IsError(logs.Message) && listOfSupressedErrors.Contains(logs.Message))
                                        logs.Status = "Error";


                                    else if (drStat["Status"].ToString() == String.Empty)
                                    {

                                        double timeDiff = diffTime.TotalMinutes * 60;

                                        logs.Status = timeDiff > 0 ? "Completed" : "Running";
                                    }
                                    else if (drStat["Status"].ToString() == "Started")
                                    {
                                        logs.Status = "Running";
                                    }


                                    if (logs.StartTime >= maxDateTime)
                                        ef.AddTotbl_SLA_DashboardLogs(logs);


                                }
                                try
                                {
                                    ef.SaveChanges();

                                }
                                catch
                                {
                                    ;
                                }
                                finally {
                                    transactionScope.Complete();
                                }
                            }
                        }


                    }

                }
            }
      }
Ejemplo n.º 56
0
        public void ExportToCsv(List<Gen4Transaction> Gen4ExportTransactions)
        {
            DateTime exportDateTime = DateTime.Now;

            StringBuilder sbExportFile = new StringBuilder();
            sbExportFile.AppendLine("TransactionID,ParentTransactionID,CustomerID,Company,CustomerName,CustomerEmail,CustomerPhone,LeadID,LeadType,Source,Description,TransactionType,IsReported,Action,Created");

            foreach (var gen4ExportTransaction in Gen4ExportTransactions)
            {
                sbExportFile.AppendLine(this.FormatForExportToCSV(gen4ExportTransaction.TransactionID.ToString()) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.ParentTransactionID.ToString()) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.CustomerID.ToString()) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.Company) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.CustomerName) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.CustomerEmail) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.CustomerPhone) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.LeadID.ToString()) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.LeadType) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.Source) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.Description) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.TransactionType) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.IsReported.ToString()) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.Action.ToString()) + "," +
                                        this.FormatForExportToCSV(gen4ExportTransaction.Created.ToString()));
            }

            string exportedFilename = this.GetExportFilename(exportDateTime);

            using (System.Transactions.TransactionScope trans = new System.Transactions.TransactionScope())
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(exportedFilename))
                {
                    sw.WriteLine(sbExportFile);
                }
                
                Gen4LiveEntities gen4Ctx = new Gen4LiveEntities();
                foreach (var gen4ExportTransaction in Gen4ExportTransactions)
                {
                    var gen4Transaction = (from t in gen4Ctx.Gen4PplLedger
                                           where t.TransactionID == gen4ExportTransaction.TransactionID
                                           select t).Single();
                    gen4Transaction.IsReported = true;
                    gen4Transaction.ReportStatus = "Exported to CSV on " + exportDateTime.ToString();
                    gen4Transaction.LastModified = DateTime.Now;
                    gen4Ctx.SaveChanges();
                }

                trans.Complete();
            }            
        }
Ejemplo n.º 57
0
        /// <summary>
        /// Add users and roles inside a transaction in case there's an exception, 
        /// we can simply click the "Install" button again.
        /// </summary>
        /// <param name="config"></param>
        private static void AddUsers(InstallerConfig config)
        {
            if (config.Membership.Create)
            {
                using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
                {
                    // Now create the roles
                    foreach (var role in config.RoleManager.Roles)
                    {
                        if (!Roles.RoleExists(role.Name))
                            Roles.CreateRole(role.Name);
                        //throw new Exception("Error adding user - by King.");

                        // Now create user and add to role.
                        foreach (var user in role.Users)
                        {
                            MembershipCreateStatus status = MembershipCreateStatus.UserRejected;
                            MembershipUser u = System.Web.Security.Membership.CreateUser(user.UserName.Trim(), user.Password.Trim(), user.Email.Trim(),
                                user.SecretQuestion.Trim(), user.SecretAnswer.Trim(), true, out status);

                            if (status == MembershipCreateStatus.Success)
                            {
                                // Add user to role
                                Roles.AddUserToRole(user.UserName, role.Name);
                            }
                            else if (status == MembershipCreateStatus.DuplicateUserName)
                            {
                                // Add a duplicate username to another role.
                                // This allows the same user to be added to any number of roles.
                                try
                                {
                                    Roles.AddUserToRole(user.UserName, role.Name);
                                }
                                catch (Exception)
                                {
                                }
                            }
                            else if (status == MembershipCreateStatus.InvalidPassword)
                            {
                                throw new ApplicationException("Please update the install.config file.  The passwords don't adhere to the rules in the web.config/membership section.");
                            }
                        }
                    }
                    scope.Complete();
                }
            }
        }
Ejemplo n.º 58
0
 public int Update(int RouteId, int PortalId, int ContentItemId, string CultureCode, string RouteName, string RouteUrl, string PhysicalFile,
 bool CheckPhysicalUrlAccess, string RouteValueDictionary, string Description, bool Discontinued)
 {
     int i = 0;
     using (CommonEntities dbContext = new CommonEntities())
     {
         using (System.Transactions.TransactionScope transcope = new System.Transactions.TransactionScope())
         {
             dbContext.Connection.Open();
             aspnet_Routes entity = dbContext.aspnet_Routes.Single(x => x.RouteId == RouteId);
             entity.PortalId = PortalId;
             entity.ContentItemId = ContentItemId;
             entity.CultureCode = CultureCode;
             entity.RouteName = RouteName;
             entity.RouteUrl = RouteUrl;
             entity.PhysicalFile = PhysicalFile;
             entity.CheckPhysicalUrlAccess = CheckPhysicalUrlAccess;
             entity.RouteValueDictionary = RouteValueDictionary;
             entity.Description = Description;
             entity.Discontinued = Discontinued;
             i = dbContext.SaveChanges();
             dbContext.Connection.Close();
             transcope.Complete();
         }
     }
     return i;
 }
Ejemplo n.º 59
0
 public static void Delete(int RouteId)
 {
     using (CommonEntities dbContext = new CommonEntities())
     {
         using (System.Transactions.TransactionScope transcope = new System.Transactions.TransactionScope())
         {
             dbContext.Connection.Open();
             aspnet_Routes entity = dbContext.aspnet_Routes.Single(x => x.RouteId == RouteId);
             dbContext.aspnet_Routes.DeleteObject(entity);
             dbContext.SaveChanges();
             dbContext.Connection.Close();
             transcope.Complete();
         }
     }
 }
        public void Save(Employee employee)
        {
            using (var transactionScope = new TransactionScope())
            {
                if (employee.IsNew)
                {
                    Add(employee);
                }
                else
                {
                    Update(employee);
                }

                foreach (var address in employee.Addresses)
                {
                    address.EmployeeId = employee.Id;
                    if (address.IsNew)
                    {
                        Add(address);
                    }
                    else
                    {
                        Update(address);
                    }
                }
                foreach (var roleId in employee.Roles.Select(x=>x.Id).Distinct())
                {
                    Add(employee.Id, roleId);
                }
                transactionScope.Complete();
            }
        }