Пример #1
1
        public SigmaResultType AddEquipment(TypeEquipment objEquipment)
        {
            TypeUserInfo userinfo = AuthMgr.GetUserInfo();

            SigmaResultType result = new SigmaResultType();
            TransactionScope scope = null;

            // Get connection string
            string connStr = ConnStrHelper.getDbConnString();

            List<SqlParameter> paramList = new List<SqlParameter>();
            paramList.Add(new SqlParameter("@EquipmentCodeMain", objEquipment.EquipmentCodeMain.Trim()));
            paramList.Add(new SqlParameter("@EquipmentCodeSub", objEquipment.EquipmentCodeSub.Trim()));
            paramList.Add(new SqlParameter("@Description", objEquipment.Description.Trim()));
            paramList.Add(new SqlParameter("@ThirdLevel", objEquipment.ThirdLevel.Trim()));
            paramList.Add(new SqlParameter("@Spec", objEquipment.Spec.Trim()));
            paramList.Add(new SqlParameter("@EquipmentType", objEquipment.EquipmentType.Trim()));
            paramList.Add(new SqlParameter("@CreatedBy", userinfo.SigmaUserId.Trim()));
            paramList.Add(new SqlParameter("@ModelNumber", objEquipment.ModelNumber.Trim()));
            SqlParameter outParam = new SqlParameter("@NewId", SqlDbType.Int);
            outParam.Direction = ParameterDirection.Output;
            paramList.Add(outParam);

            using (scope = new TransactionScope(TransactionScopeOption.Required))
            {
                result.AffectedRow = SqlHelper.ExecuteNonQuery(connStr, CommandType.StoredProcedure, "usp_AddEquipment", paramList.ToArray());
                result.IsSuccessful = true;
                result.ScalarValue = (int)outParam.Value;

                scope.Complete();
            }

            return result;
        }
Пример #2
1
        public SigmaResultType AddCWA(TypeCWA objCWA)
        {
            TypeUserInfo userinfo = AuthMgr.GetUserInfo();

            TransactionScope scope = null;
            SigmaResultType result = new SigmaResultType();

            // Get connection string
            string connStr = ConnStrHelper.getDbConnString();

            List<SqlParameter> paramList = new List<SqlParameter>();
            paramList.Add(new SqlParameter("@ProjectId", Utilities.ToInt32(userinfo.CurrentProjectId.ToString().Trim())));
            paramList.Add(new SqlParameter("@Name", objCWA.Name.Trim()));
            paramList.Add(new SqlParameter("@Area", objCWA.Area));
            paramList.Add(new SqlParameter("@Description", objCWA.Description.Trim()));
            paramList.Add(new SqlParameter("@CreatedBy", userinfo.SigmaUserId.Trim()));
            SqlParameter outParam = new SqlParameter("@NewId", SqlDbType.Int);
            outParam.Direction = ParameterDirection.Output;
            paramList.Add(outParam);

            using (scope = new TransactionScope(TransactionScopeOption.Required))
            {
                result.AffectedRow = SqlHelper.ExecuteNonQuery(connStr, CommandType.StoredProcedure, "usp_AddCWA", paramList.ToArray());
                result.IsSuccessful = true;
                result.ScalarValue = (int)outParam.Value;

                scope.Complete();
            }

            return result;
        }
Пример #3
0
        /// <summary>
        /// ����rma��
        /// </summary>
        /// <param name="rmaInfo"></param>
        public void AddRMA(RMAInfo rmaInfo)
        {
            TransactionOptions options = new TransactionOptions();
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            options.Timeout = TransactionManager.DefaultTimeout;

            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
            {
                if(!this.IfExistOpenedRMA(rmaInfo.SOSysNo))
                {
                    Hashtable leftHash = this.GetLeftRMAQty(rmaInfo.SOSysNo);
                    foreach(RMAItemInfo item in rmaInfo.ItemHash.Values)
                    {
                        if(item.RMAQty>(int)leftHash[item.ProductSysNo])
                            throw new BizException("����д�ı�����Ʒ�����������۵���ʵ�ʹ�����������ȷ���豣�޵���Ʒ��Ϊ�˵�����");
                    }
                    rmaInfo.SysNo = SequenceDac.GetInstance().Create("RMA_Sequence");
                    rmaInfo.RMAID = this.BuildRMAID(rmaInfo.SysNo);
                    rmaInfo.SubmitInfo = this.GetRMASnapShot(rmaInfo);
                    rmaInfo.Status = (int)AppEnum.RMAStatus.Origin;
                    this.InsertMaster(rmaInfo);
                    foreach(RMAItemInfo rmaItem in rmaInfo.ItemHash.Values)
                    {
                        rmaItem.RMASysNo = rmaInfo.SysNo;
                        this.InsertItem(rmaItem);
                    }
                }
                else
                    throw new BizException("�����۵��Ѿ�����һ�ű��޵��ڴ����У�������������ύ�µı������룬����ϵORS�̳ǿͷ�");
                scope.Complete();
            }
        }
Пример #4
0
        /// <summary>
        /// Starts a new Amnesia session with a remote application
        /// </summary>
        public Session(string appUrl, ILog log)
        {
            this.log = log ?? NullLog.Instance;

            this.serviceUrl = appUrl + Amnesia.Settings.Current.HandlerPath;

            // Start a new distributed transaction
            TxScope = new TransactionScope(TransactionScopeOption.Required, TransactionTimeout);
            var request = new Handler.StartSessionRequest();
            Transaction tx = Transaction.Current;
            request.Transaction = tx;

            var response = request.Send(serviceUrl);
            LogResponse(response);

            response.ReceivedByClient();

            // Monitor the distributed transaction in order to detect if its aborted remotely.
            tx.EnlistVolatile(new AbortNotification((o, e) =>
            {
                if (isDisposed)
                    return;

                if (request.Transaction.TransactionInformation.Status == TransactionStatus.Aborted)
                {
                    Session.IsRollbackPending = true;
                }
            }),
            EnlistmentOptions.None);
        }
Пример #5
0
        /// <summary>
        /// 作者:Vincen
        /// 时间:2014.04.30
        /// 描述:创建消息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="loginUserId"></param>
        /// <returns></returns>
        public static bool CreateMessage(MessageModel model, int loginUserId)
        {
            try
            {
                using (var tran = new TransactionScope())
                {
                    using (var edb = new EmeEntities())
                    {
                        var msg = new Message()
                        {
                            MessageType = model.MessageType,
                            Subject = model.Subject,
                            MContent = model.MContent,
                            Receivers = model.Receiver.Count,
                            Openers = 0,
                            Status = ConvertEnum.StatusTypeForActive,
                            CreateBy = model.CreateBy,
                            CreateTime = model.CreateTime
                        };

                        edb.Entry(msg).State = EntityState.Added;
                        edb.SaveChanges();

                        var receiver = from a in model.Receiver
                                       select new MessageReceiver()
                                           {
                                               MessageId = msg.Id,
                                               Receiver = a,
                                               IsRead = false,
                                               Status = ConvertEnum.StatusTypeForActive,
                                               CreateBy = model.CreateBy,
                                               CreateTime = model.CreateTime
                                           };
                        foreach (var messageReceiver in receiver)
                        {
                            edb.Entry(messageReceiver).State = EntityState.Added;
                        }

                        var result = edb.SaveChanges() > 0;

                        tran.Complete();
                        return result;
                    }
                }
            }
            catch (Exception e)
            {
                // 异常日志消息队列
                Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs()
                {
                    ExceptionType = CommonHelper.To<int>(ExceptionType.Function),
                    Message = string.Format("EmeBLL-CreateMessage:{0};{1};{2}", e.Message, e.InnerException.Message, e.HelpLink),
                    IsTreat = false,
                    CreateBy = loginUserId,
                    CreateTime = DateTime.Now
                });

                return false;
            }
        }
Пример #6
0
        public SigmaResultType AddSigmaUserSigmaRole(TypeSigmaUserSigmaRole objSigmaUserSigmaRole)
        {
            TypeUserInfo userinfo = AuthMgr.GetUserInfo();
            objSigmaUserSigmaRole.CreatedBy = userinfo.SigmaUserId;
            //objSigmaUserSigmaRole.ProjectId = userinfo.CurrentProjectId;

            TransactionScope scope = null;
            SigmaResultType result = new SigmaResultType();

            // Get connection string
            string connStr = ConnStrHelper.getDbConnString();

            List<SqlParameter> paramList = new List<SqlParameter>();
            paramList.Add(new SqlParameter("@SigmaRoleId", objSigmaUserSigmaRole.SigmaRoleId));
            paramList.Add(new SqlParameter("@SigmaUserId", objSigmaUserSigmaRole.SigmaUserId));
            paramList.Add(new SqlParameter("@ReportTo", objSigmaUserSigmaRole.ReportTo));
            paramList.Add(new SqlParameter("@ReportToRole", objSigmaUserSigmaRole.ReportToRole));
            paramList.Add(new SqlParameter("@IsDefault", objSigmaUserSigmaRole.IsDefault));
            paramList.Add(new SqlParameter("@ProjectId", objSigmaUserSigmaRole.ProjectId));
            paramList.Add(new SqlParameter("@CreatedBy", objSigmaUserSigmaRole.CreatedBy));

            using (scope = new TransactionScope(TransactionScopeOption.Required))
            {
                result.AffectedRow = SqlHelper.ExecuteNonQuery(connStr, CommandType.StoredProcedure, "usp_AddSigmaUserSigmaRole", paramList.ToArray());
                result.IsSuccessful = true;

                scope.Complete();
            }

            return result;
        }
Пример #7
0
        /// <summary>
        /// 创建报表文件格式
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public int Create(ReportsEntity entity,List<ReportParamsEntity> list)
        {
            if (!entity.ReportNum.IsEmpty())
            {
                return Update(entity,list);
            }
            int line = 0;
            using (TransactionScope ts = new TransactionScope())
            {
                entity.ReportNum = entity.ReportNum.IsEmpty() ? SequenceProvider.GetSequence(typeof(ReportsEntity)) : entity.ReportNum;
                entity.IncludeAll();
                line += this.Reports.Add(entity);

                if (!list.IsNullOrEmpty())
                {
                    foreach (ReportParamsEntity item in list)
                    {
                        item.ParamNum = item.ParamNum.IsEmpty() ? SequenceProvider.GetSequence(typeof(ReportParamsEntity)) : item.ParamNum;
                        item.ReportNum = entity.ReportNum;
                        item.IncludeAll();
                    }
                    this.ReportParams.Add(list);
                }
                ts.Complete();
            }

            return line;
        }
Пример #8
0
        public SigmaResultType AddCustomFieldWithEquipmentCustomField(TypeCustomField objCustomField)
        {
            TypeUserInfo userinfo = AuthMgr.GetUserInfo();

            TransactionScope scope = null;
            SigmaResultType result = new SigmaResultType();
            SigmaResultType customField = new SigmaResultType();
            SigmaResultType EquipmentCustomField = new SigmaResultType();
            TypeEquipmentCustomField typeEquipmentCustomField = new TypeEquipmentCustomField();

            typeEquipmentCustomField.EquipmentId = objCustomField.Parentid;
            typeEquipmentCustomField.Value = objCustomField.Value;
            typeEquipmentCustomField.CreatedBy = userinfo.SigmaUserId;
            typeEquipmentCustomField.UpdatedBy = userinfo.SigmaUserId;

            using (scope = new TransactionScope(TransactionScopeOption.Required))
            {
                CustomFieldMgr custom = new CustomFieldMgr();

                customField = custom.AddCustomField(objCustomField);
                typeEquipmentCustomField.CustomFieldId = customField.ScalarValue;
                EquipmentCustomField = AddEquipmentCustomField(typeEquipmentCustomField);

                scope.Complete();
            }

            return result;
        }
		public void InitialiseDatabase(Result result)
		{
			if (!result.Succeeded)
				return;

			SqlConnection conn = null;
			try
			{
				using (TransactionScope scope = new TransactionScope())
				{
					conn = (SqlConnection)DatabaseManager.DatabaseEngine.GetConnection();
					SqlServer2005Database db = (SqlServer2005Database)DatabaseManager.DatabaseEngine;
					Result r = db.ExecuteScript(conn, ResourceLoader.LoadTextResource("Sprocket.Web.FileManager.SqlServer2005.scripts.sql"));
					if (!r.Succeeded)
					{
						result.SetFailed(r.Message);
						return;
					}
					scope.Complete();
				}
			}
			finally
			{
				DatabaseManager.DatabaseEngine.ReleaseConnection(conn);
			}
			return;
		}
Пример #10
0
        public int DeleteData(IEntityBase value)
        {
            EConfigHoraSet objE = (EConfigHoraSet)value;

             try
             {

            using (TransactionScope tx = new TransactionScope())
            {

               this.DeleteDetail(objE.ColConfigHora, false);
               //this.DeleteMaster(objE.EConfigHora);

               tx.Complete();

            }

            return 1;

             }
             catch (Exception ex)
             {

            throw ex;

             }
        }
Пример #11
0
		public void Bug()
		{
			string connectionString = cfg.GetProperty("connection.connection_string");
			int id = -1;
			
			using (TransactionScope ts = new TransactionScope())
			{
				// Enlisting DummyEnlistment as a durable resource manager will start
				// a DTC transaction
				System.Transactions.Transaction.Current.EnlistDurable(
					DummyEnlistment.Id,
					new DummyEnlistment(),
					EnlistmentOptions.None);
				
				using (IDbConnection connection = new SqlConnection(connectionString))
				{
					connection.Open();
					using (ISession s = Sfi.OpenSession(connection))
					{
						id = (int)s.Save(new MyTable() { String = "hello!" });
					}
					connection.Close();
				}
				
				// Prior to the patch, an InvalidOperationException exception would occur in the
				// TransactionCompleted delegate at this point with the message, "Disconnect cannot
				// be called while a transaction is in progress". Although the exception can be
				// seen reported in the IDE, NUnit fails to see it, and the test passes. The
				// TransactionCompleted event fires *after* the transaction is committed and so
				// it doesn't affect the success of the transaction
				ts.Complete();
			}
		}
Пример #12
0
        public void InsertAssignDetail(KcbChidinhcl objKcbChidinhcls, KcbLuotkham objLuotkham, KcbChidinhclsChitiet[] assignDetail)
        {
            using (var scope = new TransactionScope())
             {
                 if (objLuotkham == null) return;
                 foreach (KcbChidinhclsChitiet objAssignDetail in assignDetail)
                 {
                     log.Info("Them moi thong tin cua phieu chi dinh chi tiet voi ma phieu Assign_ID=" +
                              objKcbChidinhcls.IdChidinh);
                     TinhCLS.TinhGiaChiDinhCLS(objLuotkham, objAssignDetail);
                     objAssignDetail.IdDoituongKcb = Utility.Int16Dbnull(objLuotkham.IdDoituongKcb);
                     objAssignDetail.IdChidinh = Utility.Int32Dbnull(objKcbChidinhcls.IdChidinh);
                     objAssignDetail.IdKham = Utility.Int32Dbnull(objKcbChidinhcls.IdKham, -1);
                     decimal PtramBHYT = Utility.DecimaltoDbnull(objLuotkham.PtramBhyt, 0);
                     TinhCLS.GB_TinhPhtramBHYT(objAssignDetail, objLuotkham, PtramBHYT);
                     objAssignDetail.MaLuotkham = objKcbChidinhcls.MaLuotkham;
                     objAssignDetail.IdBenhnhan = objKcbChidinhcls.IdBenhnhan;
                     if (Utility.Int32Dbnull(objAssignDetail.SoLuong) <= 0) objAssignDetail.SoLuong = 1;
                     if (objAssignDetail.IdChitietchidinh <= 0)
                     {

                         objAssignDetail.IsNew = true;
                         objAssignDetail.Save();
                     }
                     else
                     {
                         objAssignDetail.MarkOld();
                         objAssignDetail.IsNew = false;
                         objAssignDetail.Save();
                     }
                 }
                 scope.Complete();
             }
        }
