예제 #1
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("验证邮箱不存在,请重新填写!");
     }
 }
예제 #2
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);
            }
        }
예제 #3
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();
            }
        }
        public virtual ActionResult RemoveFromCart(int id)
        {
            using (var scope = new System.Transactions.TransactionScope())
            {
                // Remove the item from the cart
                var cart = ShoppingCart.GetCart(this.HttpContext);

                // Get the name of the album to display confirmation
                string albumName = storeDB.Carts
                    .Single(item => item.RecordId == id).Album.Title;

                // Remove from cart
                int itemCount = cart.RemoveFromCart(id);

                scope.Complete();

                // Display the confirmation message
                var results = new ShoppingCartRemoveViewModel
                                  {
                                      Message = Server.HtmlEncode(albumName) +
                                                " has been removed from your shopping cart.",
                                      CartTotal = cart.GetTotal(),
                                      CartCount = cart.GetCount(),
                                      ItemCount = itemCount,
                                      DeleteId = id
                                  };

                return Json(results);
            }
        }
예제 #5
0
        /// <summary>
        /// 添加操作记录
        /// </summary>
        /// <param name="user">当前操作用户</param>
        /// <param name="log">记录实体</param>
        /// <param name="details">记录明细列表</param>
        /// <returns></returns>
        public static ResultModel InsertOperateLog(UserModel user, OperateLogModel log, List<OperateLogDetailModel> details)
        {
            ResultModel result = new ResultModel();

            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                result = InsertOperateLog(user, log);
                if (result.ResultStatus != 0)
                    return result;

                foreach (OperateLogDetailModel m in details)
                {
                    result = InsertOperateLogDetail(user, m);
                    if (result.ResultStatus != 0)
                        return result;
                }

                scope.Complete();

                result.AffectCount = 1;
                result.Message = string.Format("操作记录添加成功,明细共{0}条", details.Count);
                result.ResultStatus = 0;
                result.ReturnValue = 1;
            }

            return result;
        }
예제 #6
0
        public void Assignment_SelectAddSelectDeleteSelect_OK()
        {
            using (System.Transactions.TransactionScope updateTransaction =
             new System.Transactions.TransactionScope())
            {
                string connectionString = GetConnectionstring();
                DataAccess d2 = new DataAccess(connectionString);

                List<Assignment> assignmentsBefore = d2.GetAssignments();

                Assignment assignment = new Assignment();
                assignment.AssignmentId = -1;
                assignment.AssignmentName = "asfdasfasdfsaf";

                Assignment assignmentAfterSave = d2.SaveAssignment(assignment);

                Assignment assignmentGetById = d2.GetAssignmentByID(assignment.AssignmentId);

                Assert.AreNotEqual(assignment.AssignmentId, -1);
                Assert.AreEqual(assignment.AssignmentName, assignmentGetById.AssignmentName);

                List<Assignment> assignmentsAfterSave = d2.GetAssignments();

                Assert.AreEqual(assignmentsAfterSave.Count, assignmentsBefore.Count + 1);

                d2.DeleteAssignment(assignment.AssignmentId);

                List<Assignment> assignmentsAfterDelete = d2.GetAssignments();

                Assert.AreEqual(assignmentsBefore.Count, assignmentsAfterDelete.Count);

            }
        }
예제 #7
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;
            }
        }
예제 #8
0
파일: MainForm.cs 프로젝트: wctang/gxxf
        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("刪除成功");
        }
        public void CheckCustomerLoginPasswordTest()
        {
            //connections variables and dataset
            SqlConnection conn = new SqlConnection(connection_string);
            List<string> errors = new List<string>();
            using (var scop = new System.Transactions.TransactionScope())
            {
                //test parameters
                Customer customer = new Customer();
                customer.customer_name = "checkpw test";
                customer.customer_pw = "test123";
                customer.customer_type = "test";
                customer.first_name = "test";
                customer.middle_name = "test";
                customer.last_name = "test";
                customer.customer_id = DALCustomers.CreateCustomer(customer, ref errors);

                Customer check = DALCustomers.CheckCustomerLoginPassword(customer.customer_name, customer.customer_pw, ref errors);
                Assert.AreEqual(0, errors.Count);
                Assert.IsNotNull(check);
                Assert.AreEqual(check.customer_id, customer.customer_id);
                Assert.AreEqual(customer.customer_name, check.customer_name);
                Assert.AreEqual(customer.customer_pw, check.customer_pw);
                Assert.AreEqual(customer.customer_type, check.customer_type);
                Assert.AreEqual(customer.first_name, check.first_name);
                Assert.AreEqual(customer.middle_name, check.middle_name);
                Assert.AreEqual(customer.last_name, check.last_name);
            }
        }
 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;
 }
 ////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;
 }
예제 #12
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);
                }
            }
        }
예제 #13
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();
            }
        }
예제 #14
0
        public void Add(long adminUid, long operatorUid)
        {
            //判断重复
            ExceptionHelper.ThrowIfNotId(adminUid, "adminUid");
            ExceptionHelper.ThrowIfNotId(operatorUid, "operatorUid");
            var admin = _Repository.Entities.FirstOrDefault(d => d.uid == adminUid);
            if(admin==null || !admin.enabled)
            {
                using (var scope = new System.Transactions.TransactionScope())
                {
                    if (admin == null)
                    {
                        var entity = Data.Admin.CreateNewInstance(adminUid);
                        entity.enabled = true;
                        entity.created = DateTime.Now;
                        _Repository.Add(entity);

                    }
                    else if (!admin.enabled)
                    {
                        admin.enabled = true;
                        admin.created = DateTime.Now;
                    }
                    _Repository.SaveChanges();
                    _AdminModifyHistoryManager.Add(new Data.AdminModifyHistory { opContent = "新增管理员", adminUid = adminUid, operatorUid = operatorUid });
                    scope.Complete();
                }
            }
        }