Пример #13
0
        public void Abandon(int masterSysNo, int userSysNo)
        {
            TransactionOptions options = new TransactionOptions();
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            options.Timeout = TransactionManager.DefaultTimeout;

            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
            {

                //�����dz�ʼ״̬
                POInfo dbInfo = LoadPO(masterSysNo);
                if ( dbInfo == null )
                    throw new BizException("does not exist this po sysno");
                if ( dbInfo.Status != (int)AppEnum.POStatus.Origin )
                    throw new BizException("status is not origin now, abandon failed");

                //���� ���š�״̬�������
                Hashtable ht = new Hashtable(4);

                ht.Add("SysNo", masterSysNo);
                ht.Add("Status", (int)AppEnum.POStatus.Abandon);
                if ( 1!=new PODac().UpdateMaster(ht))
                    throw new BizException("expected one-row update failed, verify failed ");

                ProductIDManager.GetInstance().AbandonProductIDsByPO(masterSysNo);

                scope.Complete();
            }
        }
Пример #14
0
 public int AddClient(Client client)
 {
     using (TransactionScope scope = new TransactionScope())
     {
         DbParameter parameter = null;
         parameter = Db.CreateParameter("ClientId", DbType.Int32, 8);
         parameter.Direction = ParameterDirection.Output;
         Db.ExecuteNonQuery("usp_Client_InsertClientDetails", CommandType.StoredProcedure,
             new DbParameter[] {
                        parameter,
                        Db.CreateParameter("ClientName", client.ClientName),
                        Db.CreateParameter("ContactName", client.ContactName),
                        Db.CreateParameter("Phone", client.Phone),
                        Db.CreateParameter("Email", client.Email),
                        Db.CreateParameter("TIN", client.TIN),
                        Db.CreateParameter("PrivateClientDetails", client.PrivateClientDetails),
                        Db.CreateParameter("OtherClientDetails", client.OtherClientDetails),
                        Db.CreateParameter("BillingAddress", client.BillingAddress),
                        Db.CreateParameter("City", client.City),
                        Db.CreateParameter("StateCode", client.StateCode),
                        Db.CreateParameter("Zip", client.Zip),
                        Db.CreateParameter("Country", client.Country),
                        Db.CreateParameter("ShipToDifferentAddress", client.ShipToDifferentAddress),
                        Db.CreateParameter("ShippingAddress", client.ShippingAddress),
                        Db.CreateParameter("ShippingCity", client.ShippingCity),
                        Db.CreateParameter("ShippingStateCode", client.ShippingStateCode),
                        Db.CreateParameter("ShippingZip", client.ShippingZip),
                        Db.CreateParameter("ShippingCountry", client.ShippingCountry),
                        Db.CreateParameter("Status", client.Status)
          });
         scope.Complete();
         return (int)parameter.Value;
     }
 }
Пример #15
0
        public void UpdateClient(Client client)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                Db.ExecuteNonQuery("usp_Client_UpdateClient", CommandType.StoredProcedure,
                    new DbParameter[] {
                               Db.CreateParameter("ClientId", client.ClientId),
                               Db.CreateParameter("ClientName", client.ClientName),
                               Db.CreateParameter("ContactName", client.ContactName),
                               Db.CreateParameter("Phone", client.Phone),
                               Db.CreateParameter("Email", client.Email),
                               Db.CreateParameter("TIN", client.TIN),
                               Db.CreateParameter("PrivateClientDetails", client.PrivateClientDetails),
                               Db.CreateParameter("OtherClientDetails", client.OtherClientDetails),
                               Db.CreateParameter("BillingAddress", client.BillingAddress),
                               Db.CreateParameter("City", client.City),
                               Db.CreateParameter("StateCode", client.StateCode),
                               Db.CreateParameter("Zip", client.Zip),
                               Db.CreateParameter("Country", client.Country),
                               Db.CreateParameter("ShipToDifferentAddress", client.ShipToDifferentAddress),
                               Db.CreateParameter("ShippingAddress", client.ShippingAddress),
                               Db.CreateParameter("ShippingCity", client.ShippingCity),
                               Db.CreateParameter("ShippingStateCode", client.ShippingStateCode),
                               Db.CreateParameter("ShippingZip", client.ShippingZip),
                               Db.CreateParameter("ShippingCountry", client.ShippingCountry)

                 });
                scope.Complete();
            }
        }
        public void Init()
        {
            _trans = new TransactionScope();
            // make connection
            db = new ApplicationDbContext();

            //make controller
            controller = new ReviewController { DbContext = db };

            // seed the database if empty
            if (db.Members.Count() == 0)
            {
                new Migrations.Configuration().SeedDebug(db);
                Console.WriteLine("Seeded DB");
            }
            else
            {
                Console.WriteLine("DB Already seeded");
            }

            Review validTestReview = new Review();
            Game game = db.Games.FirstOrDefault();
            Member member = db.Members.FirstOrDefault();
            validTestReview.Game_Id = game.Id;
            validTestReview.Game = game;
            validTestReview.Author = member;
            validTestReview.Rating = 3;
            validTestReview.Body = "Great Game!";
            validTestReview.Subject = "Review Title";
            validTestReview.IsApproved = false;
            validTestReview.Aprover_Id = null;

            db.Reviews.Add(validTestReview);
            db.SaveChanges();
        }
Пример #17
0
    //删除区间
    protected void Button2_Command(object sender, CommandEventArgs e)
    {
        int regionId = Convert.ToInt32(e.CommandArgument);

        bool success = false;
        using (TransactionScope ts = new TransactionScope())
        {
            DataTable lists = item_bll.GetItemListByRegionId(userId, regionId);
            foreach (DataRow dr in lists.Rows)
            {
                int itemId = Convert.ToInt32(dr["ItemID"]);
                int itemAppId = Convert.ToInt32(dr["ItemAppID"]);

                success = item_bll.DeleteItem(userId, itemId, itemAppId);
                if (!success)
                {
                    break;
                }
            }

            ts.Complete();
        }

        if (success)
        {
            Utility.Alert(this, "删除成功。", "QuJianTongJi.aspx");
        }
        else
        {
            Utility.Alert(this, "删除失败!");
        }
    }
Пример #18
0
        public ActionResult Index()
        {
            var outParam = new SqlParameter
            {
                ParameterName = "@result",
                Direction = ParameterDirection.Output,
                SqlDbType = SqlDbType.Int
            };

            List<Boolean> _BUEvent = db.Database.SqlQuery<Boolean>("sp_InsertIntoBuEventLog @result OUT", outParam).ToList();

            using (TransactionScope transaction = new TransactionScope())
            {

                bool result = _BUEvent.FirstOrDefault();
                if (result)
                {
                    var _vwSendEmail = (db.vwSendEmails.Where(a => a.CREATEDDATE == CurrentDate).Select(a => new { a.KDKC, a.email, a.NMKC,a.TAHUN,a.BULAN,a.MINGGU })).Distinct();
                    int count = 0;
                    foreach(var sending in _vwSendEmail)
                    {
                        MemoryStream memory = new MemoryStream();
                        PdfDocument document = new PdfDocument() { Url = string.Format("http://*****:*****@gmail.com", "Legal-InHealth Reminder ");
                        message.Subject = SubjectName;
                        message.Attachments.Add(data);
                        message.Body = sending.NMKC;
                        SmtpClient client = new SmtpClient();

                        try
                        {
                            client.Send(message);
                        }
                        catch (Exception ex)
                        {

                            ViewData["SendingException"] = string.Format("Exception caught in SendErrorLog: {0}",ex.ToString());
                            return View("ErrorSending", ViewData["SendingException"]);
                        }
                        data.Dispose();
                        // Close the log file.
                        memory.Close();
                        count += 1;
                    }
                }
                transaction.Complete();
            }
            return View();
        }
Пример #19
0
        /// <summary>
        /// 添加选课
        /// </summary>
        /// <param name="studentNo">学号</param>
        /// <param name="courseNo">课程编号</param>
        public void AddChooseCourse(string studentNo, string courseNo, string termTag, string ClassID)
        {
            try
            {
                string sql = "INSERT INTO [USTA].[dbo].[usta_CoursesStudentsCorrelation] ([studentNo],[courseNo],[Year],[ClassID]) VALUES(@studentNo ,@courseNo,@Year,@ClassID)";
                SqlParameter[] parameters = {
                new SqlParameter("@courseNo", SqlDbType.NChar,20),
                new SqlParameter("@studentNo", SqlDbType.NChar,10),
                new SqlParameter("@Year", SqlDbType.NVarChar,50),
                new SqlParameter("@ClassID", SqlDbType.NVarChar,50)

            };
                parameters[0].Value = courseNo;
                parameters[1].Value = studentNo;
                parameters[2].Value = termTag;
                parameters[3].Value = ClassID;
                using (TransactionScope scope = new TransactionScope())
                {
                    SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql, parameters);
                    UpdateSchoolWordAndExperiment(studentNo, courseNo);
                    scope.Complete();
                }

            }
            catch (Exception ex)
            {
               MongoDBLog.LogRecord(ex);
                CommonUtility.RedirectUrl();
            }
            finally
            {
                conn.Close();
            }
        }
Пример #20
0
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;

            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == User.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (
                    var scope = new TransactionScope(TransactionScopeOption.Required,
                        new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return RedirectToAction("Manage", new { Message = message });
        }
Пример #21
0
        public void Editar(Partido item)
        {
            if (Eleicao.Iniciou)
            {
                throw new Exception("As eleições iniciaram não é possivel fazer essa operação");
            }

            List<Partido> partidoEncontrado = FindByName(item.Nome);
            if (partidoEncontrado.FindAll(partido => partido.Nome == item.Nome).Count != 0
                && partidoEncontrado.FindAll(partido => partido.Slogan == item.Slogan).Count != 0)
            {
                throw new Exception("Nome e slogan ja existentes.");
            }

            using (TransactionScope transacao = new TransactionScope())
            using (IDbConnection connection = new SqlConnection(connectionString))
            {
                IDbCommand comando = connection.CreateCommand();
                comando.CommandText =
                    "UPDATE Partido SET Nome = @paramNome, Slogan = @paramSlogan, Sigla = @paramSigla WHERE IDPartido = @paramIDPartido";
                comando.AddParameter("paramNome", item.Nome);
                comando.AddParameter("paramSlogan", item.Slogan);
                comando.AddParameter("paramSigla", item.Sigla);
                comando.AddParameter("paramIDPartido", item.Id);
                connection.Open();

                comando.ExecuteNonQuery();

                transacao.Complete();
                connection.Close();
            }
        }
Пример #22
0
        public static ActionResult CapnhatSoluong(long id, int soluongngay,byte cachtinhsoluong)
        {
            try
            {
                using (var scope = new TransactionScope())
                {
                    using (var sh = new SharedDbConnectionScope())
                    {

                      new Update(NoitruPhanbuonggiuong.Schema)
                                             .Set(NoitruPhanbuonggiuong.Columns.SoLuong).EqualTo(soluongngay)
                                             .Set(NoitruPhanbuonggiuong.Columns.CachtinhSoluong).EqualTo(cachtinhsoluong)
                                             .Where(NoitruPhanbuonggiuong.Columns.Id).IsEqualTo(id).Execute();
                    }
                    scope.Complete();
                    return ActionResult.Success;

                }
            }
            catch (Exception exception)
            {
                Utility.CatchException(exception);
                return ActionResult.Error;
            }
        }
Пример #23
0
        public static Boolean DeletedDirectDebit(DirectDebit debit)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                Boolean bol = false;
                using (var context = new SycousCon())
                {
                    try
                    {
                        var Update = context.DirectDebits.Where(c => c.ID == debit.ID&& c.IsDeleted==0&&c.IsApproved==0);

                        foreach (DirectDebit p in Update)
                        {
                            p.IsDeleted = 2;
                            p.ModifyBy = debit.ModifyBy;
                            p.ModifyDate = DateTime.Now;

                        }//
                        context.SaveChanges();
                        context.AcceptAllChanges();
                        scope.Complete();
                        context.Dispose();
                        bol = true;
                    }
                    catch (Exception ex)
                    {
                        context.Dispose();
                        throw;
                    }

                }// using
                return bol;
            } //trans
        }
Пример #24
0
        public int DeleteData(IEntityBase value)
        {
            EProcPlani objE = (EProcPlani)value;

             try
             {

            using (TransactionScope tx = new TransactionScope())
            {

               //this.DeleteDetail(objE.EProcPlani, false);
               this.DeleteMaster(objE);

               tx.Complete();

            }

            return 1;

             }
             catch
             {
            return 0;
             }
        }
Пример #25
0
        public static Boolean CreateDirectDebit(DirectDebit mdirectdebit)
        {
            Boolean flag = false;

                using (TransactionScope scope = new TransactionScope())
                {
                    using (var context = new SycousCon())
                    {
                        try
                        {
                            context.DirectDebits.AddObject(mdirectdebit);
                            context.SaveChanges();
                            scope.Complete();
                            context.AcceptAllChanges();
                            flag = true;
                        }
                        catch (Exception ex)
                        {
                            context.Dispose();
                            throw;
                        }
                    }
                }

            return flag;
        }
Пример #26
0
        public static Boolean CreateEnergy(Energy energy)
        {
            Boolean flag = false;
              if (!(IsExistingEnergy(energy)))
              {
              using (TransactionScope scope = new TransactionScope())
              {
                  using (var context = new SycousCon())
                  {
                      try
                      {
                          context.Energies.AddObject(energy);
                          context.SaveChanges();
                          scope.Complete();
                          context.AcceptAllChanges();
                          flag = true;
                      }
                      catch (Exception ex)
                      {
                          context.Dispose();
                          throw;
                      }
                  }//
              }// using
              }//if

              return flag;
        }
		/// <summary>
		/// データ登録
		/// </summary>
		/// <param name="query">SQL文字列</param>
		/// <param name="args">パラメータ</param>
		/// <returns>True:正常終了 / False:エラー</returns>
		public static int Save(string query, params SQLiteParameter[] args)
		{
			using (var connector = new SqliteConnector())
			using (var command = new SQLiteCommand(query, connector.Connection))
			{
				SqliteCommander.SetParameters(command, args);

				connector.Open();
                
                int result = 0;

                using (var tran = new TransactionScope())
                {
                    result = command.ExecuteNonQuery();

                    if (0 < result)
                    {
                        tran.Complete();
                    }
                }

				connector.Close();

				return result;
			}
		}
Пример #28
0
        public static ActionResult Capnhatgia(long id, decimal don_gia, byte cachtinh_gia)
        {
            try
            {
                using (var scope = new TransactionScope())
                {
                    using (var sh = new SharedDbConnectionScope())
                    {

                        new Update(NoitruPhanbuonggiuong.Schema)
                                             .Set(NoitruPhanbuonggiuong.Columns.DonGia).EqualTo(don_gia)
                                             .Set(NoitruPhanbuonggiuong.Columns.CachtinhGia).EqualTo(cachtinh_gia)
                                             .Where(NoitruPhanbuonggiuong.Columns.Id).IsEqualTo(id).Execute();
                    }
                    scope.Complete();
                    return ActionResult.Success;

                }
            }
            catch (Exception exception)
            {
                Utility.CatchException(exception);
                return ActionResult.Error;
            }
        }