예제 #15
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));
        }
        public void CreateAdminTest()
        {
            //connections variables and dataset
            List<string> errors = new List<string>();
            using (var scop = new System.Transactions.TransactionScope())
            {
                //test parameters
                AdminLogin adminLogin = new AdminLogin();
                adminLogin.admin_name = "create admin test";
                adminLogin.admin_password  = "******"; // TODO: Initialize to an appropriate value
                adminLogin.first_name  = "test"; // TODO: Initialize to an appropriate value
                adminLogin.middle_name  = "test"; // TODO: Initialize to an appropriate value
                adminLogin.last_name  = "test"; // TODO: Initialize to an appropriate value
                adminLogin.admin_id = DALAdminLogins.CreateAdmin(adminLogin, ref errors);
                AdminLogin check = DALAdminLogins.GetAdminInfo(adminLogin.admin_id, ref errors);

                //assert test result to be equal to newrly created data
                Assert.AreEqual(0, errors.Count);
                Assert.IsNotNull(check);
                Assert.AreEqual(adminLogin.admin_id, check.admin_id);
                Assert.AreEqual(adminLogin.admin_name,check.admin_name);
                Assert.AreEqual(adminLogin.admin_password, check.admin_password);
                Assert.AreEqual(adminLogin.first_name, check.first_name);
                Assert.AreEqual(adminLogin.middle_name, check.middle_name);
                Assert.AreEqual(adminLogin.last_name, check.last_name);
            }
        }
        public void CheckAdminLoginPasswordTest()
        {
            //connections variables and dataset
            SqlConnection conn = new SqlConnection(connection_string);
            List<string> errors = new List<string>();
            using (var scope = new System.Transactions.TransactionScope())
            {
                AdminLogin adminLogin = new AdminLogin();
                adminLogin.admin_name = "create admin test";
                adminLogin.admin_password = "******"; // TODO: Initialize to an appropriate value
                adminLogin.first_name = "test"; // TODO: Initialize to an appropriate value
                adminLogin.middle_name = "test"; // TODO: Initialize to an appropriate value
                adminLogin.last_name = "test"; // TODO: Initialize to an appropriate value
                adminLogin.admin_id = DALAdminLogins.CreateAdmin(adminLogin, ref errors);

                AdminLogin check = DALAdminLogins.CheckAdminLoginPassword(adminLogin.admin_name, adminLogin.admin_password, ref errors);
                Assert.AreEqual(0, errors.Count);
                Assert.IsNotNull(check);
                Assert.AreEqual(adminLogin.admin_id, check.admin_id);
                Assert.AreEqual(adminLogin.admin_name, check.admin_name);
                Assert.AreEqual(adminLogin.admin_password, check.admin_password);
                Assert.AreEqual(adminLogin.first_name, check.first_name);
                Assert.AreEqual(adminLogin.middle_name, check.middle_name);
                Assert.AreEqual(adminLogin.last_name, check.last_name);
            }
        }
예제 #18
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;
         }                
     }
 }
예제 #19
0
 public void GuardarCuConfigurarIgv(string valor)
 {
     using (var transaction = new System.Transactions.TransactionScope())
     {
         dominio.ActualizarValorConfigByCodigo("01",valor);
         transaction.Complete();
     }
 }
예제 #20
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();
        }
예제 #21
0
		/// <summary>
		/// Create a transaction scope of specified TransactionScope
		/// Sets the isolation level to ReadCommitted
		/// </summary>
		/// <returns></returns>
		public static System.Transactions.TransactionScope CreateTransactionScope(System.Transactions.TransactionScopeOption tranScopeOption)
		{

			System.Transactions.TransactionOptions tranOption = new System.Transactions.TransactionOptions();
			tranOption.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;

			System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(tranScopeOption, tranOption);
			//Console.WriteLine(string.Format("Transaction Id={0}, DistId={1}", System.Transactions.Transaction.Current.TransactionInformation.LocalIdentifier, System.Transactions.Transaction.Current.TransactionInformation.DistributedIdentifier));
			return scope;
		}
 internal LinqTransactionContext()
 {
   if (System.Transactions.Transaction.Current == null)
   {
     _systemTransactionScope = new System.Transactions.TransactionScope();
   }
   else
   {
     _systemTransactionScope = null;
   }
 }
        protected long AcquireNextRange()
        {
#if MONO
            return AcquireNextRangeInternal();
#else
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Suppress))
            {
                return AcquireNextRangeInternal();
            }
#endif
        }
예제 #24
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();
     }
 }
예제 #25
0
 /// <summary>
 /// 查看用户
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public DTO.PSUserView UserView(DTO.PQUserView request)
 {
     DTO.PSUserView response = new DTO.PSUserView();
     try
     {
         using (var scope = new System.Transactions.TransactionScope())
         {
             Models.tbUser u = new Models.tbUser();
             //修改
             if (request.UserID > 0)
             {
                 u = con.tbUser.Find(request.UserID);
                 response.UserID        = u.UserID;
                 response.UserAccount   = u.UserAccount;
                 response.UserName      = u.UserName;
                 response.StartDate     = u.StartDate.ToString("yyyy-MM-dd");
                 response.EndDate       = u.EndDate.ToString("yyyy-MM-dd");
                 response.LastLoginTime = u.LastLoginTime == null ? "" : ((DateTime)u.LastLoginTime).ToString("yyyy-MM-dd HH:mm:ss");
                 response.CreateTime    = u.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                 response.UpdateTime    = u.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss");
                 response.OrgID         = (int)u.OrgID;
                 Models.tbOrg o = con.tbOrg.Find(response.OrgID);
                 response.FullPath = o.FullPath;
                 response.RoleID   = (int)u.RoleID;
                 Models.tbRole r = con.tbRole.Find(response.RoleID);
                 response.RoleName   = r.RoleName;
                 response.CellPhone  = u.CellPhone;
                 response.Email      = u.Email;
                 response.WorkNumber = u.WorkNumber;
             }
             List <Models.tbOrg> orgs = con.tbOrg.OrderBy(p => p.RealPath).ToList();
             foreach (Models.tbOrg org in orgs)
             {
                 response.OrgList.Add(new KeyValuePair <int, string>(org.OrgID, org.FullPath));
             }
             List <Models.tbRole> roles = con.tbRole.Where(p => p.RoleType == "1").OrderBy(p => p.RoleID).ToList();
             foreach (Models.tbRole role in roles)
             {
                 response.RoleList.Add(new KeyValuePair <int, string>(role.RoleID, role.RoleName));
             }
             response.ErrorCode = "A_0";
         }
     }
     catch (Exception ex)
     {
         LogHelper.Error("cUserBLL.UserView出错!", ex);
         throw;
     }
     response.ErrorMessage = rm.GetString(response.ErrorCode);
     return(response);
 }
예제 #26
0
        public bool ModificarUsuario()
        {
            bool r = true;

            using (System.Transactions.TransactionScope tr = new System.Transactions.TransactionScope())
            {
                foreach (PermisoClass p in _permisos)
                {
                    if (!p.Modificar())
                    {
                        r = false;
                        break;
                    }
                }

                if (r)
                {
                    //Modifico el usuario
                    var cur = from u in ctx.usuarios
                              where u.id_usuario == _id_usuario
                              select u;

                    var f = cur.First();
                    f.contrasenia     = this._constrasenia;
                    f.nombre_completo = this._nombre_completo;

                    //f.nombre_usuario = this._nombre_usuario;

                    try
                    {
                        ctx.SaveChanges();
                        r = true;
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "Error al modificar el usuario", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        r = false;
                    }
                }


                if (r)
                {
                    tr.Complete();
                }
            }



            return(r);
        }