Пример #29
0
        public ActionResult UpdateDynamicValues(List<DynamicValue> lstValues)
        {
            try
            {
                using (var scope = new TransactionScope())
                {
                    using (var sp = new SharedDbConnectionScope())
                    {
                        foreach (DynamicValue _object in lstValues)
                        {
                            if (_object.Id > 0)
                            {
                                _object.MarkOld();
                                _object.IsNew = false;
                                _object.Save();
                            }
                            else//Insert
                            {
                                _object.IsNew = true;

                                _object.Save();
                            }
                        }
                    }
                    scope.Complete();
                    return ActionResult.Success;
                }
            }
            catch (Exception exception)
            {
                Utility.ShowMsg(exception.Message);
                return ActionResult.Error;
            }
        }
Пример #30
0
        public string[] UpdateData(IEntityBase value)
        {
            EConfigHoraSet objE = (EConfigHoraSet)value;
             object[] objRet = null;

             try
             {

            using (TransactionScope tx = new TransactionScope())
            {

               this.DeleteDetail(objE.ColConfigHora, true);

               //objRet = this.UpdateMaster(objE.EConfigHora);

               this.UpdateDetail(objE.ColConfigHora, objRet);

               tx.Complete();

            }

            if (objRet == null)
               return null;

            return new String[] { objRet[0].ToString() };

             }
             catch (Exception ex)
             {

            throw ex;

             }
        }
            public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
            {
                DataEntityToken token = (DataEntityToken)entityToken;

                IPublishControlled publishControlled = (IPublishControlled)DataFacade.GetDataFromDataSourceId(token.DataSourceId);

                ValidationResults validationResults = ValidationFacade.Validate((IData)publishControlled);

                if (validationResults.IsValid)
                {
                    UpdateTreeRefresher treeRefresher = new UpdateTreeRefresher(token.Data.GetDataEntityToken(), flowControllerServicesContainer);

                    if (actionToken is PublishActionToken)
                    {
                        publishControlled.PublicationStatus = Published;
                    }
                    else if (actionToken is DraftActionToken)
                    {
                        publishControlled.PublicationStatus = Draft;
                    }
                    else if (actionToken is AwaitingApprovalActionToken)
                    {
                        publishControlled.PublicationStatus = AwaitingApproval;
                    }
                    else if (actionToken is AwaitingPublicationActionToken)
                    {
                        publishControlled.PublicationStatus = AwaitingPublication;
                    }
                    else if (actionToken is UnpublishActionToken)
                    {
                        publishControlled.PublicationStatus = Draft;

                        using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
                        {
                            IData data = DataFacade.GetDataFromOtherScope(token.Data, DataScopeIdentifier.Public).SingleOrDefault();

                            if (data != null)
                            {
                                IPage page = data as IPage;
                                if (page != null)
                                {
                                    IEnumerable <IData> referees;
                                    using (new DataScope(DataScopeIdentifier.Public))
                                    {
                                        referees = page.GetMetaData();
                                    }

                                    DataFacade.Delete(referees, CascadeDeleteType.Disable);
                                }


                                DataFacade.Delete(data, CascadeDeleteType.Disable);
                            }

                            transactionScope.Complete();
                        }
                    }
                    else if (actionToken is UndoPublishedChangesActionToken)
                    {
                        using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
                        {
                            using (ProcessControllerFacade.NoProcessControllers)
                            {
                                var   administrativeData = (IPublishControlled)token.Data;
                                IData publishedData      = DataFacade.GetDataFromOtherScope(token.Data, DataScopeIdentifier.Public).Single();

                                publishedData.FullCopyChangedTo(administrativeData);
                                administrativeData.PublicationStatus = Draft;

                                DataFacade.Update(administrativeData);
                            }

                            transactionScope.Complete();
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Unknown action token", "actionToken");
                    }

                    DataFacade.Update(publishControlled);

                    treeRefresher.PostRefreshMesseges(publishControlled.GetDataEntityToken());
                }
                else
                {
                    var managementConsoleMessageService = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>();

                    StringBuilder sb = new System.Text.StringBuilder();
                    sb.AppendLine(StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "ValidationErrorMessage"));
                    foreach (ValidationResult result in validationResults)
                    {
                        sb.AppendLine(result.Message);
                    }

                    managementConsoleMessageService.ShowMessage(DialogType.Error, StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "ValidationErrorTitle"), sb.ToString());
                }

                return(null);
            }
        /// <summary>
        /// Checks that cache operation behaves transactionally.
        /// </summary>
        private void CheckTxOp(Action <ICache <int, int>, int> act)
        {
            var isolationLevels = new[]
            {
                IsolationLevel.Serializable, IsolationLevel.RepeatableRead, IsolationLevel.ReadCommitted,
                IsolationLevel.ReadUncommitted, IsolationLevel.Snapshot, IsolationLevel.Chaos
            };

            foreach (var isolationLevel in isolationLevels)
            {
                var txOpts = new TransactionOptions {
                    IsolationLevel = isolationLevel
                };
                const TransactionScopeOption scope = TransactionScopeOption.Required;

                var cache = Cache();

                cache[1] = 1;
                cache[2] = 2;

                // Rollback.
                using (new TransactionScope(scope, txOpts))
                {
                    act(cache, 1);

                    Assert.IsNotNull(cache.Ignite.GetTransactions().Tx, "Transaction has not started.");
                }

                Assert.AreEqual(1, cache[1]);
                Assert.AreEqual(2, cache[2]);

                using (new TransactionScope(scope, txOpts))
                {
                    act(cache, 1);
                    act(cache, 2);
                }

                Assert.AreEqual(1, cache[1]);
                Assert.AreEqual(2, cache[2]);

                // Commit.
                using (var ts = new TransactionScope(scope, txOpts))
                {
                    act(cache, 1);
                    ts.Complete();
                }

                Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1);
                Assert.AreEqual(2, cache[2]);

                using (var ts = new TransactionScope(scope, txOpts))
                {
                    act(cache, 1);
                    act(cache, 2);
                    ts.Complete();
                }

                Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1);
                Assert.IsTrue(!cache.ContainsKey(2) || cache[2] != 2);
            }
        }
Пример #33
0
        private void btnAddUpdateInvoice_Click(object sender, EventArgs e)
        {
            bool addUpdateSuccess = false;

            if (m_invoiceExtra == null)
            {
                PopulateInvoiceExtra();
            }

            Facade.IInvoiceExtra facInvoiceExtra = new Facade.Invoice();

            if (m_isUpdate)
            {
                #region Update
                UpdateInvoiceExtra();

                using (TransactionScope ts = new TransactionScope())
                {
                    if (facInvoiceExtra.UpdateInvoiceExtra(m_invoiceExtra, this.txtAmountNet.Culture.LCID, ((Entities.CustomPrincipal)Page.User).UserName))
                    {
                        lblConfirmation.Text   = CONFIRMATION_UPDATE_MESSAGE;
                        addUpdateSuccess       = true;
                        rdiInvoiceDate.Enabled = !m_invoiceExtra.Posted;
                    }
                    else
                    {
                        lblConfirmation.Text = CONFIRMATION_ERROR_MESSAGE;
                    }

                    ts.Complete();
                }
                #endregion
            }
            else
            {
                #region Create
                m_extraIdCSV = (string)ViewState["ExtraIdCSV"];

                Entities.FacadeResult result = facInvoiceExtra.CreateInvoiceExtra(m_invoiceExtra, this.txtAmountNet.Culture.LCID, Convert.ToInt32(ViewState["IdentityId"]), ((Entities.CustomPrincipal)Page.User).UserName, m_extraIdCSV);

                if (result.Success)
                {
                    lblConfirmation.Text     = CONFIRMATION_ADD_MESSAGE;
                    btnAddUpdateInvoice.Text = "Update invoice";

                    addUpdateSuccess = true;
                    m_isUpdate       = true;

                    ViewState["InvoiceId"]    = result.ObjectId;                  // InvoiceId;
                    ViewState["InvoiceExtra"] = null;

                    PopulateStaticControls();
                    LoadInvoiceExtra();
                }
                else
                {
                    infringementDisplay.Infringements = result.Infringements;
                    infringementDisplay.DisplayInfringments();

                    lblConfirmation.Text = CONFIRMATION_ERROR_MESSAGE;
                }
                #endregion
            }

            lblConfirmation.Visible = true;

            if (addUpdateSuccess)
            {
                ViewInvoice();
            }
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,Title,Content,Summary," +
                                                             "PublishedDateTime,Url,VisitorCount,CreatedAt,ModifiedAt,BlogId,AuthorId," +
                                                             "CategoryId,TagIds,FileId,Timestamp")] Post post, IFormFile headerImage)
        {
            if (id != post.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                var transactions = new TransactionScope();
                try
                {
                    Models.File file = null;
                    if (headerImage == null || (headerImage != null &&
                                                !headerImage.ContentType.ToLower().StartsWith("image/")))
                    {
                        await _postRepository.ExecuteAsync(
                            new UpdatePostCommand(_context)
                        {
                            Id                = post.Id,
                            Title             = post.Title,
                            Summary           = post.Summary,
                            Content           = post.Content,
                            PublishedDateTime = post.PublishedDateTime,
                            AuthorId          = post.AuthorId,
                            BlogId            = post.BlogId,
                            CategoryId        = post.CategoryId,
                            TagIds            = post.TagIds,
                            CreatedAt         = post.CreatedAt,
                            Timestamp         = post.Timestamp
                        });

                        return(RedirectToAction("Index"));
                    }

                    MemoryStream ms = new MemoryStream();
                    headerImage.OpenReadStream().CopyTo(ms);

                    file = new Models.File()
                    {
                        Id          = post.FileId,
                        Name        = headerImage.Name,
                        FileName    = Path.GetFileName(headerImage.FileName),
                        Content     = ms.ToArray(),
                        Length      = headerImage.Length,
                        ContentType = headerImage.ContentType
                    };

                    if (file != null)
                    {
                        transactions.Transactions.Add(_filesContext.Database.BeginTransaction());
                        await _fileRepository.ExecuteAsync(
                            new UpdateFileCommand(_filesContext)
                        {
                            Content            = file.Content,
                            ContentDisposition = file.ContentDisposition,
                            ContentType        = file.ContentType,
                            FileName           = file.FileName,
                            Id     = file.Id,
                            Length = file.Length,
                            Name   = file.Name
                        });
                    }

                    transactions.Transactions.Add(_context.Database.BeginTransaction());
                    await _postRepository.ExecuteAsync(
                        new UpdatePostCommand(_context)
                    {
                        Id                = post.Id,
                        Title             = post.Title,
                        Summary           = post.Summary,
                        Content           = post.Content,
                        PublishedDateTime = post.PublishedDateTime,
                        AuthorId          = post.AuthorId,
                        BlogId            = post.BlogId,
                        CategoryId        = post.CategoryId,
                        TagIds            = post.TagIds,
                        CreatedAt         = post.CreatedAt,
                        Timestamp         = post.Timestamp,
                        FileId            = file.Id
                    });

                    transactions.Commit();
                    return(RedirectToAction("Index"));
                }
                catch (DbUpdateConcurrencyException dbUpdateConcurrencyException)
                {
                    if (!PostExists(post.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        try
                        {
                            #region User specific custom resolution
                            foreach (var entry in dbUpdateConcurrencyException.Entries)
                            {
                                if (entry.Entity is Post)
                                {
                                    var postEntry        = entry.GetDatabaseValues();
                                    var postFromDatabase = (Post)postEntry.ToObject();
                                    var postToBeUpdated  = (Post)entry.Entity;

                                    if (postFromDatabase.Title != postToBeUpdated.Title)
                                    {
                                        ModelState.AddModelError("Title", $"Current value: {postFromDatabase.Title}");
                                    }
                                    if (postFromDatabase.Content != postToBeUpdated.Content)
                                    {
                                        ModelState.AddModelError("Content", $"Current value: {postFromDatabase.Content}");
                                    }
                                    ModelState.AddModelError(string.Empty, "The record was modified by another user" +
                                                             " after the page was loaded. The save operation was canceled and the" +
                                                             " updated database values were displayed. If you still want to edit" +
                                                             " this record, click the Save button again.");
                                    post.Timestamp = (byte[])postFromDatabase.Timestamp;
                                    ModelState.Remove("Timestamp");
                                }
                                else if (entry.Entity is Models.File)
                                {
                                    var fileToBeUpdated = await _fileRepository.GetSingleAsync(
                                        new GetFileByIdQuery(_filesContext) { Id = ((Models.File)entry.Entity).Id }
                                        );

                                    var fileFromDatabase = _context.Entry(fileToBeUpdated);

                                    // Handle File concurrency conflicts
                                }
                                else
                                {
                                    throw new NotSupportedException("Don't know how to handle concurrency conflicts for " + entry.Metadata.Name);
                                }
                            }
                            #endregion

                            #region Client Wins
                            //var entry = dbUpdateConcurrencyException.Entries.Single();
                            //entry.OriginalValues.SetValues(entry.GetDatabaseValues());
                            //await _context.SaveChangesAsync();
                            //return RedirectToAction("Index");
                            #endregion

                            #region Database Wins
                            //dbUpdateConcurrencyException.Entries.Single().Reload();
                            //await _context.SaveChangesAsync();
                            //return RedirectToAction("Index");
                            #endregion
                        }
                        catch (Exception exception)
                        {
                            ExceptionDispatchInfo.Capture(exception.InnerException).Throw();
                        }
                    }
                }
            }
            ViewData["AuthorId"]   = new SelectList(_context.Users, "Id", "Id", post.AuthorId);
            ViewData["BlogId"]     = new SelectList(_context.Blogs, "Id", "Url", post.BlogId);
            ViewData["CategoryId"] = new SelectList(_context.Set <Category>(), "Id", "Id", post.CategoryId);
            ViewData["TagIds"]     = new MultiSelectList(_context.Tags, "Id", "Name", post.TagIds);
            return(View(post));
        }
        public async Task <IActionResult> Create([Bind("Id,Title,Content,Summary," +
                                                       "PublishedDateTime,Url,VisitorCount,CreatedAt,ModifiedAt,BlogId," +
                                                       "AuthorId,CategoryId,TagIds")] Post post, IFormFile headerImage)
        {
            if (ModelState.IsValid)
            {
                Models.File file = null;
                if (headerImage == null || (headerImage != null &&
                                            !headerImage.ContentType.ToLower().StartsWith("image/")))
                {
                    await _postRepository.ExecuteAsync(
                        new CreatePostCommand(_context)
                    {
                        Title             = post.Title,
                        Summary           = post.Summary,
                        Content           = post.Content,
                        PublishedDateTime = post.PublishedDateTime,
                        AuthorId          = post.AuthorId,
                        BlogId            = post.BlogId,
                        CategoryId        = post.CategoryId,
                        TagIds            = post.TagIds
                    });

                    return(RedirectToAction("Index"));
                }

                MemoryStream ms = new MemoryStream();
                headerImage.OpenReadStream().CopyTo(ms);

                file = new Models.File()
                {
                    Id          = Guid.NewGuid(),
                    Name        = headerImage.Name,
                    FileName    = Path.GetFileName(headerImage.FileName),
                    Content     = ms.ToArray(),
                    Length      = headerImage.Length,
                    ContentType = headerImage.ContentType
                };

                var transactions = new TransactionScope();
                try
                {
                    if (file != null)
                    {
                        transactions.Transactions.Add(_filesContext.Database.BeginTransaction());
                        await _fileRepository.ExecuteAsync(
                            new CreateFileCommand(_filesContext)
                        {
                            Content            = file.Content,
                            ContentDisposition = file.ContentDisposition,
                            ContentType        = file.ContentType,
                            FileName           = file.FileName,
                            Id     = file.Id,
                            Length = file.Length,
                            Name   = file.Name
                        });
                    }

                    transactions.Transactions.Add(_context.Database.BeginTransaction());
                    await _postRepository.ExecuteAsync(
                        new CreatePostCommand(_context)
                    {
                        Title             = post.Title,
                        Summary           = post.Summary,
                        Content           = post.Content,
                        PublishedDateTime = post.PublishedDateTime,
                        AuthorId          = post.AuthorId,
                        BlogId            = post.BlogId,
                        CategoryId        = post.CategoryId,
                        TagIds            = post.TagIds,
                        FileId            = file.Id
                    });

                    transactions.Commit();
                }
                catch (Exception exception)
                {
                    transactions.Rollback();
                    ExceptionDispatchInfo.Capture(exception.InnerException).Throw();
                }
                return(RedirectToAction("Index"));
            }
            ViewData["AuthorId"]   = new SelectList(_context.Users, "Id", "Id", post.AuthorId);
            ViewData["BlogId"]     = new SelectList(_context.Blogs, "Id", "Url", post.BlogId);
            ViewData["CategoryId"] = new SelectList(_context.Set <Category>(), "Id", "Id", post.CategoryId);
            ViewData["TagIds"]     = new MultiSelectList(_context.Tags, "Id", "Name", post.TagIds);
            return(View(post));
        }
Пример #36
0
        //审核通过
        protected void btn_Pass_Click(object sender, EventArgs e)
        {
            #region 验证数据
            var errorMsg = CheckData();
            if (!string.IsNullOrEmpty(errorMsg))
            {
                MessageBox.Show(this, errorMsg);
                return;
            }
            #endregion

            CostReportInfo model = _costReport.GetReportByReportId(new Guid(Request.QueryString["ReportId"]));
            if (model.State != (int)CostReportState.Auditing)
            {
                MessageBox.Show(this, "该单据状态已更新,不允许此操作!");
                return;
            }

            bool execute = false;
            if (model.ReportKind == (int)CostReportKind.Before)
            {
                //预借款
                BeforeLoan(model);
            }
            else if (model.ReportKind == (int)CostReportKind.Paying)
            {
                execute = true;
                //已扣款核销
                PayVerification(model);
            }
            else if (model.ReportKind == (int)CostReportKind.Later)
            {
                //凭证报销
                VoucherPay(model);
            }
            else if (model.ReportKind == (int)CostReportKind.FeeIncome)
            {
                //费用收入
                FeeIncome(model);
            }

            model.AssumeBranchId = string.IsNullOrEmpty(ddl_AssumeBranch.SelectedValue) ? Guid.Empty : new Guid(ddl_AssumeBranch.SelectedValue);
            model.AssumeGroupId  = string.IsNullOrEmpty(ddl_AssumeGroup.SelectedValue) ? Guid.Empty : new Guid(ddl_AssumeGroup.SelectedValue);
            model.AssumeShopId   = string.IsNullOrEmpty(ddl_AssumeShop.SelectedValue) ? Guid.Empty : new Guid(ddl_AssumeShop.SelectedValue);
            model.AuditingMan    = Personnel.PersonnelId;
            model.AuditingDate   = DateTime.Now;
            model.AuditingMemo   = txt_AuditingMemo.Text;

            #region 保存数据
            using (var ts = new TransactionScope(TransactionScopeOption.Required))
            {
                try
                {
                    _costReport.UpdateReport(model);

                    if (execute)
                    {
                        _costReport.UpdatePayCostAndExecuteDate(model.ReportId, model.RealityCost);
                        string errorMessage;
                        bool   result = ExecuteFinishHandle(model, Personnel, out errorMessage);
                        if (!result)
                        {
                            throw new Exception(errorMessage);
                        }
                    }

                    //添加操作日志
                    _operationLogManager.Add(Personnel.PersonnelId, Personnel.RealName, model.ReportId, model.ReportNo, OperationPoint.CostDeclare.AuditDeclare.GetBusinessInfo(), 1, "");

                    ts.Complete();
                    MessageBox.AppendScript(this, "setTimeout(function(){ CloseAndRebind(); }, " + GlobalConfig.PageAutoRefreshDelayTime + ");");
                }
                catch
                {
                    MessageBox.Show(this, "保存失败!");
                }
                finally
                {
                    ts.Dispose();
                }
            }
            #endregion
        }
Пример #37
0
        //
        // Drop():
        //
        // -1 - error
        // 0 - dropped, no waitlist
        // 1 - dropped, enrolled student from waitlist
        // 2 - not enrolled, dropped from waitlist
        // 3 - student was not either enrolled or waitlisted
        //
        private int Drop(int sid, int cid)
        {
            int retries = 0;

            // make sure parameters are valid
            if (sid < 0 || cid < 0)
            {
                return(-1);
            }

            using (var db = new CoursemoDataContext())
            {
                while (retries < 3)
                {
                    try
                    {
                        var txOptions = new TransactionOptions();
                        txOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable;

                        using (var transaction = new TransactionScope(TransactionScopeOption.Required,
                                                                      txOptions))
                        {
                            // student enrolled, drop course and enroll first student on waitlist
                            if (StudentEnrolled(sid, cid))
                            {
                                db.UnregisterStudent(sid, cid);
                                // candidate on waitlist exists
                                int sidFromWaitList = GetFirstStudentFromWaitlist(cid);

                                System.Threading.Thread.Sleep(_delay);

                                if (sidFromWaitList != 0)
                                {
                                    db.RegisterStudent(sidFromWaitList, cid);
                                    db.UnwaitlistStudent(sidFromWaitList, cid);
                                    db.SubmitChanges();
                                    transaction.Complete();
                                    return(1);
                                }
                                db.SubmitChanges();
                                transaction.Complete();
                                return(0);
                            }
                            // student not enrolled, but waitlisted, remove from waitlist
                            else if (StudentWaitlisted(sid, cid))
                            {
                                db.UnwaitlistStudent(sid, cid);
                                db.SubmitChanges();
                                transaction.Complete();
                                return(2);
                            }
                            else
                            {
                                return(3);
                            }
                        }
                    }
                    catch (SqlException exc)
                    {
                        // deadlock
                        if (exc.Number == 1205)
                        {
                            retries++;
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Drop(): " + e.Message);
                        return(-1);
                    }
                } // while
            }

            return(-1);
        }
Пример #38
0
        //
        // Enroll():
        //
        // Return values:
        //  -1 - error
        //  0 - Student already enrolled
        //  1 - Student enrolled
        //  2 - Student already waitlisted
        //  3 - Student waitlisted
        //
        private int Enroll(int sid, int cid)
        {
            int retries = 0;

            // make sure parameters are valid
            if (sid < 0 || cid < 0)
            {
                return(-1);
            }

            using (var db = new CoursemoDataContext())
            {
                while (retries < 3)
                {
                    try
                    {
                        var txOptions = new TransactionOptions();
                        txOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable;

                        using (var transaction = new TransactionScope(TransactionScopeOption.Required,
                                                                      txOptions))
                        {
                            // check if student is already enrolled
                            if (StudentEnrolled(sid, cid))
                            {
                                return(0);
                            }

                            // class is full, add to waitlist
                            if (GetCourseCapacity(cid) - GetCurrentEnrollment(cid) < 1)
                            {
                                // check if student is not on waitlist alread
                                if (StudentWaitlisted(sid, cid))
                                {
                                    return(2);
                                }

                                db.WaitlistStudent(sid, cid);
                                db.SubmitChanges();
                                transaction.Complete();
                                return(3);
                            }
                            // enroll
                            else
                            {
                                System.Threading.Thread.Sleep(_delay);

                                db.RegisterStudent(sid, cid);
                                db.SubmitChanges();
                                transaction.Complete();
                                return(1);
                            }
                        }
                    }
                    catch (SqlException exc)
                    {
                        // deadlock
                        if (exc.Number == 1205)
                        {
                            retries++;
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Enroll(): " + e.Message);
                        return(-1);
                    }
                } // while
            }

            return(-1);
        } // Enroll()
Пример #39
0
 public void BeforeTest(ITest test)
 {
     _scope = new TransactionScope(TransactionScopeOption.RequiresNew);
 }
 public void Initialize()
 {
     t = new TransactionScope();
 }
        /// <summary>
        /// Creates a product
        /// </summary>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public int CreateDTPatient(int incommingMsgID, string userID, string status, int attachmentID)
        {
            try
            {
                tblPatients patient        = new tblPatients();
                tblReferrer referrerRecord = new tblReferrer();
                tblRefAddr  referrerAddr   = new tblRefAddr();

                //  tbl_DT_Incoming_Message_Individual_Attachments tblAttachment = new tbl_DT_Incoming_Message_Individual_Attachments();
                tbl_DT_PatientReferral_Processed processedPatient = new tbl_DT_PatientReferral_Processed();
                var incomingMessagPprocessEntity = (from p in _unitOfWork.DT_Incoming_MessageRepo.Get()
                                                    join e in _unitOfWork.DT_Individial_AttachRepo.Get()
                                                    on p.ID equals e.InComingMessageID
                                                    where p.ID == incommingMsgID && e.ID == attachmentID
                                                    select new DT_IncomingMessagOperationEntity
                {
                    FileData = e.FileData,
                    EmailID = p.From
                }).ToList().FirstOrDefault();
                var DT_Referrer = (from p in _unitOfWork.DT_Referrer_EmailsRepo.Get()
                                   where p.DT_Email_Address == incomingMessagPprocessEntity.EmailID
                                   select p.Institute_ID).FirstOrDefault();

                string xmlString = incomingMessagPprocessEntity.FileData.ToString();

                //referrer = _unitOfWork.DT_Referrer_EmailsRepo.Get(o => o.Institute_ID == PatientWIP.Institute_ID).FirstOrDefault();

                using (StreamReader reader = new StreamReader(GenerateStreamFromString(xmlString), Encoding.Unicode))
                {
                    string oldstr  = "xmlns=\"urn:hl7-org:v3\"";
                    string oldstr1 = "xmlns:sdtc=\"urn:hl7-org:sdtc\"";

                    xmlString = xmlString.Replace(oldstr, "");
                    xmlString = xmlString.Replace(oldstr1, "");
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(xmlString);

                    var         nameNode          = xmlDoc.SelectNodes("ClinicalDocument/recordTarget/patientRole/patient/name");
                    var         DOBNode           = xmlDoc.SelectNodes("ClinicalDocument/recordTarget/patientRole/patient");
                    var         CityNode          = xmlDoc.SelectNodes("ClinicalDocument/recordTarget/patientRole/addr");
                    var         referrerNode      = xmlDoc.SelectNodes("ClinicalDocument/legalAuthenticator/assignedEntity/assignedPerson/name");
                    var         referrerAddrNode  = xmlDoc.SelectNodes("ClinicalDocument/legalAuthenticator/assignedEntity/addr");
                    var         referrerPhoneNode = xmlDoc.SelectNodes("ClinicalDocument/legalAuthenticator/assignedEntity/telecom");
                    XmlNodeList xnListtelecom     = xmlDoc.SelectNodes("/ClinicalDocument/recordTarget/patientRole/telecom");
                    ////ClinicalDocument//recordTarget//patientRole//patientRole//name
                    foreach (XmlNode subNode in nameNode)
                    {
                        patient.FirstName = subNode["given"].InnerText;
                        patient.LastName  = subNode["family"].InnerText;
                        patient.NickName  = patient.FirstName;
                    }
                    foreach (XmlNode subNode in referrerNode)
                    {
                        string given2 = string.Empty;
                        if (subNode["given"].NextSibling != null)
                        {
                            given2 = subNode["given"].NextSibling.InnerText.ToStringOrEmpty();
                        }
                        referrerRecord.FirstName   = subNode["given"].InnerText.ToStringOrEmpty() + " " + given2;
                        referrerRecord.LastName    = subNode["family"].InnerText.ToStringOrEmpty();
                        referrerRecord.PrintName   = subNode["family"].InnerText.ToStringOrEmpty() + ", " + subNode["given"].InnerText.ToStringOrEmpty() + " " + given2 + subNode["suffix"].InnerText.ToStringOrEmpty();
                        referrerRecord.Credentials = subNode["suffix"].InnerText.ToStringOrEmpty();
                    }
                    referrerRecord.ReferralType      = "DT";
                    referrerRecord.SendPOCBy         = "DT";
                    referrerRecord.createdby         = "DT-Load";
                    referrerRecord.createdts         = DateTime.Now;
                    referrerRecord.updatedby         = "DT-Load";
                    referrerRecord.updatedts         = DateTime.Now;
                    referrerRecord.NoFax             = false;
                    referrerRecord.ReferralInstitute = DT_Referrer;
                    referrerRecord.Title             = "Dr";
                    referrerRecord.NPINumber         = "";
                    referrerRecord.Email             = incomingMessagPprocessEntity.EmailID;
                    foreach (XmlNode subNode in DOBNode)
                    {
                        patient.BirthDate = subNode["birthTime"].Attributes["value"].Value;

                        DateTime dt;
                        if (DateTime.TryParseExact(patient.BirthDate.ToString(), "yyyyMMdd",
                                                   CultureInfo.InvariantCulture,
                                                   DateTimeStyles.None, out dt))
                        {
                            //Console.WriteLine(dt);
                            //  patient.BirthDate = dt.ToString();
                            patient.BirthDate = dt.ToShortDateString();
                        }


                        string gender = subNode["administrativeGenderCode"].Attributes["code"].Value;
                        if (gender.ToLower() == "f")
                        {
                            patient.Gender = "Female";
                        }
                        patient.Title = "Miss";
                        if (gender.ToLower() == "m")
                        {
                            patient.Gender = "Male";
                        }
                        patient.Title = "MR";
                    }
                    foreach (XmlNode subNode in CityNode)
                    {
                        patient.City     = subNode["city"].InnerText;
                        patient.State    = subNode["state"].InnerText;
                        patient.Address1 = subNode["streetAddressLine"].InnerText;
                        patient.ZipCode  = subNode["postalCode"].InnerText;
                    }
                    foreach (XmlNode subNode in referrerAddrNode)
                    {
                        referrerAddr.City          = subNode["city"].InnerText;
                        referrerAddr.State         = subNode["state"].InnerText;
                        referrerAddr.StreetAddress = subNode["streetAddressLine"].InnerText;
                        referrerAddr.ZipCode       = subNode["postalCode"].InnerText;
                        referrerAddr.startdt       = DateTime.Now;
                        referrerAddr.enddt         = DateTime.Now;
                        referrerAddr.createdby     = "DT-Load";
                        referrerAddr.createdts     = DateTime.Now;
                        referrerAddr.updatedby     = "DT-Load";
                        referrerAddr.updatedts     = DateTime.Now;
                    }
                    foreach (XmlNode xn in referrerPhoneNode)
                    {
                        if (xn.Attributes[0].Value == "WP")
                        {
                            var ph = xn.Attributes[1].Value.Replace("-", "").Replace("(", "").Replace(")", "");
                            referrerAddr.PhoneNo = ph.ToStringOrEmpty().Length > 0 ? ph.Substring(6) : "";
                        }
                    }
                    referrerAddr.FaxNo = "";

                    DateTime NowTime         = DateTime.Now;
                    int      M_Current_Day   = NowTime.Day;                           // Current Date with Day Display
                    int      M_Current_Month = Convert.ToInt32(DateTime.Today.Month); //Current Month as a Single Integer Display
                    int      CurrentYear     = DateTime.Today.Year;                   // Display Year as Integer

                    patient.ReferralDate = DateTime.Now.ToShortDateString();          //**what is referral date?

                    patient.updatedts = DateTime.Now.ToShortDateString().StringToDate();
                    patient.createdts = DateTime.Now.ToShortDateString().StringToDate();

                    //patient.ReferralDate = CurrentYear.ToString()+M_Current_Month.ToString()+M_Current_Day.ToString();  //need to find referral date.
                    // patient.ReferralSource = incomingMessagPprocessEntity.EmailID == null ? "noemail" : incomingMessagPprocessEntity.EmailID.Substring(0, 9);

                    // patient.HomePh = "000000000"; //need to find patient phone.

                    foreach (XmlNode xn in xnListtelecom)
                    {
                        if (xn.Attributes[0].Value == "HP")
                        {
                            patient.HomePh = xn.Attributes[1].Value.ToStringOrEmpty().Length > 0 ? xn.Attributes[1].Value.Substring(4) : "";
                        }
                        if (xn.Attributes[0].Value == "WP")
                        {
                            patient.WorkPh = xn.Attributes[1].Value.ToStringOrEmpty().Length > 0 ? xn.Attributes[1].Value.Substring(4) : "";
                        }
                        if (xn.Attributes[0].Value == "MC")
                        {
                            patient.CellPh = xn.Attributes[1].Value.ToStringOrEmpty().Length > 0 ? xn.Attributes[1].Value.Substring(4) : "";
                        }
                    }
                    //patient.ClinicNo = 7;
                    using (RehabEntities rehab = new RehabEntities())
                    {
                        var clinicnumber = (from inc in rehab.tbl_DT_ClinicUserMapping where inc.EmailId == incomingMessagPprocessEntity.EmailID.ToString() select inc.ClinicNo).FirstOrDefault();
                        if (clinicnumber == null)
                        {
                            patient.ClinicNo = Convert.ToInt16(clinicnumber);
                        }
                        else
                        {
                            patient.ClinicNo = 0;
                        }
                    }
                }


                using (var scopeCreate = new TransactionScope())
                {
                    _unitOfWork.ReferrerRepo.Insert(referrerRecord);
                    _unitOfWork.Save();

                    referrerAddr.Rrowid = referrerRecord.Rrowid;
                    _unitOfWork.RefAddrRepo.Insert(referrerAddr);
                    _unitOfWork.Save();



                    patient.ReferralSource = referrerRecord.Rrowid.ToStringOrEmpty();
                    _unitOfWork.PatientEntityRepo.Insert(patient);
                    _unitOfWork.Save();

                    ImportPatient(patient.Prowid, incommingMsgID, userID, status, attachmentID);

                    scopeCreate.Complete();
                    return(patient.Prowid);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public int ImportPatient(int paientID, int incommingMsgID, string userID, string status, int attachmentID)
        {
            int instituteId = 0;
            int flag        = 0;
            tblPatScannedDocs         patScanDoc = new tblPatScannedDocs();
            tbl_DT_PatientReferralMRN MRNEntity  = new tbl_DT_PatientReferralMRN();

            try
            {
                var incomingMessagPprocessEntity = (from p in _unitOfWork.DT_Incoming_MessageRepo.Get()
                                                    join e in _unitOfWork.DT_Individial_AttachRepo.Get()
                                                    on p.ID equals e.InComingMessageID
                                                    where p.ID == incommingMsgID && e.ID == attachmentID
                                                    select new DT_IncomingMessagOperationEntity
                {
                    FileData = e.FileData,
                    EmailID = p.From,
                    InComingMessageID = p.ID
                }).ToList().FirstOrDefault();


                string xmlString = incomingMessagPprocessEntity.FileData.ToString();
                if (incomingMessagPprocessEntity.InComingMessageID > 0)
                {
                    var referrer = (from S in _unitOfWork.DT_ReferrerRepo.Get()
                                    join K in _unitOfWork.DT_Referrer_EmailsRepo.Get()
                                    on S.Institute_ID equals K.Institute_ID
                                    where K.DT_Email_Address == incomingMessagPprocessEntity.EmailID
                                    select new
                    {
                        Institute_ID = S.Institute_ID,
                        EmailID = K.DT_Email_Address
                    }).SingleOrDefault();
                    MRNEntity.Institute_ID = referrer.Institute_ID.ToString();
                    instituteId            = referrer.Institute_ID;
                }
                patScanDoc.PDFName = GeneratePdf(xmlString, paientID);
                patScanDoc.PTrowid = paientID;
                patScanDoc.doctype = "DT_Message";
                //patScanDoc.createdby = ;
                patScanDoc.createdts          = DateTime.Now;
                MRNEntity.InstitutePatientMRN = "";

                MRNEntity.PatientId = paientID;
                var tblMrn = _unitOfWork.DT_PatientReferralMRNRepo.Get(o => o.ID == paientID).FirstOrDefault();
                using (var scopeImport = new TransactionScope())
                {
                    _unitOfWork.PatScannedDocsRepo.Insert(patScanDoc);

                    if (tblMrn != null)
                    {
                        if (tblMrn.ID > 0)
                        {
                            if (instituteId != 0 || !string.IsNullOrEmpty(MRNEntity.InstitutePatientMRN))
                            {
                                _unitOfWork.DT_PatientReferralMRNRepo.Insert(MRNEntity);
                            }
                        }
                    }
                    MoveIncomingtoReferrerProccessed(paientID, incommingMsgID, xmlString, instituteId, status, userID);
                    _unitOfWork.Save();
                    scopeImport.Complete();

                    flag = 1;
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return(flag);
        }
        public async Task <HttpResponseMessage> PostUserImage()
        {
            Dictionary <string, object> dict    = new Dictionary <string, object>();
            Dictionary <string, object> product = new Dictionary <string, object>();

            if (!Request.Content.IsMimeMultipartContent())
            {
                return(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
            }
            var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();

            var contentMP = filesReadToProvider.Contents;

            foreach (var item in contentMP)
            {
                if (item.Headers.ContentType.MediaType == "application/json")
                {
                    product[item.Headers.ContentDisposition.Name.ToString().Replace("\"", "")] = item.ReadAsStringAsync().Result;
                }
                else
                {
                    var fileBytes = await item.ReadAsByteArrayAsync();

                    int            MaxContentLength      = 1024 * 1024 * 5; //Size = 1 MB
                    IList <string> AllowedFileExtensions = new List <string> {
                        ".jpg", ".gif", ".png"
                    };
                    var filename = item.Headers.ContentDisposition.FileName;
                    filename = filename.Replace("\"", "");

                    var ext       = filename.Substring(filename.LastIndexOf('.'));
                    var extension = ext.ToLower();
                    // extension= extension.Remove(extension.Length - 1, 1);
                    if (!AllowedFileExtensions.Contains(extension))
                    {
                        var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
                        dict.Add("error", message);

                        return(Request.CreateResponse(HttpStatusCode.BadRequest, dict));
                    }
                    else if (item.Headers.ContentLength > MaxContentLength)
                    {
                        var message = string.Format("Please Upload a file upto 1 mb.");

                        dict.Add("error", message);
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, dict));
                    }
                    else
                    {
                        var httpPostedFile = HttpContext.Current.Request.Files["image"];

                        string relativepath = "~/productimage/" + product["ItemName"] + extension;
                        product["filepath"] = relativepath;
                        var filePath = HttpContext.Current.Server.MapPath(relativepath);
                        httpPostedFile.SaveAs(filePath);
                    }
                }
            }
            //db add


            var db = DbUtils.GetDBConnection();

            db.Connection.Open();
            // using (var scope = db.Connection.BeginTransaction())
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    var res = db.Query("fooditem").Insert(product);
                    scope.Complete();  // if record is entered successfully , transaction will be committed
                    db.Connection.Close();
                    return(Request.CreateResponse(HttpStatusCode.Created, new Dictionary <string, object>()
                    {
                        { "LastInsertedId", res }
                    }));
                }
                catch (Exception ex)
                {
                    scope.Dispose();   //if there are any error, rollback the transaction
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
                }
            }
        }
Пример #44
0
        public int SaveWeavingGriage(PrdWeavingMRRMaster model, vmCmnParameters objcmnParam)
        {
            int result = 0;

            using (TransactionScope transaction = new TransactionScope())
            {
                GFactory_WeavingMRRMaster = new PrdWeavingMRRMaster_EF();
                string CustomNo = string.Empty, WeavingMRRNo = string.Empty;
                try
                {
                    if (model.WeavingMRRID == 0)
                    {
                        Int64 NextId = GFactory_WeavingMRRMaster.getMaxVal_int64("WeavingMRRID", "PrdWeavingMRRMaster");
                        CustomNo = GFactory_WeavingMRRMaster.getCustomCode(objcmnParam.menuId, DateTime.Now, objcmnParam.loggedCompany, 1, 1);
                        if (CustomNo == null || CustomNo == "")
                        {
                            WeavingMRRNo = NextId.ToString();
                        }
                        else
                        {
                            WeavingMRRNo = CustomNo;
                        }

                        model.WeavingMRRID = NextId;
                        model.WeavingMRRNo = WeavingMRRNo;
                        model.IsIssued     = true;
                        model.IsFinishid   = false;
                        model.IsReceived   = false;
                        model.DepartmentID = objcmnParam.DepartmentID;
                        model.StatusID     = objcmnParam.loggeduser;
                        model.CompanyID    = objcmnParam.loggedCompany;
                        model.CreateBy     = objcmnParam.loggeduser;
                        model.CreateOn     = DateTime.Now;
                        model.CreatePc     = HostService.GetIP();

                        GFactory_WeavingMRRMaster.Insert(model);
                        GFactory_WeavingMRRMaster.Save();
                    }
                    else
                    {
                        PrdWeavingMRRMaster _objWeavingMRRMaster = GFactory_WeavingMRRMaster.GetAll().Where(x => x.WeavingMRRID == model.WeavingMRRID).FirstOrDefault();
                        _objWeavingMRRMaster.DoffingNo       = model.DoffingNo;
                        _objWeavingMRRMaster.MachineConfigID = model.MachineConfigID;
                        _objWeavingMRRMaster.ItemID          = model.ItemID;
                        _objWeavingMRRMaster.SetID           = model.SetID;
                        _objWeavingMRRMaster.SizeMRRID       = model.SizeMRRID;
                        _objWeavingMRRMaster.UnitID          = model.UnitID;
                        _objWeavingMRRMaster.ShiftID         = model.ShiftID;
                        _objWeavingMRRMaster.OperatorID      = model.OperatorID;
                        _objWeavingMRRMaster.Qty             = model.Qty;
                        _objWeavingMRRMaster.Remarks         = model.Remarks;

                        _objWeavingMRRMaster.UpdateOn = DateTime.Now;
                        _objWeavingMRRMaster.UpdatePc = HostService.GetIP();
                        _objWeavingMRRMaster.UpdateBy = objcmnParam.loggeduser;

                        GFactory_WeavingMRRMaster.Update(_objWeavingMRRMaster);
                        GFactory_WeavingMRRMaster.Save();
                    }
                    transaction.Complete();
                    result = 1;
                }
                catch (Exception e)
                {
                    e.ToString();
                    result = 0;
                }
            }

            return(result);
        }
Пример #45
0
        public ActionResult UploadUser(FormCollection formCollection)
        {
            if (Request != null)
            {
                CashMeContext      _context = new CashMeContext();
                HttpPostedFileBase file     = Request.Files["UploadedFile"];
                if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                {
                    string fileName        = file.FileName;
                    string fileContentType = file.ContentType;
                    byte[] fileBytes       = new byte[file.ContentLength];
                    var    data            = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
                    using (var package = new ExcelPackage(file.InputStream))
                    {
                        var currentSheet = package.Workbook.Worksheets;
                        var workSheet    = currentSheet.First();
                        var noOfCol      = workSheet.Dimension.End.Column;
                        var noOfRow      = workSheet.Dimension.End.Row;
                        for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
                        {
                            string email         = workSheet.Cells[rowIterator, 1].Value.ToString();
                            string password      = workSheet.Cells[rowIterator, 2].Value.ToString();
                            string SecurityStamp = workSheet.Cells[rowIterator, 3].Value.ToString();
                            string IP            = workSheet.Cells[rowIterator, 4].Value.ToString();
                            string WalletCode    = workSheet.Cells[rowIterator, 5].Value.ToString();
                            int    Ref           = int.Parse(workSheet.Cells[rowIterator, 6].Value.ToString());

                            string username = Regex.Split(email, "@")[0];

                            var user = new ApplicationUser();
                            user.Email                = email;
                            user.PasswordHash         = password;
                            user.SecurityStamp        = SecurityStamp;
                            user.PhoneNumberConfirmed = false;
                            user.TwoFactorEnabled     = false;
                            user.LockoutEnabled       = true;
                            user.AccessFailedCount    = 1;
                            user.UserName             = username;

                            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(_context));
                            var store       = new UserStore <ApplicationUser>(_context);
                            var manager     = new UserManager <ApplicationUser>(store);
                            var existUser   = userManager.Users.FirstOrDefault(aa => aa.Id == user.Id);
                            if (existUser != null)
                            {
                                manager.Update(user);
                                var ctx = store.Context;
                                ctx.SaveChanges();
                                var lstRole = new string[] { DefaultData.RoleUser };
                                var allRole = userManager.GetRoles(existUser.Id).ToArray();
                                if (allRole != null && allRole.Any())
                                {
                                    using (TransactionScope scope = new TransactionScope())
                                    {
                                        userManager.RemoveFromRoles(existUser.Id, allRole);
                                        if (lstRole.Length > 0)
                                        {
                                            var roles    = _roleServices.GetAllRoles().Where(aa => lstRole.Contains(aa.Id));
                                            var rolesAdd = roles.Select(aa => aa.Name).ToArray();
                                            userManager.AddToRoles(existUser.Id, rolesAdd);
                                        }
                                        scope.Complete();
                                    }
                                }
                            }
                            else
                            {
                                manager.Create(user);
                                var ctx = store.Context;

                                userManager.AddToRole(user.Id, DefaultData.RoleUser);
                                ctx.SaveChanges();
                            }
                            var wallet = _walletServices.GetWalletbyCode(WalletCode);
                            var uInfo  = new UserInfo();
                            uInfo.UserId        = user.Id;
                            uInfo.WalletId      = wallet.Id;
                            uInfo.Amount        = (wallet.Claim * 25) + (Ref * 5);
                            uInfo.IP            = IP;
                            uInfo.CreateDate    = DateTime.Now;
                            uInfo.LastLoginDate = DateTime.Now;
                            _userInfoServices.InserUserInfo(uInfo);
                            var claim = new Claims();
                            claim.UserId     = user.Id;
                            claim.CountImage = wallet.Claim;
                            _claimsServices.InserClaims(claim);
                        }
                    }
                }
            }
            return(View("Upload"));
        }
Пример #46
0
 public void BeforeTest(ITest testDetails)
 {
     transaction = new TransactionScope();
 }
        /// <summary>
        /// 批量提交PDA扫描数据
        /// </summary>
        /// <param name="dt">应包含opType、barCode、scanTime、userName等列</param>
        /// <returns>返回:包含“成功”,则调用成功,否则返回调用失败原因</returns>
        public string InsertByBatch(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return("无任何可保存的数据");
            }

            string[] colNames = { "opType", "barCode", "scanTime", "userName" };

            DataColumnCollection cols = dt.Columns;

            foreach (DataColumn col in cols)
            {
                if (!colNames.Contains(col.ColumnName))
                {
                    return("检测到提交的数据集中未包含" + col.ColumnName + "列");
                }
            }

            DataRowCollection rows = dt.Rows;

            List <PDAOrderScanDetailInfo> osdList = new List <PDAOrderScanDetailInfo>();

            //定义非重复的用户名、用户ID
            Dictionary <string, object> dicUser = new Dictionary <string, object>();

            try
            {
                SysEnum seBll  = new SysEnum();
                var     seList = seBll.GetList("and t2.EnumCode = 'SendReceiveType'", null);
                if (seList == null || seList.Count == 0)
                {
                    return("服务端的操作类型未设定,请先完成设定");
                }
                var firstModel = seList.OrderBy(m => m.Sort).First();

                foreach (DataRow row in rows)
                {
                    string opType = "";
                    if (row["opType"] != DBNull.Value)
                    {
                        opType = row["opType"].ToString();
                    }
                    else
                    {
                        return("操作类型不能为空");
                    }

                    var seModel = seList.Find(m => m.EnumValue.Trim() == opType.Trim());
                    if (seModel == null)
                    {
                        return("不存在操作类型:" + opType);
                    }

                    string barCode = "";
                    if (row["barCode"] != DBNull.Value)
                    {
                        barCode = row["barCode"].ToString();
                    }
                    DateTime scanTime = DateTime.MinValue;
                    if (row["scanTime"] != DBNull.Value)
                    {
                        DateTime.TryParse(row["scanTime"].ToString(), out scanTime);
                    }
                    if (scanTime == DateTime.MinValue)
                    {
                        return("数据集中包含不合法数据:scanTime值格式不正确");
                    }

                    string userName = "";
                    if (row["userName"] != DBNull.Value)
                    {
                        userName = row["userName"].ToString();
                    }
                    if (string.IsNullOrEmpty(userName))
                    {
                        return("数据集中包含用户名为空");
                    }

                    if (!dicUser.ContainsKey(userName))
                    {
                        dicUser.Add(userName, Guid.Empty);
                    }

                    osdList.Add(new PDAOrderScanDetailInfo {
                        OrderCode = barCode, CurrNodeId = seModel.Id, ScanTime = scanTime, Remark = seModel.Remark, Sort = seModel.Sort, LastUpdatedDate = DateTime.Now, UserName = userName, SysEnumValue = opType
                    });
                }

                TyUser tyuBll = new TyUser();

                foreach (KeyValuePair <string, object> kvp in dicUser)
                {
                    MembershipUser user = Membership.GetUser(kvp.Key, false);
                    if (user == null)
                    {
                        return("不存在用户:" + kvp.Key);
                    }

                    TyUserInfo tyuModel = tyuBll.GetModelByUser(user.UserName);

                    var currList = osdList.FindAll(m => m.UserName == kvp.Key);
                    foreach (var item in currList)
                    {
                        item.UserId = user.ProviderUserKey;

                        string sRemark = "";
                        if (tyuModel != null && !string.IsNullOrWhiteSpace(tyuModel.OrganizationName))
                        {
                            sRemark = string.Format(item.Remark, tyuModel.OrganizationName);
                        }
                        else
                        {
                            sRemark = item.Remark.Replace(@"{0}", "");
                        }
                        sRemark = item.SysEnumValue + ":" + sRemark;

                        item.Remark = sRemark;
                    }
                }

                PDAOrderScan       osBll  = new PDAOrderScan();
                PDAOrderScanDetail osdBll = new PDAOrderScanDetail();
                Order   oBll   = new Order();
                SmsSend smsBll = new SmsSend();

                var q = osdList.OrderBy(m => m.Sort);
                foreach (var item in q)
                {
                    object nextNodeId  = Guid.Empty;
                    var    currSeModel = seList.Find(m => m.EnumValue.Trim() == item.SysEnumValue);
                    var    nextSeModel = seList.FindAll(m => m.Sort > item.Sort).OrderBy(m => m.Sort).FirstOrDefault();
                    if (nextSeModel == null)
                    {
                        nextNodeId = item.CurrNodeId;
                    }
                    else
                    {
                        nextNodeId = nextSeModel.Id;
                    }
                    var  lastSeModel = seList.OrderByDescending(m => m.Sort).First();
                    bool isFinish    = lastSeModel.EnumValue.Trim() == item.SysEnumValue;

                    bool isOsdExists = false;

                    PDAOrderScanInfo currOsModel = new PDAOrderScanInfo();
                    currOsModel.OrderCode       = item.OrderCode;
                    currOsModel.CurrNodeId      = item.CurrNodeId;
                    currOsModel.NextNodeId      = nextNodeId;
                    currOsModel.IsFinish        = isFinish;
                    currOsModel.LastUpdatedDate = DateTime.Now;

                    PDAOrderScanDetailInfo currOsdModel = new PDAOrderScanDetailInfo();
                    currOsdModel.OrderCode       = item.OrderCode;
                    currOsdModel.CurrNodeId      = item.CurrNodeId;
                    currOsdModel.ScanTime        = item.ScanTime;
                    currOsdModel.UserId          = item.UserId;
                    currOsdModel.LastUpdatedDate = currOsModel.LastUpdatedDate;
                    currOsdModel.Remark          = item.Remark;

                    if (item.SysEnumValue == "干线发运" || item.SysEnumValue == "干线到达")
                    {
                        var orders = oBll.GetOrderByCarcode(item.OrderCode);
                        if (orders == null || orders.Count() == 0)
                        {
                            return("操作类型:" + item.SysEnumValue + "找不到订单号,有错误");
                        }

                        foreach (var currOrderCode in orders)
                        {
                            currOsModel.OrderCode  = currOrderCode;
                            currOsdModel.OrderCode = currOrderCode;

                            var oldOsdList = osdBll.GetList(currOrderCode);
                            if (oldOsdList != null)
                            {
                                isOsdExists = oldOsdList.Exists(m => m.CurrNodeId.Equals(item.CurrNodeId));
                            }

                            if (!isOsdExists)
                            {
                                SmsSendInfo ssiModel = new SmsSendInfo();
                                ssiModel.OrderCode    = currOrderCode;
                                ssiModel.TranNode     = currSeModel.EnumCode;
                                ssiModel.TranNodeText = currSeModel.EnumValue;

                                using (TransactionScope scope = new TransactionScope())
                                {
                                    if (osBll.GetModel(currOrderCode) == null)
                                    {
                                        osBll.Insert(currOsModel);
                                    }
                                    else
                                    {
                                        osBll.Update(currOsModel);
                                    }

                                    osdBll.Insert(currOsdModel);

                                    scope.Complete();
                                }

                                smsBll.InsertByStrategy(ssiModel);
                            }
                        }
                    }
                    else if (item.Sort == firstModel.Sort)
                    {
                        var oldOsModel = osBll.GetModel(item.OrderCode);
                        if (oldOsModel == null)
                        {
                            SmsSendInfo ssiModel = new SmsSendInfo();
                            ssiModel.OrderCode    = item.OrderCode;
                            ssiModel.TranNode     = currSeModel.EnumCode;
                            ssiModel.TranNodeText = currSeModel.EnumValue;

                            using (TransactionScope scope = new TransactionScope())
                            {
                                osBll.Insert(currOsModel);
                                osdBll.Insert(currOsdModel);

                                scope.Complete();
                            }

                            smsBll.InsertByStrategy(ssiModel);
                        }
                    }
                    else
                    {
                        var oldOsModel = osBll.GetModel(item.OrderCode);
                        if (oldOsModel == null)
                        {
                            return("订单号:" + item.OrderCode + ",操作类型:" + item.SysEnumValue + "未取货,有错误");
                        }

                        var oldOsdList = osdBll.GetList(item.OrderCode);
                        if (oldOsdList != null)
                        {
                            isOsdExists = oldOsdList.Exists(m => m.CurrNodeId.Equals(item.CurrNodeId));

                            currOsModel.IsFinish = oldOsdList.Count == 5;
                        }

                        if (currOsModel.IsFinish)
                        {
                            continue;
                        }

                        if (!isOsdExists)
                        {
                            SmsSendInfo ssiModel = new SmsSendInfo();
                            ssiModel.OrderCode    = currOsModel.OrderCode;
                            ssiModel.TranNode     = currSeModel.EnumCode;
                            ssiModel.TranNodeText = currSeModel.EnumValue;

                            using (TransactionScope scope = new TransactionScope())
                            {
                                osBll.Update(currOsModel);

                                osdBll.Insert(currOsdModel);

                                scope.Complete();
                            }

                            smsBll.InsertByStrategy(ssiModel);
                        }
                    }

                    Console.WriteLine("request: opType:{0},barCode:{1},scanTime:{3},user:{2}", item.SysEnumValue, item.OrderCode, item.ScanTime, item.UserName);
                }

                return("保存成功");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
        /// <summary>
        /// 新增PDA扫描数据
        /// </summary>
        /// <param name="opType">操作类型</param>
        /// <param name="barCode">单号条码</param>
        /// <param name="scanTime">扫描时间</param>
        /// <param name="userName">用户名</param>
        /// <returns>返回:包含“成功”,则调用成功,否则返回调用失败原因</returns>
        public string Insert(string opType, string barCode, DateTime scanTime, string userName)
        {
            #region 参数合法性检查

            if (string.IsNullOrEmpty(opType))
            {
                return("操作类型不能为空");
            }
            opType = opType.Trim();
            if (string.IsNullOrEmpty(barCode))
            {
                return("单号条码不能为空");
            }
            barCode = barCode.Trim();
            //if (barCode.Length != 13)
            //{
            //    return "单号条码不正确";
            //}

            if (scanTime == DateTime.MinValue)
            {
                return("扫描时间格式不正确");
            }

            if (string.IsNullOrEmpty(userName))
            {
                return("用户不能为空");
            }

            #endregion

            try
            {
                MembershipUser user = Membership.GetUser(userName);
                if (user == null)
                {
                    return("不存在用户:" + userName);
                }

                SysEnum seBll  = new SysEnum();
                var     seList = seBll.GetList("and t2.EnumCode = 'SendReceiveType'", null);
                if (seList == null || seList.Count == 0)
                {
                    return("服务端的操作类型未设定,请先完成设定");
                }

                var firstModel  = seList.OrderBy(m => m.Sort).First();
                var currSeModel = seList.Find(m => m.EnumValue.Trim() == opType);
                if (currSeModel == null)
                {
                    return("当前操作类型“" + opType + "”不存在");
                }

                object nextNodeId  = Guid.Empty;
                var    nextSeModel = seList.FindAll(m => m.Sort > currSeModel.Sort).OrderBy(m => m.Sort).FirstOrDefault();
                if (nextSeModel == null)
                {
                    nextNodeId = currSeModel.Id;
                }
                else
                {
                    nextNodeId = nextSeModel.Id;
                }

                bool isOsdExists = false;

                PDAOrderScanInfo currOsModel = new PDAOrderScanInfo();
                currOsModel.OrderCode       = barCode;
                currOsModel.CurrNodeId      = currSeModel.Id;
                currOsModel.NextNodeId      = nextNodeId;
                currOsModel.IsFinish        = false;
                currOsModel.LastUpdatedDate = DateTime.Now;

                PDAOrderScanDetailInfo currOsdModel = new PDAOrderScanDetailInfo();
                currOsdModel.OrderCode       = barCode;
                currOsdModel.CurrNodeId      = currOsModel.CurrNodeId;
                currOsdModel.ScanTime        = scanTime;
                currOsdModel.UserId          = user.ProviderUserKey;
                currOsdModel.LastUpdatedDate = currOsModel.LastUpdatedDate;

                Order              oBll   = new Order();
                PDAOrderScan       osBll  = new PDAOrderScan();
                PDAOrderScanDetail osdBll = new PDAOrderScanDetail();
                TyUser             tyuBll = new TyUser();
                SmsSend            smsBll = new SmsSend();

                string     sRemark  = "";
                TyUserInfo tyuModel = tyuBll.GetModelByUser(user.UserName);
                if (tyuModel != null && !string.IsNullOrWhiteSpace(tyuModel.OrganizationName))
                {
                    sRemark = string.Format(currSeModel.Remark, tyuModel.OrganizationName);
                }
                else
                {
                    sRemark = currSeModel.Remark.Replace(@"{0}", "");
                }
                sRemark = currSeModel.EnumValue + ":" + sRemark;

                currOsdModel.Remark = sRemark;

                if (opType == "干线发运" || opType == "干线到达")
                {
                    var orders = oBll.GetOrderByCarcode(barCode);
                    if (orders == null || orders.Count() == 0)
                    {
                        return("操作类型:" + barCode + "找不到订单号,有错误");
                    }

                    foreach (var currOrderCode in orders)
                    {
                        currOsModel.OrderCode  = currOrderCode;
                        currOsdModel.OrderCode = currOrderCode;

                        var oldOsdList = osdBll.GetList(currOrderCode);
                        if (oldOsdList != null)
                        {
                            isOsdExists = oldOsdList.Exists(m => m.CurrNodeId.Equals(currSeModel.Id));
                        }

                        if (isOsdExists)
                        {
                            return("订单号:" + currOrderCode + " 操作类型:" + opType + "已存在,不能重复提交");
                        }

                        //发短信
                        SmsSendInfo ssiModel = new SmsSendInfo();
                        ssiModel.OrderCode    = currOrderCode;
                        ssiModel.TranNode     = currSeModel.EnumCode;
                        ssiModel.TranNodeText = currSeModel.EnumValue;

                        using (TransactionScope scope = new TransactionScope())
                        {
                            if (osBll.GetModel(currOrderCode) == null)
                            {
                                osBll.Insert(currOsModel);
                            }
                            else
                            {
                                osBll.Update(currOsModel);
                            }

                            osdBll.Insert(currOsdModel);

                            scope.Complete();
                        }

                        smsBll.InsertByStrategy(ssiModel);
                    }
                }

                else if (currSeModel.Sort == firstModel.Sort)
                {
                    var oldOsModel = osBll.GetModel(barCode);
                    if (oldOsModel != null)
                    {
                        return("订单号:" + barCode + ",操作类型:" + opType + "已存在,不能重复提交");
                    }

                    SmsSendInfo ssiModel = new SmsSendInfo();
                    ssiModel.OrderCode    = barCode;
                    ssiModel.TranNode     = currSeModel.EnumCode;
                    ssiModel.TranNodeText = currSeModel.EnumValue;

                    using (TransactionScope scope = new TransactionScope())
                    {
                        osBll.Insert(currOsModel);
                        osdBll.Insert(currOsdModel);

                        scope.Complete();
                    }

                    smsBll.InsertByStrategy(ssiModel);
                }
                else
                {
                    var oldOsModel = osBll.GetModel(barCode);
                    if (oldOsModel == null)
                    {
                        return("订单号:" + barCode + ",操作类型:" + opType + "未取货,有错误");
                    }

                    var oldOsdList = osdBll.GetList(barCode);
                    if (oldOsdList != null)
                    {
                        isOsdExists = oldOsdList.Exists(m => m.CurrNodeId.Equals(currSeModel.Id));

                        currOsModel.IsFinish = oldOsdList.Count == 5;
                    }

                    if (currOsModel.IsFinish)
                    {
                        return("订单号:" + barCode + "已完成所有操作");
                    }

                    if (isOsdExists)
                    {
                        return("订单号:" + barCode + ",操作类型:" + opType + "已存在,不能重复提交");
                    }

                    SmsSendInfo ssiModel = new SmsSendInfo();
                    ssiModel.OrderCode    = barCode;
                    ssiModel.TranNode     = currSeModel.EnumCode;
                    ssiModel.TranNodeText = currSeModel.EnumValue;

                    using (TransactionScope scope = new TransactionScope())
                    {
                        osBll.Update(currOsModel);

                        osdBll.Insert(currOsdModel);

                        scope.Complete();
                    }

                    smsBll.InsertByStrategy(ssiModel);
                }

                Console.WriteLine("request: opType:{0},barCode:{1},scanTime:{3},user:{2}", opType, barCode, scanTime, userName);

                return("保存成功");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Пример #49
0
        public async Task <ExecutionResult> Execute()
        {
            log($"SQL Continuous Delivery start");

            var path = _command.Path;

            log($"Path: {path}");

            // 1. get newest version from repository
            log($"get newest version from repository");
            var newest = _repository.GetNewestCommit(path);

            // 2. get latest version from db
            // database preparation
            log($"database preparation start");
            await _dbPrepare.Prepare();

            log($"database preparation finish");

            log($"get last version from database");
            var latestSqlVersion = await _dbNegotiator.GetLatestSqlVersion();

            var latest = RepositoryVersion.GetRepositoryVersion(latestSqlVersion);

            // 3. get changed(added, modified) files from repository
            log($"get changed(added, modified) files");
            var changedFiles = _repository.GetChangedFiles(path, newest, latest);

            // 4. exclude ignored files
            log($"exclude ignored files");
            _sqlSelector.Exclude(_sqlIgnoreConfiguration, ref changedFiles);

            // 5. sort files
            log($"sort files");
            _sqlSelector.Sort(_sqlOrderConfiguration, ref changedFiles);

            // 6. delivery to database
            try
            {
                var scripts = await Task.WhenAll(changedFiles
                                                 .Where(file => file.ToLower().EndsWith(".sql"))
                                                 .Select(async file => await _fileReader.GetContentAsync($"{_command.Path}/{file}"))
                                                 .ToList());

                if (!scripts.Any())
                {
                    goto endCommand;
                }

                using (var trans = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    // execute all scripts
                    var beginTime = TimeUtility.Now;
                    log($"delivery start at {beginTime}");
                    foreach (var script in scripts)
                    {
                        log($"delivery for {string.Concat(script.Take(20))}...");
                        await _dbNegotiator.Execute(script);
                    }

                    var endTime = TimeUtility.Now;
                    log($"delivery end at {endTime}");

                    // insert delivery record
                    log($"insert delivery record");
                    // 1.get the latest version
                    var preVersion = await _dbNegotiator.GetLatestSqlVersion();

                    // 2.update all other records.IsLatest = false
                    await _dbNegotiator.SetAllNonLatest();

                    // 3.insert sv
                    var sv = new SqlVersion(_baseConfiguration.RepositoryType, newest.Version,
                                            (endTime - beginTime).TotalMilliseconds)
                    {
                        IsLatest = true, LastVersion = preVersion?.Id
                    };
                    await _dbNegotiator.InsertSqlVersion(sv);

                    trans.Complete();
                }

endCommand:
                log($"SQL Continuous Delivery finish");
                return(new ExecutionResult()
                {
                    Success = true,
                    ErrorMessage = string.Empty
                });
            }
            catch (Exception ex)
            {
                return(new ExecutionResult()
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }
        }
Пример #50
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            if (BillingAddressSameRadio.Checked)
            {
                ListItem itemAlreadySelectedState = StateDropDown.Items.FindByValue(StateIdHidden.Value);
                if (itemAlreadySelectedState != null)
                {
                    itemAlreadySelectedState.Selected = true;
                }
                CityText.Text     = CityHidden.Value;
                ZipText.Text      = ZipHidden.Value;
                Address1Text.Text = Address1Hidden.Value;
            }

            bool isStatusUpdated = false;

            TotalAmountPayable = 0.0m;
            var selectedRows = GetSelectedRows();

            try
            {
                using (var transaction = new TransactionScope())
                {
                    if (PaymentMode.SelectedValue != PaymentType.CreditCard.PersistenceLayerId.ToString() ||
                        AddressValidation())
                    {
                        foreach (var row in selectedRows)
                        {
                            if (row == null)
                            {
                                continue;
                            }

                            var orderDetailIdLiteral    = row.FindControl("OrderDetailIdLiteral") as Literal;
                            var shippingDetailIdLiteral = row.FindControl("ShippingDetailIdLiteral") as Literal;
                            var actualPrice             = row.FindControl("PriceLabel") as Label;

                            if (orderDetailIdLiteral != null && shippingDetailIdLiteral != null)
                            {
                                var orderDetailId    = Convert.ToInt64(orderDetailIdLiteral.Text);
                                var shippingDetailId = Convert.ToInt64(shippingDetailIdLiteral.Text);

                                isStatusUpdated = _shippingDetailOrderDetailRepository.UpdateStatus(shippingDetailId, orderDetailId, false);

                                var shippingDetail = _shippingDetailRepository.GetById(shippingDetailId);
                                shippingDetail.Status = ShipmentStatus.Cancelled;
                                _shippingDetailRepository.Save(shippingDetail);

                                var resultShippingDetails  = _shippingDetailRepository.GetShippingDetailsForCancellation(orderDetailId).ToList();
                                var productShippingDetails = _shippingDetailRepository.GetProductShippingDetailsForCancellation(orderDetailId).ToList();
                                if (productShippingDetails.Count > resultShippingDetails.Count)
                                {
                                    var productShippingDetail = productShippingDetails.FirstOrDefault();
                                    if (productShippingDetail != null)
                                    {
                                        _shippingDetailOrderDetailRepository.UpdateStatus(productShippingDetail.Id, orderDetailId, false);
                                        productShippingDetail.Status = ShipmentStatus.Cancelled;
                                        _shippingDetailRepository.Save(productShippingDetail);
                                        CheckEventCustomerResultStateAndDeleteCdGenTrackRecord();
                                    }
                                }

                                if (actualPrice != null && !string.IsNullOrEmpty(actualPrice.Text))
                                {
                                    TotalAmountPayable += Convert.ToDecimal(actualPrice.Text);
                                }
                            }
                        }

                        if (AmountPaid < (DiscountedTotal - TotalAmountPayable))
                        {
                            TotalAmountPayable = 0;
                        }
                        else
                        {
                            TotalAmountPayable = AmountPaid - (DiscountedTotal - TotalAmountPayable);
                        }

                        var isRefundQueueEnabled = IoC.Resolve <ISettings>().IsRefundQueueEnabled;

                        if (PaymentMode.SelectedValue == PaymentType.CreditCard.PersistenceLayerId.ToString() &&
                            BillingAddressDifferentRadio.Checked && !isRefundQueueEnabled)
                        {
                            var creatorOrganizationRoleUser = GetCreatorOrganizationRoleUser();
                            UpdateCustomerBillingAddress(creatorOrganizationRoleUser.Id);
                        }

                        if (isStatusUpdated)
                        {
                            if (TotalAmountPayable > 0)
                            {
                                if (isRefundQueueEnabled)
                                {
                                    var refundRequest          = PrepareRefundRequestObject();
                                    var refundRequestValidator = IoC.Resolve <RefundRequestEditModelValidator>();
                                    var result = refundRequestValidator.Validate(refundRequest);
                                    if (result.IsValid)
                                    {
                                        IoC.Resolve <IRefundRequestService>().SaveRequest(refundRequest);
                                    }
                                    else
                                    {
                                        var propertyNames = result.Errors.Select(er => er.PropertyName).Distinct();
                                        var htmlString    = propertyNames.Aggregate("", (current, property) => current + (result.Errors.Where(er => er.PropertyName == property).FirstOrDefault().ErrorMessage + "&nbsp;&nbsp;"));
                                        MessageBox.ShowErrorMessage(htmlString);
                                        return;
                                    }
                                }
                                else
                                {
                                    var creatorOrganizationRoleUser = GetCreatorOrganizationRoleUser();
                                    var paymentInstrument           = RefundPayment(creatorOrganizationRoleUser,
                                                                                    OrderId + "_" + CustomerId);
                                    if (paymentInstrument != null &&
                                        ApplyPaymentToOrder(creatorOrganizationRoleUser, CurrentOrder, paymentInstrument))
                                    {
                                        transaction.Complete();
                                        Response.RedirectUser(ReturnUrl);
                                    }
                                    else
                                    {
                                        SetAndDisplayErrorMessage("Oops some error occured in the system please try again later.");
                                    }
                                }
                            }
                            transaction.Complete();
                            if (UrlValidator.IsUrlLocalToHost(Request, ReturnUrl))
                            {
                                Response.RedirectUser(ReturnUrl);
                            }
                        }
                        else
                        {
                            SetAndDisplayErrorMessage("Oops some error occured in the system please try again later.");
                        }
                    }
                }
            }
            catch (InvalidOperationException)
            {
            }
            catch { SetAndDisplayErrorMessage("Oops some error occured in the system please try again later."); }
        }
 public SqlServerClubRepositoryTests(SqlServerTestDataFixture databaseFixture)
 {
     _databaseFixture = databaseFixture ?? throw new ArgumentNullException(nameof(databaseFixture));
     _scope           = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
 }
Пример #52
0
 public void MyTestInitialize()
 {
     transaction = new TransactionScope();
 }
Пример #53
0
        public HttpResponseMessage AddMidEvaluationJury(Object MidEvaluation)
        {
            var test = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(Convert.ToString(MidEvaluation));

            object FypID;

            test.TryGetValue("FypID", out FypID);
            int _FypID = Convert.ToInt32(FypID);

            object FormID;

            test.TryGetValue("FormID", out FormID);
            int _FormID = Convert.ToInt32(FormID);

            object ProjectProgress;

            test.TryGetValue("ProjectProgress", out ProjectProgress);
            int _ProjectProgress = Convert.ToInt32(ProjectProgress);

            object DocumentationStatus;

            test.TryGetValue("DocumentationStatus", out DocumentationStatus);
            int _DocumentationStatus = Convert.ToInt32(DocumentationStatus);

            object ProgressComments;

            test.TryGetValue("ProgressComments", out ProgressComments);
            string _ProgressComments = Convert.ToString(ProgressComments);

            object LeaderID;

            test.TryGetValue("LeaderID", out LeaderID);
            int _LeaderID = Convert.ToInt32(LeaderID);

            object Member1ID;

            test.TryGetValue("Member1ID", out Member1ID);
            int _Member1ID = Convert.ToInt32(Member1ID);

            object Member2ID;

            test.TryGetValue("Member2ID", out Member2ID);
            int _Member2ID = Convert.ToInt32(Member2ID);

            var db = DbUtils.GetDBConnection();

            db.Connection.Open();

            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    var res = db.Query("FypEvaluation").InsertGetId <int>(new
                    {
                        FypID  = _FypID,
                        FormID = _FormID,

                        ProjectProgress     = _ProjectProgress,
                        DocumentationStatus = _DocumentationStatus,
                        ProgressComments    = _ProgressComments
                    });

                    var totalMarks = _ProjectProgress + _DocumentationStatus;

                    db.Query("FypMarks").Insert(new
                    {
                        StudentID = _LeaderID,
                        FormID    = 3,
                        Marks     = totalMarks
                    });

                    db.Query("FypMarks").Insert(new
                    {
                        StudentID = _Member1ID,
                        FormID    = 3,
                        Marks     = totalMarks
                    });

                    db.Query("FypMarks").Insert(new
                    {
                        StudentID = _Member2ID,
                        FormID    = 3,
                        Marks     = totalMarks
                    });

                    scope.Complete();
                    db.Connection.Close();
                    return(Request.CreateResponse(HttpStatusCode.Created, new Dictionary <string, object>()
                    {
                        { "LastInsertedId", res }
                    }));
                }
                catch (Exception ex)
                {
                    scope.Dispose();
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
                }
            }
        }
Пример #54
0
        public ActionResult UpdateOutboundReason(List <String> dynamic_select, List <string> txtDN, List <string> txtRemark)
        {
            using (TransactionScope Trans = new TransactionScope())
            {
                try
                {
                    //Write to Adjested table
                    int countDN = 0;
                    for (int i = 0; i < dynamic_select.Count; i++)
                    {
                        if (!String.IsNullOrEmpty(dynamic_select[i]))
                        {
                            string dn         = txtDN[i];
                            string reasonId   = dynamic_select[i];
                            string remark     = txtRemark[i];
                            string reasonName = objBs.reasonOutboundBs.GetByID(Convert.ToInt32(reasonId)).Name;
                            bool   isadjust   = objBs.reasonOutboundBs.GetByID(Convert.ToInt32(reasonId)).IsAdjust;

                            DWH_ONTIME_DN ontimeDn = objBs.dWH_ONTIME_DNBs.GetByID(dn);
                            ontimeDn.OUTB_ADJUST      = isadjust ? 0 : 0;
                            ontimeDn.OUTB_ADJUST_BY   = User.Identity.Name;
                            ontimeDn.OUTB_ADJUST_DATE = DateTime.Now;
                            ontimeDn.OUTB_REASON      = reasonName;
                            ontimeDn.OUTB_REASON_ID   = Convert.ToInt32(reasonId);
                            ontimeDn.OUTB_REMARK      = remark;

                            objBs.dWH_ONTIME_DNBs.Update(ontimeDn);

                            OutboundDelay tmp_adjusted = new OutboundDelay();
                            tmp_adjusted = objBs.outboundDelayBs.GetByID(dn);
                            if (tmp_adjusted == null)
                            {
                                return(Json("DN " + dn + " ได้ทำการ adjust ไปแล้ว"));
                            }
                            OutboundAdjusted tmp_toInsert = new OutboundAdjusted
                            {
                                CARRIER_ID       = tmp_adjusted.CARRIER_ID,
                                DEPARTMENT_ID    = tmp_adjusted.DEPARTMENT_ID,
                                DEPARTMENT_NAME  = tmp_adjusted.DEPARTMENT_NAME,
                                SECTION_ID       = tmp_adjusted.SECTION_ID,
                                SECTION_NAME     = tmp_adjusted.SECTION_NAME,
                                MATFRIGRP        = tmp_adjusted.MATFRIGRP,
                                MATNAME          = tmp_adjusted.MATNAME,
                                REGION_ID        = tmp_adjusted.REGION_ID,
                                REGION_NAME_EN   = tmp_adjusted.REGION_NAME_EN,
                                REGION_NAME_TH   = tmp_adjusted.REGION_NAME_TH,
                                SOLDTO           = tmp_adjusted.SOLDTO,
                                SOLDTO_NAME      = tmp_adjusted.SOLDTO_NAME,
                                SHIPTO           = tmp_adjusted.SHIPTO,
                                SEGMENT          = tmp_adjusted.SEGMENT,
                                SUBSEGMENT       = tmp_adjusted.SUBSEGMENT,
                                TO_SHPG_LOC_NAME = tmp_adjusted.TO_SHPG_LOC_NAME,
                                VENDOR_CODE      = tmp_adjusted.VENDOR_CODE,
                                VENDOR_NAME      = tmp_adjusted.VENDOR_NAME,
                                PLNOUTBDATE      = tmp_adjusted.PLNOUTBDATE,
                                PLNOUTBDATE_D    = tmp_adjusted.PLNOUTBDATE_D,
                                ACDLVDATE        = tmp_adjusted.ACDLVDATE,
                                ACDLVDATE_D      = tmp_adjusted.ACDLVDATE_D,
                                ACTGIDATE        = tmp_adjusted.ACTGIDATE,
                                ACTGIDATE_D      = tmp_adjusted.ACTGIDATE_D,
                                SHPPOINT         = tmp_adjusted.SHPPOINT,
                                TRUCK_TYPE       = tmp_adjusted.TRUCK_TYPE,
                                DELVNO           = tmp_adjusted.DELVNO,
                                SHPMNTNO         = tmp_adjusted.SHPMNTNO,
                                LOADED_DATE      = DateTime.Now,
                                OUTB_ADJUST      = isadjust ? 1 : 0,
                                OUTB_ADJUST_BY   = User.Identity.Name,
                                OUTB_ADJUST_DATE = DateTime.Now,
                                OUTB_REASON      = reasonName,
                                OUTB_REASON_ID   = Convert.ToInt32(reasonId),
                                OUTB_REMARK      = remark
                            };
                            //insert waiting for approval
                            objBs.outboundAdjustedBs.Insert(tmp_toInsert);
                            //delete OntimeDelays
                            objBs.outboundDelayBs.Delete(dn);

                            countDN++;
                        }
                    }

                    Trans.Complete();
                    return(RedirectToAction("Index", new { sms = countDN + "-DN is adjusted Successfully!" }));
                }
                catch (Exception ex)
                {
                    return(RedirectToAction("Index", new { sms = "Operation update reason accepted failed !" + ex.InnerException.InnerException.Message.ToString() }));
                }
            }
        }
Пример #55
0
 public TransactionScopeWrapper()
 {
     m_Scope = TransactionScopeFactory.CreateTransactionScope();
 }
Пример #56
0
        public ContentResult UploadReason()
        {
            using (TransactionScope Trans = new TransactionScope())
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    string errorRef = "";

                    string             reference  = Request.Files.AllKeys[i];
                    HttpPostedFileBase FileUpload = Request.Files[i]; //Uploaded file
                                                                      //Use the following properties to get file's name, size and MIMEType
                    string fileName   = reference;
                    string targetpath = Server.MapPath("~/Content/Docs/outb/");
                    FileUpload.SaveAs(targetpath + DateTime.Now.ToString("yyyyMMddHHmm", new CultureInfo("th-TH")) + "_adjust.xlsx");
                    string pathToExcelFile = targetpath + DateTime.Now.ToString("yyyyMMddHHmm", new CultureInfo("th-TH")) + "_adjust.xlsx";
                    var    ext             = Path.GetExtension(pathToExcelFile);

                    int countDN = 0;

                    //if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                    if (ext == ".xlsx")
                    {
                        DataTable dT = ExcelModels.openExcel(pathToExcelFile, 1);
                        try
                        {
                            foreach (DataRow dr in dT.Rows)
                            {
                                //Do record adjust data - send to approval
                                if (!String.IsNullOrEmpty(dr[0].ToString()))
                                {
                                    string dn         = dr[0].ToString();
                                    int    reasonId   = Convert.ToInt32(dr[14].ToString());
                                    string remark     = dr[15].ToString();
                                    string reasonName = objBs.reasonOutboundBs.GetByID(reasonId).Name;
                                    bool   isadjust   = objBs.reasonOutboundBs.GetByID(Convert.ToInt32(reasonId)).IsAdjust;

                                    DWH_ONTIME_DN ontimeDn = objBs.dWH_ONTIME_DNBs.GetByID(dn);
                                    ontimeDn.INB_ADJUST      = isadjust ? 0 : 0;
                                    ontimeDn.INB_ADJUST_BY   = User.Identity.Name;
                                    ontimeDn.INB_ADJUST_DATE = DateTime.Now;
                                    ontimeDn.INB_REASON      = reasonName;
                                    ontimeDn.INB_REASON_ID   = Convert.ToInt32(reasonId);
                                    ontimeDn.INB_REMARK      = remark;

                                    objBs.dWH_ONTIME_DNBs.Update(ontimeDn);

                                    InboundDelay tmp_adjusted = objBs.inboundDelayBs.GetByID(dn);
                                    if (tmp_adjusted == null)
                                    {
                                        errorRef = errorRef + dn + " , ";
                                    }
                                    else
                                    {
                                        InboundAdjusted tmp_toInsert = new InboundAdjusted
                                        {
                                            CARRIER_ID       = tmp_adjusted.CARRIER_ID,
                                            DEPARTMENT_ID    = tmp_adjusted.DEPARTMENT_ID,
                                            DEPARTMENT_NAME  = tmp_adjusted.DEPARTMENT_NAME,
                                            SECTION_ID       = tmp_adjusted.SECTION_ID,
                                            SECTION_NAME     = tmp_adjusted.SECTION_NAME,
                                            MATFRIGRP        = tmp_adjusted.MATFRIGRP,
                                            MATNAME          = tmp_adjusted.MATNAME,
                                            REGION_ID        = tmp_adjusted.REGION_ID,
                                            REGION_NAME_EN   = tmp_adjusted.REGION_NAME_EN,
                                            REGION_NAME_TH   = tmp_adjusted.REGION_NAME_TH,
                                            SOLDTO           = tmp_adjusted.SOLDTO,
                                            SOLDTO_NAME      = tmp_adjusted.SOLDTO_NAME,
                                            SHIPTO           = tmp_adjusted.SHIPTO,
                                            SEGMENT          = tmp_adjusted.SEGMENT,
                                            SUBSEGMENT       = tmp_adjusted.SUBSEGMENT,
                                            TO_SHPG_LOC_NAME = tmp_adjusted.TO_SHPG_LOC_NAME,
                                            VENDOR_CODE      = tmp_adjusted.VENDOR_CODE,
                                            VENDOR_NAME      = tmp_adjusted.VENDOR_NAME,
                                            LTNRDDATE        = tmp_adjusted.LTNRDDATE,
                                            LTNRDDATE_D      = tmp_adjusted.LTNRDDATE_D,
                                            PLNINBDATE       = tmp_adjusted.PLNINBDATE,
                                            PLNINBDATE_D     = tmp_adjusted.PLNINBDATE_D,
                                            ACTGIDATE        = tmp_adjusted.ACTGIDATE,
                                            ACTGIDATE_D      = tmp_adjusted.ACTGIDATE_D,
                                            SHPPOINT         = tmp_adjusted.SHPPOINT,
                                            TRUCK_TYPE       = tmp_adjusted.TRUCK_TYPE,
                                            DELVNO           = tmp_adjusted.DELVNO,
                                            SHPMNTNO         = tmp_adjusted.SHPMNTNO,
                                            LOADED_DATE      = DateTime.Now,
                                            INB_ADJUST       = isadjust ? 1 : 0,
                                            INB_ADJUST_BY    = User.Identity.Name,
                                            INB_ADJUST_DATE  = DateTime.Now,
                                            INB_REASON       = reasonName,
                                            INB_REASON_ID    = Convert.ToInt32(reasonId),
                                            INB_REMARK       = remark
                                        };
                                        //insert waiting for approval
                                        objBs.inboundAdjustedBs.Insert(tmp_toInsert);
                                        //delete AcceptedDelays
                                        objBs.inboundDelayBs.Delete(dn);

                                        countDN++;
                                    }
                                }
                            }
                            Trans.Complete();
                            if (errorRef != "")
                            {
                                errorRef = "<div style='overflow:auto'> DN หมายเลข " + errorRef + "ได้ทำการ adjust ไปแล้ว </div>";
                            }
                            return(Content("อัพโหลดสำเร็จ " + countDN + " DN" + "<br>" + errorRef));
                        }
                        catch (Exception e)
                        {
                            return(Content("อัพโหลดไม่สำเร็จ กรอกข้อมูลไม่ถูกต้อง"));
                        }
                    }
                    //deleting excel file from folder
                    if ((System.IO.File.Exists(pathToExcelFile)))
                    {
                        System.IO.File.Delete(pathToExcelFile);
                    }
                }
            }
            return(Content("อัพโหลดไม่สำเร็จ ประเภทไฟล์ไม่ถูกต้อง"));
        }
Пример #57
0
        public HttpResponseMessage AddFinalEvaluationJury(Object FinalEvaluation)
        {
            var test = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(Convert.ToString(FinalEvaluation));

            object FormID;

            test.TryGetValue("FormID", out FormID);
            int _FormID = Convert.ToInt32(FormID);

            object LeaderID;

            test.TryGetValue("LeaderID", out LeaderID);
            int _LeaderID = Convert.ToInt32(LeaderID);

            object Member1ID;

            test.TryGetValue("Member1ID", out Member1ID);
            int _Member1ID = Convert.ToInt32(Member1ID);

            object Member2ID;

            test.TryGetValue("Member2ID", out Member2ID);
            int _Member2ID = Convert.ToInt32(Member2ID);

            object leaderMarks;

            test.TryGetValue("leaderMarks", out leaderMarks);
            double _leaderMarks = Convert.ToDouble(leaderMarks);

            object member1marks;

            test.TryGetValue("member1marks", out member1marks);
            double _member1marks = Convert.ToDouble(member1marks);

            object member2marks;

            test.TryGetValue("member2marks", out member2marks);
            double _member2marks = Convert.ToDouble(member2marks);

            var db = DbUtils.GetDBConnection();

            db.Connection.Open();


            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    db.Query("FypMarks").Insert(new
                    {
                        StudentID = _LeaderID,
                        FormID    = _FormID,
                        Marks     = _leaderMarks
                    });

                    db.Query("FypMarks").Insert(new
                    {
                        StudentID = _Member1ID,
                        FormID    = _FormID,
                        Marks     = _member1marks
                    });

                    db.Query("FypMarks").Insert(new
                    {
                        StudentID = _Member2ID,
                        FormID    = _FormID,
                        Marks     = _member2marks
                    });


                    scope.Complete();
                    db.Connection.Close();
                    return(Request.CreateResponse(HttpStatusCode.Created, new Dictionary <string, object>()
                    {
                        { "Marks Updated", 0 }
                    }));
                }
                catch (Exception ex)
                {
                    scope.Dispose();
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
                }
            }
        }
Пример #58
0
 public TransactionScopeWrapper(TransactionScopeOption tso)
 {
     m_Scope = TransactionScopeFactory.CreateTransactionScope(tso);
 }
Пример #59
0
        public void InsertCompany(Model.Profile.Company.Entity.Company company)
        {
            using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                try
                {
                    StandartPersistence standartPersistence =
                        new StandartPersistence(this.Connection);

                    company.DateUpdated = DateTime.Now;
                    company.DateCreated = DateTime.Now;

                    standartPersistence.Insert <Model.Profile.Company.Entity.Company>(company);

                    if (company.Address != null)
                    {
                        company.Address.DateUpdated = DateTime.Now;
                        company.Address.DateCreated = DateTime.Now;

                        standartPersistence.Insert <Address>(company.Address);

                        standartPersistence.Execute(CommandType.Text,
                                                    "INSERT INTO CompanyAddress Values (@IdCompany, @IdAddress)",
                                                    new
                        {
                            IdCompany = company.Id,
                            IdAddress = company.Address.Id
                        });
                    }

                    if (company.Expertises != null && company.Expertises.Count > 0)
                    {
                        for (int i = 0; i < company.Expertises.Count; i++)
                        {
                            standartPersistence.Execute(CommandType.Text,
                                                        "INSERT INTO CompanyExpertise Values (@IdCompany, @IdExpertise)",
                                                        new
                            {
                                IdCompany   = company.Id,
                                IdExpertise = company.Expertises[i].IdExpertise,
                                MinCost     = company.Expertises[i].CompanyMinCost
                            });
                        }
                    }

                    if (company.CompanyPartners != null && company.CompanyPartners.Count > 0)
                    {
                        for (int i = 0; i < company.CompanyPartners.Count; i++)
                        {
                            company.CompanyPartners[i].DateUpdated = DateTime.Now;
                            company.CompanyPartners[i].DateCreated = DateTime.Now;

                            company.CompanyPartners[i].IdCompany = company.Id;
                            company.CompanyPartners[i].Password  = CryptHelper.Encrypt(company.CompanyPartners[i].Password);
                            standartPersistence.Insert(company.CompanyPartners[i]);
                            if (company.CompanyPartners[i].CompanyPartnerFiles != null)
                            {
                                foreach (var file in company.CompanyPartners[i].CompanyPartnerFiles)
                                {
                                    file.DateUpdated = DateTime.Now;
                                    file.DateCreated = DateTime.Now;

                                    file.Connection = company.CompanyFiles.FirstOrDefault().Connection;
                                    file.Container  = "bplace";
                                    //file.Container = file.Type == (int)Model.Profile.Company.Entity.CompanyPartnerFile.FileType.PROFILE ? "companyrecognitionfacial" : "companydocuments";


                                    var blob = AzureBlobStorage.Upload(file.FilePath,
                                                                       file.Name,
                                                                       file.Connection,
                                                                       file.Container
                                                                       );

                                    if (blob != null)
                                    {
                                        file.URL = blob.StorageUri.PrimaryUri.AbsoluteUri;
                                        file.IdCompanyPartner = company.CompanyPartners[i].Id;
                                        standartPersistence.Insert(file);
                                    }
                                    else
                                    {
                                        throw new System.Exception("Falha no processo de Upload de arquivos no AzureBlobStorage.");
                                    }
                                }
                            }
                        }
                    }

                    if (company.CompanyFiles != null && company.CompanyFiles.Count > 0)
                    {
                        for (int i = 0; i < company.CompanyFiles.Count; i++)
                        {
                            var blob = AzureBlobStorage.Upload(company.CompanyFiles[i].FilePath,
                                                               company.CompanyFiles[i].Name,
                                                               company.CompanyFiles[i].Connection,
                                                               company.CompanyFiles[i].Container
                                                               );

                            if (blob != null)
                            {
                                company.CompanyFiles[i].URL         = blob.StorageUri.PrimaryUri.AbsoluteUri;
                                company.CompanyFiles[i].IdCompany   = company.Id;
                                company.CompanyFiles[i].DateUpdated = DateTime.Now;
                                company.CompanyFiles[i].DateCreated = DateTime.Now;

                                standartPersistence.Insert(company.CompanyFiles[i]);
                            }
                            else
                            {
                                throw new System.Exception("Falha no processo de Upload de arquivos no AzureBlobStorage.");
                            }
                        }
                    }

                    transactionScope.Complete();
                }
                catch (SqlException e)
                {
                    throw e;
                }
                catch (TransactionException e)
                {
                    throw e;
                }
            }
        }