예제 #27
0
        private void init()
        {
            lock (dictMarketHolidays)
            {
                lock (dictMarketLastReferenceTime)
                {
                    if (dictMarketLastReferenceTime.ContainsKey(Market) &&
                        dictMarketHolidays.ContainsKey(Market) &&
                        DateTime.UtcNow.Subtract(dictMarketLastReferenceTime[Market]).TotalMinutes < 15)
                    {
                        holidays = dictMarketHolidays[Market];
                        return;
                    }
                    try
                    {
                        using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Suppress))
                        {
                            holidays = Common.GyomuDataAccess.ListHoliday(Market);

                            if (dictMarketHolidays.ContainsKey(Market) == false)
                            {
                                dictMarketHolidays.Add(Market, holidays);
                            }
                            else
                            {
                                dictMarketHolidays[Market] = holidays;
                            }
                            if (dictMarketLastReferenceTime.ContainsKey(Market) == false)
                            {
                                dictMarketLastReferenceTime.Add(Market, DateTime.UtcNow);
                            }
                            else
                            {
                                dictMarketLastReferenceTime[Market] = DateTime.UtcNow;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (dictMarketHolidays.ContainsKey(Market))
                        {
                            holidays = dictMarketHolidays[Market];
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }
            }
        }
예제 #28
0
 public long AddNewSingleOrder(Guid callbackID, string username, Dictionary <string, object> data, Dictionary <string, object> details)
 {
     try
     {
         using (CmdOnPoolGenerator gen = new CmdOnPoolGenerator(ConStrongKeys.FixDbCon))
         {
             DbCommand cmdOrder = gen.CreateCommand(new CustomizedCommand()
             {
                 ColumnsData = data, FilteredColumnsData = null, CommandType = CustomizedCommandType.New, ConnectionString = SystemConfigurations.GetConnectionString(ConStrongKeys.FixDbCon), DataProvider = DataProvider.SqlServer, TableName = "Orders"
             }, true);
             using (System.Transactions.TransactionScope tran = new System.Transactions.TransactionScope())
             {
                 long orderID = Convert.ToInt64(gen.DatabaseInstance.ExecuteScalar(cmdOrder));
                 details.Add(SingleOrdDetailsProps.OrderID, orderID);
                 DbCommand cmdOrdersDetail = gen.CreateCommand(new CustomizedCommand()
                 {
                     ColumnsData = details, FilteredColumnsData = null, CommandType = CustomizedCommandType.New, ConnectionString = SystemConfigurations.GetConnectionString(ConStrongKeys.FixDbCon), DataProvider = DataProvider.SqlServer, TableName = "Orders_Details"
                 }, false);
                 gen.DatabaseInstance.ExecuteNonQuery(cmdOrdersDetail);
                 DbCommand   cmdSub = gen.DatabaseInstance.GetSqlStringCommand(string.Format("INSERT INTO [SessionOrders] (SessionID,Username, ReqOrdID, OrdID, SubscriptionDateTime) Values (@SubscriberID, @username,@RequesterOrderID, @OrderID, @SubscriptionDateTime)"));
                 DbParameter para1  = cmdSub.CreateParameter();
                 para1.ParameterName = "@SubscriberID";
                 para1.Value         = callbackID;
                 cmdSub.Parameters.Add(para1);
                 DbParameter para2 = cmdSub.CreateParameter();
                 para2.ParameterName = "@RequesterOrderID";
                 para2.Value         = (Guid)data[SingleOrderProperties.RequesterOrderID];
                 cmdSub.Parameters.Add(para2);
                 DbParameter para3 = cmdSub.CreateParameter();
                 para3.ParameterName = "@OrderID";
                 para3.Value         = orderID;
                 cmdSub.Parameters.Add(para3);
                 DbParameter para4 = cmdSub.CreateParameter();
                 para4.ParameterName = "@SubscriptionDateTime";
                 para4.Value         = data[SingleOrderProperties.PlacementDateTime];
                 cmdSub.Parameters.Add(para4);
                 DbParameter para5 = cmdSub.CreateParameter();
                 para5.ParameterName = "@Username";
                 para5.Value         = username;
                 cmdSub.Parameters.Add(para5);
                 gen.DatabaseInstance.ExecuteNonQuery(cmdSub);
                 tran.Complete();
                 return(orderID);
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public ActionResult BulkDeleteSubmissions([DataSourceRequest] DataSourceRequest request)
        {
            request.PageSize = 0;

            var submissionsDataSourceResult = this.GetData().ToDataSourceResult(request);
            var submissions = submissionsDataSourceResult.Data;

            using (var scope = new TransactionScope())
            {
                foreach (GridModelType submission in submissions)
                {
                    this.Data.Submissions.Delete(submission.Id);
                    this.submissionsForProcessingData.RemoveBySubmissionId(submission.Id);
                }

                this.Data.SaveChanges();

                foreach (GridModelType submission in submissions)
                {
                    var dbSubmission = this.Data.Submissions.GetById(submission.Id);

                    if (!dbSubmission.ParticipantId.HasValue)
                    {
                        this.TempData[GlobalConstants.DangerMessage] = "Потребителя не съществува!";
                        return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = "Administration" }));
                    }

                    var submissionProblemId     = dbSubmission.ProblemId.Value;
                    var submissionParticipantId = dbSubmission.ParticipantId.Value;

                    var isBestSubmission = this.IsBestSubmission(
                        submissionProblemId,
                        submissionParticipantId,
                        dbSubmission.Id);

                    if (isBestSubmission)
                    {
                        this.participantScoresBusiness.RecalculateForParticipantByProblem(
                            dbSubmission.ParticipantId.Value,
                            dbSubmission.ProblemId.Value);
                    }
                }

                this.Data.SaveChanges();

                scope.Complete();
            }

            this.TempData[GlobalConstants.InfoMessage] = $"Успешно изтрихте {submissionsDataSourceResult.Total} решения.";
            return(this.RedirectToAction <SubmissionsController>(c => c.Index()));
        }
예제 #30
0
        private static void CreateBenelux()
        {
            using (var trs = new System.Transactions.TransactionScope())
            {
                CreateCountryParameters param = new CreateCountryParameters()
                {
                    CountryName       = "Benelux",
                    CurrencyName      = "Euro",
                    CurrencyShortName = "EUR",
                    CurrencySymbol    = "€",
                    CurrencyID        = 4
                };

                if (countryExists(param))
                {
                    return;
                }

                var country = countryService.CreateCountry(param);

                var luxemburg = regionService.CreateRegion(new CreateRegionParameters()
                {
                    CanSpawn  = true,
                    CountryID = country.ID,
                    Name      = "Luxemburg"
                });

                var belgium = regionService.CreateRegion(new CreateRegionParameters()
                {
                    CanSpawn  = true,
                    CountryID = country.ID,
                    Name      = "Belgium"
                });

                var netherlands = regionService.CreateRegion(new CreateRegionParameters()
                {
                    CanSpawn  = true,
                    CountryID = country.ID,
                    Name      = "Netherlands"
                });

                regionService.ConnectRegions(luxemburg, belgium, 170);
                regionService.ConnectRegions(belgium, netherlands, 140);
                regionService.ConnectRegions(luxemburg, regionRepository.GetRegion("Western Germany"), 110);
                regionService.ConnectRegions(belgium, regionRepository.GetRegion("Western Germany"), 240);
                regionService.ConnectRegions(netherlands, regionRepository.GetRegion("Western Germany"), 300);
                regionService.ConnectRegions(netherlands, regionRepository.GetRegion("Lower Saxony"), 200);

                trs.Complete();
            }
        }
예제 #31
0
파일: DbUtil.cs 프로젝트: wooln/AK47Source
        internal static void ReOrder(string objectId, string parentId, bool down, bool toEdge)
        {
            var adapter   = PC.Adapters.SchemaRelationObjectAdapter.Instance;
            var relations = adapter.LoadByParentID(parentId);

            relations.Sort((m, n) => m.InnerSort.CompareTo(n.InnerSort));
            var subset = relations.FindAll(m => (m.ParentSchemaType == "Organizations" && m.Status == SchemaObjectStatus.Normal));
            int index  = -1;
            int count  = subset.Count;

            for (int i = count - 1; i >= 0; i--)
            {
                if (subset[i].Child.ID == objectId)
                {
                    index = i;
                    break;
                }
            }

            if (index >= 0)
            {
                var item = subset[index];
                if (down)
                {
                    if (index < subset.Count - 1)
                    {
                        subset.RemoveAt(index);
                        subset.Insert(toEdge ? subset.Count : (index + 1), item);
                    }
                }
                else
                {
                    if (index > 0)
                    {
                        subset.RemoveAt(index);
                        subset.Insert(toEdge ? 0 : index - 1, item);
                    }
                }

                using (System.Transactions.TransactionScope scope = TransactionScopeFactory.Create())
                {
                    for (int i = 0; i < count; i++)
                    {
                        subset[i].InnerSort = i;
                        adapter.Update(subset[i]);
                    }

                    scope.Complete();
                }
            }
        }
예제 #32
0
        public ActionResult BodyAdd(FormCollection collection)
        {
            BizProcess.Platform.Organize   borganize = new BizProcess.Platform.Organize();
            BizProcess.Data.Model.Organize org       = null;
            string id     = Request.QueryString["id"];
            string name   = string.Empty;
            string type   = string.Empty;
            string status = string.Empty;
            string note   = string.Empty;

            Guid orgID;

            if (id.IsGuid(out orgID))
            {
                org = borganize.Get(orgID);
            }

            if (collection != null && org != null)
            {
                name   = Request.Form["Name"];
                type   = Request.Form["Type"];
                status = Request.Form["Status"];
                note   = Request.Form["note"];

                BizProcess.Data.Model.Organize org1 = new BizProcess.Data.Model.Organize();
                Guid org1ID = Guid.NewGuid();
                org1.ID       = org1ID;
                org1.Name     = name.Trim();
                org1.Note     = note.IsNullOrEmpty() ? null : note.Trim();
                org1.Number   = org.Number + "," + org1ID.ToString().ToLower();
                org1.ParentID = org.ID;
                org1.Sort     = borganize.GetMaxSort(org.ID);
                org1.Status   = status.IsInt() ? status.ToInt() : 0;
                org1.Type     = type.ToInt();
                org1.Depth    = org.Depth + 1;

                using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
                {
                    borganize.Add(org1);
                    //更新父级[ChildsLength]字段
                    borganize.UpdateChildsLength(org.ID);
                    scope.Complete();
                }

                BizProcess.Platform.Log.Add("添加了组织机构", org1.Serialize(), BizProcess.Platform.Log.Types.组织机构);
                ViewBag.Script = "alert('添加成功!');parent.frames[0].reLoad('" + id + "');window.location=window.location;";
            }
            ViewBag.TypeRadios   = borganize.GetTypeRadio("Type", type, "validate=\"radio\"");
            ViewBag.StatusRadios = borganize.GetStatusRadio("Status", "0", "validate=\"radio\"");
            return(View());
        }
예제 #33
0
        ///// <summary>
        ///// 增加
        /////
        ///// </summary>
        ///// <param name="model">设备接口对象</param>
        ///// <returns>返回处理结果</returns>
        //public CommonResult<QC_FindLeakDrumsSet> AddQCDrumsSet(QC_FindLeakDrumsSet model)
        //{
        //    var result = new CommonResult<QC_FindLeakDrumsSet>();
        //    try
        //    {
        //        //   CheckDeviceExecute(model, result);
        //        var dbSession = new DBService<QC_FindLeakDrumsSet>().DbSession;

        //        if (dbSession.GetQueryable(t => t.AutoId == model.AutoId).FirstOrDefault() != null)
        //        {
        //            result.IsSuccess = false;
        //            result.Message = "漏检单号不能重复!";
        //        }
        //        else
        //        {
        //            result.Data = dbSession.Insert(model);
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        result.IsSuccess = false;
        //        result.Message = ex.Message;
        //        result.StackTrace = ex.StackTrace;
        //    }
        //    return result;
        //}


        /// <summary>
        ///
        /// 设定转漏转鼓保存
        /// </summary>
        /// <param name="model">设备接口对象</param>
        /// <returns>返回处理结果</returns>
        public CommonResult <bool> AddQCDrumsSet(QC_FindLeakDrumsSet model, List <QC_FindLeakDrumsSetDetail> detailList)
        {
            var result = new CommonResult <bool>();

            try
            {
                //   CheckDeviceExecute(model, result);
                var dbSession  = new DBService <QC_FindLeakDrumsSet>().DbSession;
                var dbSession1 = new DBService <QC_FindLeakDrumsSetDetail>().DbSession;
                //start 不为空判断

                //end

                if (result.IsSuccess)
                {
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                    {
                        var currModel = dbSession.Insert(model);
                        detailList.ForEach(item =>
                        {
                            item.ID = currModel.ID;
                        });
                        dbSession1.Insert(detailList);

                        //更新工艺执行表进入检漏状态,开启检漏工艺
                        foreach (var item in detailList)
                        {
                            item.AutoID = currModel.ID;
                            //排配单操作日志
                            ForCfPExecuteServices.GetInstance(currUserSession.SessionId).InsertArrangedVouchLog(new ArrangedVouchLog()
                            {
                                ArrangedVouchCode = item.ArrangedVouchCode,
                                CraftsName        = "检漏",
                                OperatDesc        = "检漏开始",
                                Operator          = currUserSession.UserName,
                                OperatingTime     = DateTime.Now,
                                Frequency         = model.Frequency
                            });
                        }
                        ts.Complete();
                        result.Data = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.Logger.Error(ex.ToString());
                throw ex;
            }
            return(result);
        }
예제 #34
0
 /// <summary>
 /// 修改当前用户密码
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public DTO.PSPasswordModify PasswordModify(DTO.PQPasswordModify request)
 {
     DTO.PSPasswordModify response = new DTO.PSPasswordModify();
     try
     {
         using (var scope = new System.Transactions.TransactionScope())
         {
             if (request.NewPass2 != request.NewPass1)
             {
                 response.ErrorCode    = "A_TWO_NEW_NOT_PAIR";
                 response.ErrorMessage = rm.GetString(response.ErrorCode);
                 return(response);
             }
             Models.tbUser obj = con.tbUser.Find(request.UID);
             if (obj == null)
             {
                 response.ErrorCode    = "A_PARAM_ERROR";
                 response.ErrorMessage = rm.GetString(response.ErrorCode);
                 return(response);
             }
             //根据老密码生成密文
             SHA1          sha   = SHA1.Create();
             ASCIIEncoding enc   = new ASCIIEncoding();
             byte[]        oData = enc.GetBytes(request.OldPass + obj.Salt);
             byte[]        dData = sha.ComputeHash(oData);
             string        pass  = BitConverter.ToString(dData).Replace("-", "");
             if (obj.UserPass.Trim() != pass)
             {
                 response.ErrorCode    = "A_OLD_PASS_NOT_RIGHT";
                 response.ErrorMessage = rm.GetString(response.ErrorCode);
                 return(response);
             }
             //根据新密码生成密文
             byte[] oData1 = enc.GetBytes(request.NewPass1 + obj.Salt);
             byte[] dData1 = sha.ComputeHash(oData1);
             string pass1  = BitConverter.ToString(dData1).Replace("-", "");
             obj.UserPass = pass1;
             con.SaveChanges();
             scope.Complete();
             response.ErrorCode = "A_0";
         }
     }
     catch (Exception ex)
     {
         LogHelper.Error("cUserBLL.PasswordModify出错!", ex);
         throw;
     }
     response.ErrorMessage = rm.GetString(response.ErrorCode);
     return(response);
 }
        private void DisposeInnerScope()
        {
            if (_innerScope != null)
            {
                var scopeToDispose = _innerScope;
                _innerScope = null;

                // De-register this scope as the primary transaction so others can be created
                _transactionScopeManager?.DeregisterTransaction(this);

                // Dispose of the EF transaction which should tidy itself up.
                scopeToDispose.Dispose();
            }
        }
예제 #36
0
        // Constructors
        public DistributedTransactionScopeProvider(System.Transactions.TransactionScope transactionScope)
        {
            #region Contracts

            if (transactionScope == null)
            {
                throw new ArgumentNullException();
            }

            #endregion

            // Arguments
            _transactionScope = transactionScope;
        }
예제 #37
0
        /// <summary>
        /// Deshabilita todos los periodos asociados a una asignación de actividad
        /// </summary>
        /// <param name="idAsignacionActividad">Id de </param>
        /// <param name="id_usuario">Id de usuario</param>
        /// <returns></returns>
        public static RetornoOperacion DeshabilitaPeriodosAsignacionActividad(int idAsignacionActividad, int id_usuario)
        {
            //Declarando variable de retorno
            RetornoOperacion resultado = new RetornoOperacion(1);

            //Creamos la transacción
            using (System.Transactions.TransactionScope scope = Transaccion.InicializaBloqueTransaccional(System.Transactions.IsolationLevel.ReadCommitted))
            {
                //Cargando los periodos ligados a la asignación
                using (DataTable mit = AsignacionPeriodo.CargaPeriodosAsignacionActividad(idAsignacionActividad))
                {
                    //Validando que el origen de datos exista
                    if (Validacion.ValidaOrigenDatos(mit))
                    {
                        //Para cada registro devuelto
                        foreach (DataRow f in mit.Rows)
                        {
                            //Instanciando registro
                            using (AsignacionPeriodo p = new AsignacionPeriodo(f.Field <int>("IdActividadAsignacionPeriodo")))
                            {
                                //Si el periodo existe
                                if (p.id_actividad_asignacion_periodo > 0)
                                {
                                    //Deshabilitando el registro
                                    resultado = p.DeshabilitaActividadPeriodo(id_usuario);
                                }
                                else
                                {
                                    resultado = new RetornoOperacion("Error al leer registro del periodo.");
                                }

                                //En caso de error, saliendo del ciclo
                                if (!resultado.OperacionExitosa)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
                //Validamos Resultado
                if (resultado.OperacionExitosa)
                {
                    scope.Complete();
                }
            }

            //Devolviendo resultado
            return(resultado);
        }
예제 #38
0
파일: Form2.cs 프로젝트: zhimaqiao51/docs
        //---------------------------------------------------------------------
        void Test()
        {
            //<Snippet11>
            using (System.Transactions.TransactionScope updateTransaction =
                       new System.Transactions.TransactionScope())
            {
                // Add code to save your data here.
                // Throw an exception to roll back the transaction.

                // Call the Complete method to commit the transaction
                updateTransaction.Complete();
            }
            //</Snippet11>
        }
        private void CDD_EditSaveEntry()
        {
            DataClasses1DataContext db = new DataClasses1DataContext();

            using (var scope = new System.Transactions.TransactionScope())
            {
                //Edison_DispatchExpHDR objCourse = new Edison_DispatchExpHDR();

                //objCourse.DispatchNo = Convert.ToInt32(searchLookUpEdit13.EditValue);


                //objCourse.InsertedDatetime = db.ExecuteQuery<DateTime>("SELECT GETDATE()").First();

                //db.Edison_DispatchExpHDRs.InsertOnSubmit(objCourse);
                //db.SubmitChanges();


                var a = from s in db.Edison_DispatchExpDTLs
                        where s.DispatchNo.Equals(textBox4.Text)
                        select s;

                if (a.Any())
                {
                    foreach (var d in a)
                    {
                        db.Edison_DispatchExpDTLs.DeleteOnSubmit(d);
                        db.SubmitChanges();
                    }
                }


                foreach (DataGridViewRow row in dataGridView5.Rows)
                {
                    Edison_DispatchExpDTL AddItems = new Edison_DispatchExpDTL();
                    AddItems.DispatchNo = Convert.ToInt32(textBox4.Text);
                    AddItems.ExpenseID  = Convert.ToInt32(row.Cells[1].Value.ToString() == "" ? "0" : row.Cells[1].Value.ToString());
                    AddItems.Amount     = Convert.ToDecimal(row.Cells[3].Value.ToString() == "" ? "0" : row.Cells[3].Value.ToString());
                    db.Edison_DispatchExpDTLs.InsertOnSubmit(AddItems);
                    db.SubmitChanges();
                }

                CD_RevertState();
                CD_DisableAll();

                scope.Complete();
            }

            form1.RefreshFormExpense();
        }
예제 #40
0
        private void resetTablesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (var db = new CoursemoDataContext())
                {
                    var TxOptions = new System.Transactions.TransactionOptions();
                    TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable;

                    using (var Tx = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, TxOptions))
                    {
                        var query = from en in db.Enrolleds
                                    select en;

                        foreach (Enrolled en in query)
                        {
                            db.Enrolleds.DeleteOnSubmit(en);
                        }

                        //db.Enrolleds.DeleteAllOnSubmit(query);

                        var query2 = from w in db.Waitlists
                                     select w;

                        foreach (Waitlist w in query2)
                        {
                            db.Waitlists.DeleteOnSubmit(w);
                        }
                        //db.Waitlists.DeleteAllOnSubmit(query2);

                        db.SubmitChanges();

                        Tx.Complete();
                    } //Using tx
                }     //Using db

                MessageBox.Show("Deletes successful");
            }

            catch (Exception ex)
            {
                MessageBox.Show("Delete failed + " + ex.Message);
            }
            finally
            {
                StudentListBox_SelectedIndexChanged(sender, e);
                CourseListBox_SelectedIndexChanged(sender, e);
            }
        }
예제 #41
0
        public static void InsertKpiMeasuerementImported(int kpiId, List <KPIMeasurements> theList, string type)
        {
            if (kpiId <= 0)
            {
                throw new ArgumentException(Resources.ImportData.ZeroKpiId);
            }

            using (System.Transactions.TransactionScope transaction = new System.Transactions.TransactionScope())
            {
                try
                {
                    KpiMeasurementDSTableAdapters.QueriesTableAdapter queries = new KpiMeasurementDSTableAdapters.QueriesTableAdapter();

                    foreach (KPIMeasurements theData in theList)
                    {
                        if (theData.DataTime != null)
                        {
                            theData.Measurement = KPIDataTimeBLL.GetValueFromKPIDataTime(theData.DataTime);
                        }

                        if (!string.IsNullOrEmpty(theData.MeasurementIDsToReplace) && type.Equals("R"))
                        {
                            queries.DeleteKpiMeasurementByListIds(theData.MeasurementIDsToReplace);
                        }

                        int?newData = 0;
                        queries.InsertKpiMeasurement(ref newData, kpiId, theData.Date, theData.Measurement);

                        if (!string.IsNullOrEmpty(theData.Detalle))
                        {
                            string[] itemList     = theData.Detalle.Split(',');
                            string[] categoryList = theData.Categories.Split(',');
                            for (int i = 0; i < itemList.Length; i++)
                            {
                                queries.InsertKpiMeasurementCategories(newData.Value, itemList[i].Trim(), categoryList[i].Trim());
                            }
                        }
                    }

                    transaction.Complete();
                }
                catch (Exception exc)
                {
                    log.Error("Error en InsertKpiMeasuerementImported para kpiId: " + kpiId, exc);
                    transaction.Dispose();
                    throw new Exception(Resources.ImportData.InsertMeasurementError);
                }
            }
        }
예제 #42
0
        private static PaymentResult ChangeBalance(Wallet wallet, TradeMode tradeMode, decimal totalFee, string tradeCode, string bizSource, long handlerId)
        {
            if (string.IsNullOrEmpty(bizSource))
            {
                throw new ArgumentNullException("bizSource");
            }

            if ((tradeMode == TradeMode.Payoff && totalFee < 0) || (tradeMode == TradeMode.Payout && totalFee > 0))
            {
                totalFee = 0 - totalFee;
            }

            var addWithdrawBalance = ModuleEnvironment.RealityMoneyBizSourceScopeList.Contains(bizSource);

            var journal = new WalletJournal();

            journal.WalletId        = wallet.WalletId;
            journal.TradeMode       = tradeMode;
            journal.TargetTradeCode = tradeCode;
            journal.BizSource       = bizSource;
            journal.TotalFee        = totalFee;
            journal.HandlerId       = handlerId;

            using (var scope = new System.Transactions.TransactionScope())
            {
                var changed = wallet.AddBalance(totalFee, addWithdrawBalance);
                if (changed)
                {
                    journal.Save();
                    scope.Complete();

                    var paidDetail = new Dictionary <string, object>();
                    paidDetail.Add("TradeCode", tradeCode);
                    paidDetail.Add("WalletId", wallet.WalletId);
                    paidDetail.Add("WalletType", wallet.WalletType);
                    paidDetail.Add("JournalId", journal.JournalId);
                    paidDetail.Add("BizSource", journal.BizSource);
                    paidDetail.Add("TotalFee", journal.TotalFee);
                    return(new PaymentResult()
                    {
                        Success = true, PaidDetail = paidDetail.ToJson()
                    });
                }
                return(new PaymentResult()
                {
                    Success = false
                });
            }
        }
예제 #43
0
        public ActionResult Edit(int id, TestViewModel test)
        {
            if (test != null && this.ModelState.IsValid)
            {
                var existingTest = this.Data.Tests.GetById(id);

                if (existingTest == null)
                {
                    this.TempData.AddDangerMessage(Resource.Invalid_test);
                    return(this.RedirectToAction("Problem", new { id }));
                }

                if (!this.CheckIfUserHasProblemPermissions(existingTest.ProblemId))
                {
                    this.TempData[GlobalConstants.DangerMessage] = "Нямате привилегиите за това действие";
                    return(this.RedirectToAction("Index", "Contests", new { area = "Administration" }));
                }

                using (var scope = new TransactionScope())
                {
                    existingTest.InputData   = test.InputData;
                    existingTest.OutputData  = test.OutputData;
                    existingTest.OrderBy     = test.OrderBy;
                    existingTest.IsTrialTest = test.Type == TestType.Trial;
                    existingTest.IsOpenTest  = test.Type == TestType.Open;

                    this.Data.Submissions.Update(
                        x => x.ProblemId == existingTest.ProblemId && !x.IsDeleted,
                        x => new Submission {
                        TestRunsCache = null
                    });
                    this.Data.SaveChanges();
                    this.Data.TestRuns.Delete(tr => tr.Test.ProblemId == existingTest.ProblemId);

                    if (test.RetestTask)
                    {
                        this.RetestSubmissions(existingTest.ProblemId);
                    }

                    this.Data.SaveChanges();
                    scope.Complete();
                }

                this.TempData.AddInfoMessage(Resource.Test_edited_successfully);
                return(this.RedirectToAction("Problem", new { id = existingTest.ProblemId }));
            }

            return(this.View(test));
        }
예제 #44
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();
                }
            }
        }
예제 #45
0
        /// <summary>
        /// Editamos un Concepto
        /// </summary>
        /// <param name="id_comprobante"></param>
        /// <param name="cantidad"></param>
        /// <param name="id_unidad"></param>
        /// <param name="id_descripcion"></param>
        /// <param name="descripcion_parte"></param>
        /// <param name="no_identificacion"></param>
        /// <param name="valor_unitario"></param>
        /// <param name="importe_moneda_captura"></param>
        /// <param name="importe_moneda_nacional"></param>
        /// <param name="id_usuario"></param>
        /// <returns></returns>
        public RetornoOperacion EditaConcepto(int id_comprobante, decimal cantidad, int id_unidad, int id_descripcion,
                                              int descripcion_parte, string no_identificacion, decimal valor_unitario,
                                              decimal importe_moneda_captura, decimal importe_moneda_nacional, int id_usuario)
        {
            //Declaramos Objeto Resultado
            RetornoOperacion resultado = new RetornoOperacion();

            //Creamos la transacción
            using (System.Transactions.TransactionScope scope = Transaccion.InicializaBloqueTransaccional(System.Transactions.IsolationLevel.ReadCommitted))
            {
                //Instanciamos comprobante
                using (Comprobante objComprobante = new Comprobante(id_comprobante))
                {
                    //validamos Existencia de comprobante
                    if (objComprobante.id_comprobante > 0)
                    {
                        //Validamos existencia de Descuento
                        if (objComprobante.descuento_moneda_captura == 0 || objComprobante.descuento_moneda_nacional == 0)
                        {
                            //Realizando actualizacion
                            resultado = editaConcepto(id_comprobante, 0, 1, cantidad, id_unidad, id_descripcion, "",
                                                      no_identificacion, valor_unitario, importe_moneda_captura, importe_moneda_nacional, id_usuario,
                                                      this._habilitar);



                            //Validamos Resultado
                            //Recalucular Impuestos
                            if (resultado.OperacionExitosa)
                            {
                                resultado = Impuesto.RecalcularImpuestos(id_comprobante, id_usuario);
                                //Finalizamos transacción
                                scope.Complete();
                            }
                        }
                        else
                        {
                            resultado = new RetornoOperacion("No se puede editar un concepto, ya que existe el descuento");
                        }
                    }
                    else
                    {
                        resultado = new RetornoOperacion("No se encontró datos complementarios Comprobante");
                    }
                }
            }

            return(resultado);
        }
 public static IQueryable <string> GetDistinctMediaTypes()
 {
     using (var txn = new System.Transactions.TransactionScope(
                System.Transactions.TransactionScopeOption.Required,
                new System.Transactions.TransactionOptions
     {
         IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
     }
                ))
     {
         return(BsoArchiveEntities.Current.WorkDocuments.
                Where(wd => wd.WorkDocumentName != "null" && !String.IsNullOrEmpty(wd.WorkDocumentName)).
                Select(wd => wd.WorkDocumentName.Trim()).Distinct());
     }
 }
 /// <summary>
 /// Get Distinct Commissions
 /// </summary>
 /// <returns></returns>
 public static IQueryable <string> GetDistinctCommissions()
 {
     using (var txn = new System.Transactions.TransactionScope(
                System.Transactions.TransactionScopeOption.Required,
                new System.Transactions.TransactionOptions
     {
         IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
     }
                ))
     {
         return(BsoArchiveEntities.Current.EventDetails.
                Where(ed => ed.WorkCommission != "null" && !String.IsNullOrEmpty(ed.WorkCommission)).
                Select(ed => ed.WorkCommission.Trim()).Distinct());
     }
 }
 /// <summary>
 /// Get Distinct Ensembles from Artist Detail
 /// </summary>
 /// <returns></returns>
 public static IQueryable <string> GetDistinctInstruments()
 {
     using (var txn = new System.Transactions.TransactionScope(
                System.Transactions.TransactionScopeOption.Required,
                new System.Transactions.TransactionOptions
     {
         IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
     }
                ))
     {
         return(BsoArchiveEntities.Current.ArtistDetails.
                Where(ad => ad.EnsembleType != "null" && !String.IsNullOrEmpty(ad.EnsembleType)).
                Select(ad => ad.EnsembleType.Trim()).Distinct());
     }
 }
예제 #49
0
        public int UpdateWithTrans(BMS_DAL.DS.BMSDS.TInvoiceDetailsDataTable dt)
        {
            int r = 0;

            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
            {
                try
                {
                    r = this.Adapter.Update(dt);
                    ts.Complete();
                }
                catch (Exception ex) { throw ex; }
            }
            return(r);
        }
        public void Delete(MasjidConstruction entity)
        {
            tbl_MasjidConstruction _tbl_MasjidConstruction_LocalVar = new tbl_MasjidConstruction(entity);

            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                if (entity.Id != null && entity.Id != 0)
                {
                    _tbl_MasjidConstruction_LocalVar        = _tbl_MasjidConstruction.FindBy(x => x.Id == entity.Id).FirstOrDefault();
                    _tbl_MasjidConstruction_LocalVar.Status = false;
                    _tbl_MasjidConstruction.Update(_tbl_MasjidConstruction_LocalVar);
                }
                scope.Complete();
            }
        }
예제 #51
0
        static void Replace(object replaceValue, object newValue)
        {
            using (var scope = new System.Transactions.TransactionScope())
                using (var connection = GetConnection())
                {
                    connection.Search(replaceValue, (result) =>
                    {
                        var sql         = $"Update {result.TableName} set {result.ColumnName} = @newValue where {result.ColumnName} = @replaceValue";
                        var effectCount = connection.Execute(sql, new { replaceValue, newValue }); //Using Dapper ORM

                        Assert.True(effectCount > 0);
                    });
                    scope.Complete();
                }
        }
예제 #52
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();
            }
        }
        public void Delete(MasjidLandRequest entity)
        {
            tbl_MasjidLandRequest AddMasjidLandRequestData = new tbl_MasjidLandRequest(entity);

            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                if (entity.Id != null && entity.Id != 0)
                {
                    AddMasjidLandRequestData.Id     = entity.Id;
                    AddMasjidLandRequestData.Status = false;
                    _tbl_MasjidLandRequest.Update(AddMasjidLandRequestData);
                }
                scope.Complete();
            }
        }
        public void Delete(NewMadarsaOperation entity)
        {
            tbl_NewMadarsaOperations _tbl_EMO_LocalVar = new tbl_NewMadarsaOperations(entity);

            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
            {
                if (entity.Id != null && entity.Id != 0)
                {
                    _tbl_EMO_LocalVar.Id     = entity.Id;
                    _tbl_EMO_LocalVar.Status = false;
                    _tbl_NewMadarsaOperations.Update(_tbl_EMO_LocalVar);
                }
                scope.Complete();
            }
        }