Пример #60
0
        public void DistributedTransactionRollback()
        {
            int field_serial1;
            int field_serial2;

            try
            {
                string connectionString = TheConnectionString + ";enlist=true";
                using (TransactionScope scope = new TransactionScope())
                {
                    //UseStringParameterWithNoNpgsqlDbType
                    using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
                    {
                        connection.Open();
                        NpgsqlCommand command = new NpgsqlCommand("insert into tablea(field_text) values (:p0)", connection);

                        command.Parameters.Add(new NpgsqlParameter("p0", "test"));


                        Assert.AreEqual(command.Parameters[0].NpgsqlDbType, NpgsqlDbType.Text);
                        Assert.AreEqual(command.Parameters[0].DbType, DbType.String);

                        Object result = command.ExecuteNonQuery();

                        Assert.AreEqual(1, result);


                        field_serial1 = (int)new NpgsqlCommand("select max(field_serial) from tablea", connection).ExecuteScalar();
                        NpgsqlCommand command2 = new NpgsqlCommand("select field_text from tablea where field_serial = (select max(field_serial) from tablea)", connection);


                        result = command2.ExecuteScalar();



                        Assert.AreEqual("test", result);
                    }
                    //UseIntegerParameterWithNoNpgsqlDbType
                    using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
                    {
                        connection.Open();
                        NpgsqlCommand command = new NpgsqlCommand("insert into tablea(field_int4) values (:p0)", connection);

                        command.Parameters.Add(new NpgsqlParameter("p0", 5));

                        Assert.AreEqual(command.Parameters[0].NpgsqlDbType, NpgsqlDbType.Integer);
                        Assert.AreEqual(command.Parameters[0].DbType, DbType.Int32);


                        Object result = command.ExecuteNonQuery();

                        Assert.AreEqual(1, result);


                        field_serial2 = (int)new NpgsqlCommand("select max(field_serial) from tablea", connection).ExecuteScalar();
                        NpgsqlCommand command2 = new NpgsqlCommand("select field_int4 from tablea where field_serial = (select max(field_serial) from tablea)", connection);


                        result = command2.ExecuteScalar();


                        Assert.AreEqual(5, result);

                        // using new connection here... make sure we can't see previous results even though
                        // it is the same distributed transaction
                        NpgsqlCommand command3 = new NpgsqlCommand("select field_text from tablea where field_serial = :p0", connection);
                        command3.Parameters.Add(new NpgsqlParameter("p0", field_serial1));

                        result = command3.ExecuteScalar();


                        // won't see value of "test" since that's
                        // another connection
                        Assert.AreEqual(null, result);
                    }
                    // not commiting here.
                }
                // This is an attempt to wait for the distributed transaction to rollback
                // not guaranteed to work, but should be good enough for testing purposes.
                System.Threading.Thread.Sleep(500);
                AssertNoTransactions();
                // ensure they no longer exist since we rolled back
                AssertRowNotExist("field_text", field_serial1);
                AssertRowNotExist("field_int4", field_serial2);
            }
            catch (NotImplementedException)
            {
            }
        }