예제 #55
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;
     }
 }
        /// <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();
            }
        }
        public void CreateAdminLoginTest()
        {
            AdminLogin adminLogin = new AdminLogin();
            List<string> errors = new List<string>();
            adminLogin.admin_name = "BLcreateadmintest";
            adminLogin.admin_password = "******"; // TODO: Initialize to an appropriate value
            adminLogin.first_name = "test"; // TODO: Initialize to an appropriate value
            adminLogin.middle_name = "test"; // TODO: Initialize to an appropriate value
            adminLogin.last_name = "test"; // TODO: Initialize to an appropriate value
            AdminLogin check = new AdminLogin();
            using (var scop = new System.Transactions.TransactionScope())
            {
                //insert
                BLAdminLogins.CreateAdminLogin(adminLogin, ref errors);
                check = BLAdminLogins.GetAdminInfo(adminLogin.admin_id.ToString(), ref errors);
                Assert.AreEqual(0, errors.Count);
                Assert.IsNotNull(check);
                Assert.AreEqual(adminLogin.admin_id, check.admin_id);
                Assert.AreEqual(adminLogin.admin_name, check.admin_name);
                Assert.AreEqual(adminLogin.admin_password, check.admin_password);
                Assert.AreEqual(adminLogin.first_name, check.first_name);
                Assert.AreEqual(adminLogin.middle_name, check.middle_name);
                Assert.AreEqual(adminLogin.last_name, check.last_name);

                //update
                adminLogin.admin_password = "******"; // TODO: Initialize to an appropriate value
                adminLogin.first_name = "updated BL "; // TODO: Initialize to an appropriate value
                adminLogin.middle_name = "updated BL"; // TODO: Initialize to an appropriate value
                adminLogin.last_name = "updated BL"; // TODO: Initialize to an appropriate value
                BLAdminLogins.UpdateAdmin(adminLogin, ref errors);
                check = BLAdminLogins.GetAdminInfo(adminLogin.admin_id.ToString(), ref errors);
                Assert.AreEqual(0, errors.Count);
                Assert.IsNotNull(check);
                Assert.AreEqual(adminLogin.admin_id, check.admin_id);
                Assert.AreEqual(adminLogin.admin_name, check.admin_name);
                Assert.AreEqual(adminLogin.admin_password, check.admin_password);
                Assert.AreEqual(adminLogin.first_name, check.first_name);
                Assert.AreEqual(adminLogin.middle_name, check.middle_name);
                Assert.AreEqual(adminLogin.last_name, check.last_name);

                //detele
                BLAdminLogins.DeleteAdmin(adminLogin.admin_id.ToString(), ref errors);
                check = BLAdminLogins.GetAdminInfo(adminLogin.admin_id.ToString(), ref errors);
                Assert.AreEqual(0, errors.Count);
                Assert.IsNull(check);

            }
        }
예제 #58
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;
			}
		}
예제 #59
0
        public void CreatePermitErrorTest()
        {
            Customer customer = new Customer();
            customer.customer_name = "bltestcreatecustomer";
            customer.customer_pw = "fakepassword1"; // TODO: Initialize to an appropriate value
            customer.customer_type = "undertest";
            customer.first_name = "test"; // TODO: Initialize to an appropriate value
            customer.middle_name = "test"; // TODO: Initialize to an appropriate value
            customer.last_name = "test"; // TODO: Initialize to an appropriate value
            List<string> errors = new List<string>();
            using (var scop = new System.Transactions.TransactionScope())
            {
                BLCustomers.CreateCustomer(customer, ref errors);

                Permit permit = new Permit();
                permit.permit_name = "bl customertest";
                permit.customer_type = "undergrad";
                permit.price = 50;
                permit.v_description = "test";
                BLPermitTypes.CreatePermitType(permit, ref errors);

                Record record = new Record();
                record.customer_id = customer.customer_id;
                record.permit_type_id = permit.id;
                record.expire_date = DateTime.Parse("11/11/2011");
                record.valid = true;
                BLRecords.CreatePermit(record, ref errors);

                Violation violation = new Violation();
                violation.permit_id = record.permit_id;
                violation.fee = 48;
                violation.v_description = "testing create violations - test1";
                violation.violation_date = DateTime.Parse("11/11/2011");
                violation.paid = false;
                BLViolations.CreateViolation(violation, ref errors);

                Record record1 = new Record();
                record1.customer_id = customer.customer_id;
                record1.permit_type_id = permit.id;
                record1.expire_date = DateTime.Parse("11/11/2011");
                record1.valid = true;
                BLRecords.CreatePermit(record1, ref errors);

                Assert.AreEqual(1, errors.Count);
            }
        }
        public void CreateInvoiceTest()
        {
            //connections variables and dataset
            SqlConnection conn = new SqlConnection(connection_string);
            List<string> errors = new List<string>();
            using (var scop = new System.Transactions.TransactionScope())
            {
                Customer customer = new Customer();
                customer.customer_name = "create invoice test";
                customer.customer_pw = "test";
                customer.customer_type = "test";
                customer.first_name = "test";
                customer.middle_name = "test";
                customer.last_name = "test";
                int customerId = DALCustomers.CreateCustomer(customer, ref errors);

                Permit permit = new Permit();
                permit.permit_name = "create invoice test";
                permit.customer_type = "test";
                permit.price = 50;
                permit.v_description = "test";
                permit.id = DALPermitTypes.CreatePermitType(permit, ref errors);

                Invoice invoice = new Invoice();
                invoice.invoice_type = "create invoice test";
                invoice.customer_id = customerId;
                invoice.item_id = permit.id;
                invoice.amt_paid = 200;
                invoice.pay_method = "visa";
                invoice.pay_date = DateTime.Today;
                invoice.invoice_id = DALInvoices.CreateInvoice(invoice, ref errors);
                Invoice check = DALInvoices.GetInvoiceInfo(invoice.invoice_id, ref errors);

                Assert.AreEqual(0, errors.Count);
                Assert.IsNotNull(check);
                Assert.AreEqual(invoice.invoice_id, check.invoice_id);
                Assert.AreEqual(invoice.invoice_type, check.invoice_type);
                Assert.AreEqual(invoice.customer_id, check.customer_id);
                Assert.AreEqual(invoice.item_id, check.item_id);
                Assert.AreEqual(invoice.amt_paid, check.amt_paid);
                Assert.AreEqual(invoice.pay_method, check.pay_method);
                Assert.AreEqual(invoice.pay_date, check.pay_date);

            }
        }