public void Calling_Rollback_on_an_already_disposed_DbContextTransaction_still_calls_Rollback_on_underlying_EntityTransaction() { var mockEntityTransaction = new Mock <EntityTransaction>(); var mockEntityConnection = new Mock <EntityConnection>(); mockEntityConnection.SetupGet(m => m.State).Returns(ConnectionState.Open); mockEntityConnection.Setup(m => m.BeginTransaction()).Returns(mockEntityTransaction.Object); var dbContextTransaction = new DbContextTransaction(mockEntityConnection.Object); dbContextTransaction.Dispose(); dbContextTransaction.Rollback(); mockEntityTransaction.Verify(m => m.Rollback(), Times.Once()); }
protected Collection CollectionLog(Collection collection, CollectionStatus status) { using (System.Data.Entity.DbContextTransaction dbTran = upsertContext.Database.BeginTransaction()) { try { Collection one = upsertContext.Collections.Find(collection.ID); one.status = status; upsertContext.SaveChanges(); dbTran.Commit(); } catch (Exception e) { log.Error(e); dbTran.Rollback(); } dbTran.Dispose(); } return(collection); }
protected void ChannelStatus(Channel channel, ActionStatus status) { using (System.Data.Entity.DbContextTransaction dbTran = upsertContext.Database.BeginTransaction()) { try { Channel c = upsertContext.Channels.Find(channel.ID); c.action = status; upsertContext.Entry(c).State = EntityState.Modified; upsertContext.SaveChanges(); dbTran.Commit(); } catch (Exception e) { log.Error(e); dbTran.Rollback(); } dbTran.Dispose(); } }
public void JobLog(Channel c, BatchStatus batchStatus, string message) { using (System.Data.Entity.DbContextTransaction dbTran = upsertContext.Database.BeginTransaction()) { try { Batch batch = new Batch { name = c.name, bound = c.bound, status = batchStatus, message = message }; upsertContext.Batches.Add(batch); upsertContext.SaveChanges(); dbTran.Commit(); } catch (Exception e) { log.Error(e); dbTran.Rollback(); } dbTran.Dispose(); } }
protected void CollectionLog(Channel channel, string name, string ftpname, CollectionStatus status) { using (System.Data.Entity.DbContextTransaction dbTran = upsertContext.Database.BeginTransaction()) { try { Collection collection = new Collection { channelId = channel.ID, name = name, ftpname = ftpname, status = status }; upsertContext.Collections.Add(collection); upsertContext.SaveChanges(); dbTran.Commit(); } catch (Exception e) { log.Error(e); dbTran.Rollback(); } dbTran.Dispose(); } }
public void Calling_Dispose_on_DbContextTransaction_which_opened_the_connection_closes_the_connection() { var connectionState = ConnectionState.Closed; var mockEntityTransaction = new Mock <EntityTransaction>(); mockEntityTransaction.Protected().Setup("Dispose", true).Verifiable(); var mockEntityConnection = new Mock <EntityConnection>(); mockEntityConnection.SetupGet(m => m.State).Returns(() => connectionState); mockEntityConnection.Setup(m => m.Open()).Callback(() => connectionState = ConnectionState.Open); mockEntityConnection.Setup(m => m.Close()).Callback(() => connectionState = ConnectionState.Closed); mockEntityConnection.Setup(m => m.BeginTransaction()).Returns(mockEntityTransaction.Object); var dbContextTransaction = new DbContextTransaction(mockEntityConnection.Object); Assert.Equal(ConnectionState.Open, connectionState); dbContextTransaction.Dispose(); mockEntityTransaction.Protected().Verify("Dispose", Times.Once(), true); Assert.Equal(ConnectionState.Closed, connectionState); }
public async Task <IHttpActionResult> DeleteDocSecondHandRazbor2Tab(int id, HttpRequestMessage request) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocSecondHandRazbors")); if (iRight != 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Параметры //save, save_close, held, held_cancel //var paramList = request.GetQueryNameValuePairs(); //docSecondHandRazbor2Tab.DocSecondHandPurchID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocSecondHandPurchID", true) == 0).Value); #endregion #region Проверки if (!ModelState.IsValid) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91))); //return BadRequest(ModelState); } Models.Sklad.Doc.DocSecondHandRazbor2Tab docSecondHandRazbor2Tab = await db.DocSecondHandRazbor2Tabs.FindAsync(id); int? DocSecondHandPurchID = docSecondHandRazbor2Tab.DocSecondHandPurchID; //Не трогать !!! string DirNomenName = docSecondHandRazbor2Tab.dirNomen.DirNomenName; //1. Если проведён //if (Convert.ToBoolean(docSecondHandRazbor2Tab.docSecondHandPurch.doc.Held)) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57_3)); //2. Если разобран (надо поменять статус) if (Convert.ToBoolean(docSecondHandRazbor2Tab.docSecondHandPurch.DirSecondHandStatusID != 12)) { return(Ok(returnServer.Return(false, "Для удаления запчасти (партии) статус аппарата должен быть 'В разборе'!"))); } //3. Есть ли остаток int?DocID = docSecondHandRazbor2Tab.docSecondHandPurch.DocID; var queryRemParties = await ( from x in db.RemParties where x.DocID == DocID && x.FieldID == docSecondHandRazbor2Tab.DocSecondHandRazbor2TabID select x ).ToListAsync(); if (queryRemParties.Count() > 0) { if (queryRemParties[0].Remnant < docSecondHandRazbor2Tab.Quantity) { return(Ok(returnServer.Return(false, "Партия уже продана! К-во на остатке: " + queryRemParties[0].Remnant))); } } #endregion #region Сохранение //using (TransactionScope ts = new TransactionScope()) using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { db.Configuration.AutoDetectChangesEnabled = false; try { #region 1. DocSecondHandRazbor2Tabs db.Entry(docSecondHandRazbor2Tab).State = EntityState.Deleted; await db.SaveChangesAsync(); #endregion #region 2. RemParties int?RemPartyID = queryRemParties[0].RemPartyID; Models.Sklad.Rem.RemParty remParty = await db.RemParties.FindAsync(RemPartyID); db.Entry(remParty).State = EntityState.Deleted; await db.SaveChangesAsync(); #endregion #region 3. Лог: Пишем в Лог о смене статуса и мастера, если такое было logService.DocSecondHandPurchID = DocSecondHandPurchID; logService.DirSecondHandLogTypeID = 6; //Смена статуса logService.DirEmployeeID = field.DirEmployeeID; //logService.DirSecondHandStatusID = DirSecondHandStatusID; logService.Msg = "Разборка: удалили запчасть: " + DirNomenName; await logServicesController.mPutPostLogSecondHands(db, logService, EntityState.Added); #endregion ts.Commit(); } catch (Exception ex) { try { ts.Rollback(); ts.Dispose(); } catch { } try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { } return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } } #region 6. JourDisp *** *** *** *** *** *** *** *** *** * Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp(); sysJourDisp.DirDispOperationID = 5; //Удаление записи sysJourDisp.DirEmployeeID = field.DirEmployeeID; sysJourDisp.ListObjectID = ListObjectID; sysJourDisp.TableFieldID = docSecondHandRazbor2Tab.DocSecondHandPurchID; sysJourDisp.Description = ""; try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { } #endregion dynamic collectionWrapper = new { ID = id, Msg = Classes.Language.Sklad.Language.msg19 }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
public async Task <IHttpActionResult> PostDirWarehouse(DirWarehouse dirWarehouse) { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDirWarehouses")); if (iRight != 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Проверки if (!ModelState.IsValid) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91))); //return BadRequest(ModelState); } //Подстановки - некоторые поля надо заполнить, если они не заполены //dirWarehouse.Substitute(); #endregion #region Сохранение try { //Используем метод, что бы было всё в одном потоке //db.Entry(dirWarehouse).State = EntityState.Added; //await Task.Run(() => db.SaveChangesAsync()); using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { db.Configuration.AutoDetectChangesEnabled = false; try { //Используем метод, что бы было всё в одном потоке dirWarehouse = await Task.Run(() => mPutPostDirWarehouse(db, dirWarehouse, EntityState.Added, field)); ts.Commit(); //.Complete(); } catch (Exception ex) { try { ts.Rollback(); ts.Dispose(); } catch { } try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { } return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } } #region 6. JourDisp *** *** *** *** *** *** *** *** *** * Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp(); sysJourDisp.DirDispOperationID = 3; //Добавление записи sysJourDisp.DirEmployeeID = field.DirEmployeeID; sysJourDisp.ListObjectID = ListObjectID; sysJourDisp.TableFieldID = dirWarehouse.DirWarehouseID; sysJourDisp.Description = ""; try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { } #endregion dynamic collectionWrapper = new { ID = dirWarehouse.DirWarehouseID }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } #endregion }
/// <summary> /// Will set the permissions for the targetUser, use recursive if you want it to propagate to child file and folders. /// context & dbcxtransaction should be null. /// </summary> /// <param name="FolderId"></param> /// <param name="user"></param> /// <param name="targetUser"></param> /// <param name="canListObjects"></param> /// <param name="canCreateFiles"></param> /// <param name="canCreateFolders"></param> /// <param name="canDelete"></param> /// <param name="canChangePermissions"></param> /// <param name="recursive"></param> /// <param name="context"></param> /// <param name="dbcxtransaction"></param> public static void SetPermissions(Guid FolderId, Principal user, Principal targetUser, bool canListObjects, bool canCreateFiles, bool canCreateFolders, bool canDelete, bool canChangePermissions, bool recursive = false, OnlineFilesEntities context = null, DbContextTransaction dbcxtransaction = null) { bool createdContext = false; bool createdTransaction = false; bool didRollback = false; if (context == null) { createdContext = true; context = new OnlineFilesEntities(); } if (dbcxtransaction == null) { dbcxtransaction = context.Database.BeginTransaction(); createdTransaction = true; } try { Folder target = context.Folders .Include(d => d.FolderSecurities) .FirstOrDefault(d => d.pk_FolderId == FolderId); //Can the user Change Permissions if (target.FolderSecurities.Any(d => d.canChangePermissions && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId))) { var secRecord = target.FolderSecurities.FirstOrDefault(d => d.SecurityObjectId == targetUser.UserProfile.SecurityObjectId); if (secRecord == null) { secRecord = new FolderSecurity() { SecurityObjectId = targetUser.UserProfile.SecurityObjectId, canChangePermissions = canChangePermissions, canListObjects = canListObjects, canCreateFolders = canCreateFolders, canCreateFiles = canCreateFiles, canDelete = canDelete, fk_FolderId = target.pk_FolderId }; target.FolderSecurities.Add(secRecord); } else { secRecord.canListObjects = canListObjects; secRecord.canChangePermissions = canChangePermissions; secRecord.canCreateFiles = canCreateFiles; secRecord.canCreateFolders = canCreateFolders; secRecord.canDelete = canDelete; } foreach (File source in context.Files.Where(d => d.fk_FolderId == target.pk_FolderId)) File.SetPermissions(source.pk_FileId, user, targetUser, canListObjects, canCreateFiles, canDelete, context, dbcxtransaction); context.SaveChanges(); if (recursive) foreach (Folder folder in context.Folders.Where(d => d.fk_ParentFolderId == target.pk_FolderId)) SetPermissions(folder.pk_FolderId, user, targetUser, canListObjects, canCreateFiles, canCreateFolders, canDelete, canChangePermissions, recursive, context, dbcxtransaction); } else { throw new SecurityException("Not Authorized."); } } catch (Exception) { if (createdTransaction) { didRollback = true; dbcxtransaction.Rollback(); } throw; } finally { if (createdTransaction) { if (!didRollback) dbcxtransaction.Commit(); dbcxtransaction.Dispose(); } if (createdContext) context.Dispose(); } }
public async Task <IHttpActionResult> PostDocSecondHandRazbor2Tab(DocSecondHandRazbor2Tab docSecondHandRazbor2Tab, HttpRequestMessage request) { //Алгоритм //1. DirNomens (ищим: находим (ничего), не находим (новый)) и заполняем DocSecondHandRazbor2Tabs.DirNomenID //2. DocSecondHandRazbor2Tabs (сохраняем) //3. Партии (создаём партию) try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocSecondHandRazbors")); if (iRight != 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Параметры //save, save_close, held, held_cancel var paramList = request.GetQueryNameValuePairs(); docSecondHandRazbor2Tab.DocSecondHandPurchID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocSecondHandPurchID", true) == 0).Value); #endregion #region Проверки if (!ModelState.IsValid) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91))); //return BadRequest(ModelState); } //Если документ "docSecondHandRazbor2Tab.DocSecondHandPurchID" проведён, то выдать Эксепшн /* * Models.Sklad.Doc.DocSecondHandRazbor docSecondHandRazbor = await db.DocSecondHandRazbors.FindAsync(docSecondHandRazbor2Tab.DocSecondHandPurchID); * //Models.Sklad.Doc.Doc doc = await db.Docs.FindAsync(docSecondHandRazbor.DocID); * if (Convert.ToBoolean(docSecondHandRazbor.doc.Held)) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57_3)); */ Models.Sklad.Doc.DocSecondHandPurch docSecondHandPurch = await db.DocSecondHandPurches.FindAsync(docSecondHandRazbor2Tab.DocSecondHandPurchID); if (docSecondHandPurch == null) { return(Ok(returnServer.Return(false, "Документ (аппарат) не найден №" + docSecondHandRazbor2Tab.DocSecondHandPurchID))); } else { if (docSecondHandPurch.DirSecondHandStatusID != 12) { return(Ok(returnServer.Return(false, "Для добавление запчастей, статус документа должен быть '12.В разборе'. А он " + docSecondHandPurch.DirSecondHandStatusID + "." + docSecondHandPurch.dirSecondHandStatus.DirSecondHandStatusName))); } } //Подстановки - некоторые поля надо заполнить, если они не заполены (Юридические реквизиты) //docSecondHandRazbor2Tab.Substitute(); #endregion #region Сохранение //using (TransactionScope ts = new TransactionScope()) using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { db.Configuration.AutoDetectChangesEnabled = false; try { //Используем метод, что бы было всё в одном потоке docSecondHandRazbor2Tab = await Task.Run(() => mPutPostDocSecondHandRazbor2Tab(db, dbRead, sysSetting, docSecondHandRazbor2Tab, EntityState.Added, field)); //sysSetting ts.Commit(); //.Complete(); } catch (Exception ex) { try { ts.Rollback(); ts.Dispose(); } catch { } try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { } return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } } #region 6. JourDisp *** *** *** *** *** *** *** *** *** * Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp(); sysJourDisp.DirDispOperationID = 3; //Добавление записи sysJourDisp.DirEmployeeID = field.DirEmployeeID; sysJourDisp.ListObjectID = ListObjectID; sysJourDisp.TableFieldID = docSecondHandRazbor2Tab.DocSecondHandPurchID; sysJourDisp.Description = ""; try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { } #endregion dynamic collectionWrapper = new { DocSecondHandRazbor2TabID = docSecondHandRazbor2Tab.DocSecondHandRazbor2TabID }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
public async Task <IHttpActionResult> DeleteDocServicePurch1Tab(int id, HttpRequestMessage request) { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocServicePurch1Tabs")); if (iRight != 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Параметры var paramList = request.GetQueryNameValuePairs(); int iDirServiceStatusID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceStatusID", true) == 0).Value); string sDiagnosticRresults = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "sDiagnosticRresults", true) == 0).Value; #endregion #region Удаление try { DocServicePurch1Tab docServicePurch1Tab = await db.DocServicePurch1Tabs.FindAsync(id); if (docServicePurch1Tab == null) { //return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg99)); dynamic collectionWrapper2 = new { ID = 0, Msg = Classes.Language.Sklad.Language.msg99 }; return(Ok(returnServer.Return(true, collectionWrapper2))); } //Проверка точки === === === Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch1Tab.DocServicePurchID); if (field.DirEmployeeID != 1) { int?DirWarehouseID = docServicePurch.DirWarehouseID; var query = await ( from x in db.DirEmployeeWarehouse where x.DirEmployeeID == field.DirEmployeeID && x.DirWarehouseID == DirWarehouseID select x ).ToListAsync(); if (query.Count() == 0) { return(Ok(returnServer.Return(false, "У Вас нет доступа к этой точке!"))); } } using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { db.Configuration.AutoDetectChangesEnabled = false; try { #region Лог //Пишем в Лог о смене статуса и мастера, если такое было logService.DocServicePurchID = docServicePurch1Tab.DocServicePurchID; logService.DirServiceLogTypeID = 5; logService.DirEmployeeID = field.DirEmployeeID; logService.DirServiceStatusID = null; logService.Msg = "Удаление записи " + docServicePurch1Tab.DirServiceJobNomenName + " на сумму " + docServicePurch1Tab.PriceCurrency; logService.Msg += "<br />Причина удаление: " + sDiagnosticRresults; await logServicesController.mPutPostLogServices(db, logService, EntityState.Added); #endregion #region Save db.DocServicePurch1Tabs.Remove(docServicePurch1Tab); await db.SaveChangesAsync(); #endregion ts.Commit(); } catch (Exception ex) { try { ts.Rollback(); ts.Dispose(); } catch { } try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { } return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } } dynamic collectionWrapper = new { ID = docServicePurch1Tab.DocServicePurch1TabID, Msg = Classes.Language.Sklad.Language.msg19 }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "") } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } #endregion }
public async Task <IHttpActionResult> PostDocServicePurch1Tab(DocServicePurch1Tab docServicePurch1Tab, HttpRequestMessage request) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocServicePurch1Tabs")); if (iRight != 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Параметры var paramList = request.GetQueryNameValuePairs(); int iDirServiceStatusID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceStatusID", true) == 0).Value); string sDiagnosticRresults = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "sDiagnosticRresults", true) == 0).Value; //Получаем колекцию "Спецификации" Models.Sklad.Doc.DocServicePurch1Tab[] DocServicePurch1TabCollection = null; if (!String.IsNullOrEmpty(docServicePurch1Tab.recordsDataX)) { JavaScriptSerializer serializer = new JavaScriptSerializer(); DocServicePurch1TabCollection = serializer.Deserialize <Models.Sklad.Doc.DocServicePurch1Tab[]>("[" + docServicePurch1Tab.recordsDataX + "]"); } if (DocServicePurch1TabCollection.Length > 0) { docServicePurch1Tab = DocServicePurch1TabCollection[0]; docServicePurch1Tab.PriceVAT = docServicePurch1Tab.PriceCurrency; if (docServicePurch1Tab.DirServiceJobNomenID == 0) { docServicePurch1Tab.DirServiceJobNomenID = null; } if (docServicePurch1Tab.DocServicePurch1TabID == null || docServicePurch1Tab.DocServicePurch1TabID < 1) { docServicePurch1Tab.DocServicePurch1TabID = null; docServicePurch1Tab.DirEmployeeID = field.DirEmployeeID; docServicePurch1Tab.DirCurrencyID = sysSetting.DirCurrencyID; docServicePurch1Tab.DirCurrencyRate = 1; docServicePurch1Tab.DirCurrencyMultiplicity = 1; if (docServicePurch1Tab.DirServiceJobNomenID == null) { bool bRight = await Task.Run(() => accessRight.AccessCheck(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocServiceWorkshopsTab1AddCheck")); if (!bRight) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } } } } //Проверка точки === === === Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch1Tab.DocServicePurchID); if (field.DirEmployeeID != 1) { int?DirWarehouseID = docServicePurch.DirWarehouseID; var query = await ( from x in db.DirEmployeeWarehouse where x.DirEmployeeID == field.DirEmployeeID && x.DirWarehouseID == DirWarehouseID select x ).ToListAsync(); if (query.Count() == 0) { return(Ok(returnServer.Return(false, "У Вас нет доступа к этой точке!"))); } } #endregion #region Сохранение using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { db.Configuration.AutoDetectChangesEnabled = false; try { #region Save docServicePurch //Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch1Tab.DocServicePurchID); int?DirServiceStatusIDOLD = docServicePurch.DirServiceStatusID; docServicePurch.DirServiceStatusID = iDirServiceStatusID; db.Entry(docServicePurch).State = EntityState.Modified; #region Лог - если поменялся статус if (DirServiceStatusIDOLD != iDirServiceStatusID) { //Пишем в Лог о смене статуса и мастера, если такое было logService.DocServicePurchID = docServicePurch1Tab.DocServicePurchID; logService.DirServiceLogTypeID = 1; logService.DirEmployeeID = field.DirEmployeeID; logService.DirServiceStatusID = iDirServiceStatusID; if (!String.IsNullOrEmpty(sDiagnosticRresults)) { logService.Msg = sDiagnosticRresults; } await logServicesController.mPutPostLogServices(db, logService, EntityState.Added); } #endregion #endregion #region Save docServicePurch1Tab #region Лог //Пишем в Лог о смене статуса и мастера, если такое было logService.DocServicePurchID = docServicePurch1Tab.DocServicePurchID; logService.DirServiceLogTypeID = 5; logService.DirEmployeeID = field.DirEmployeeID; logService.DirServiceStatusID = iDirServiceStatusID; if (docServicePurch1Tab.DocServicePurch1TabID == null) { logService.Msg = "Создание записи " + docServicePurch1Tab.DirServiceJobNomenName + " на сумму " + docServicePurch1Tab.PriceCurrency; } else { logService.Msg = "Изменение записи " + docServicePurch1Tab.DirServiceJobNomenName + " на сумму " + docServicePurch1Tab.PriceCurrency; } if (!String.IsNullOrEmpty(sDiagnosticRresults)) { logService.Msg += "<br /> Результат Диагностики: " + sDiagnosticRresults; } await logServicesController.mPutPostLogServices(db, logService, EntityState.Added); #endregion docServicePurch1Tab.DirServiceStatusID = iDirServiceStatusID; if (docServicePurch1Tab.DocServicePurch1TabID > 0) { db.Entry(docServicePurch1Tab).State = EntityState.Modified; } else { docServicePurch1Tab.DiagnosticRresults = sDiagnosticRresults; docServicePurch1Tab.TabDate = DateTime.Now; db.Entry(docServicePurch1Tab).State = EntityState.Added; } await Task.Run(() => db.SaveChangesAsync()); #endregion ts.Commit(); } catch (Exception ex) { try { ts.Rollback(); ts.Dispose(); } catch { } try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { } return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } } dynamic collectionWrapper = new { DocServicePurch1TabID = docServicePurch1Tab.DocServicePurch1TabID, DirEmployeeID = docServicePurch1Tab.DirEmployeeID, DirCurrencyID = docServicePurch1Tab.DirCurrencyID, DirCurrencyRate = docServicePurch1Tab.DirCurrencyRate, DirCurrencyMultiplicity = docServicePurch1Tab.DirCurrencyMultiplicity }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
public async Task <IHttpActionResult> PostDocSecondHandReturn(DocSecondHandReturn docSecondHandReturn, HttpRequestMessage request) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocSecondHandRetailReturns")); if (iRight != 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Скидка: разрешена или нет if (docSecondHandReturn.Discount > 0) { iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocDescription")); if (iRight == 3) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57_5))); } } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Параметры //save, save_close, held, held_cancel var paramList = request.GetQueryNameValuePairs(); string UO_Action = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "UO_Action", true) == 0).Value; if (UO_Action == null) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg101))); } UO_Action = UO_Action.ToLower(); //Получаем колекцию "Спецификации" /*Models.Sklad.Doc.DocSecondHandReturnTab[] docSecondHandReturnTabCollection = null; * if (!String.IsNullOrEmpty(docSecondHandReturn.recordsDocSecondHandReturnTab) && UO_Action != "held_cancel") * { * JavaScriptSerializer serializer = new JavaScriptSerializer(); * docSecondHandReturnTabCollection = serializer.Deserialize<Models.Sklad.Doc.DocSecondHandReturnTab[]>(docSecondHandReturn.recordsDocSecondHandReturnTab); * }*/ #endregion #region Проверки if (!ModelState.IsValid) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91))); //return BadRequest(ModelState); } /* * //Получаем "docSecondHandReturn.DocID" из БД, если он отличается от пришедшего от клиента "docSecondHandReturn.DocID" выдаём ошибку * //Были проблемы, кодга на один "DocID" числилось 2-а документа, а то и больше * var query = await Task.Run(() => * ( * from x in dbRead.DocSecondHandReturns * where x.DocSecondHandReturnID == docSecondHandReturn.DocSecondHandReturnID * select x * ).ToListAsync()); * * if (query.Count() > 0) * if (query[0].DocID != docSecondHandReturn.DocID) * return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg8)); //return BadRequest(); * * //dbRead.Database.Connection.Close(); */ //Проверка "Скидки" //1. Получаем сотурдника с правами //Подстановки - некоторые поля надо заполнить, если они не заполены (Юридические реквизиты) docSecondHandReturn.Substitute(); #endregion #region Сохранение using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { db.Configuration.AutoDetectChangesEnabled = false; try { //Используем метод, что бы было всё в одном потоке docSecondHandReturn = await Task.Run(() => mPutPostDocSecondHandReturn(db, dbRead, UO_Action, docSecondHandReturn, EntityState.Added, field)); //sysSetting ts.Commit(); //.Complete(); } catch (Exception ex) { try { ts.Rollback(); ts.Dispose(); } catch { } try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { } return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } } #region 6. JourDisp *** *** *** *** *** *** *** *** *** * Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp(); sysJourDisp.DirDispOperationID = 3; //Добавление записи sysJourDisp.DirEmployeeID = field.DirEmployeeID; sysJourDisp.ListObjectID = ListObjectID; sysJourDisp.TableFieldID = docSecondHandReturn.DocSecondHandReturnID; sysJourDisp.Description = ""; try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { } #endregion dynamic collectionWrapper = new { DocID = docSecondHandReturn.DocID, DocSecondHandReturnID = docSecondHandReturn.DocSecondHandReturnID }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
public async Task <IHttpActionResult> PutDocSalary(int id, DocSalary docSalary, HttpRequestMessage request) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocSalaries")); if (iRight != 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки //Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Параметры //save, save_close, held, held_cancel var paramList = request.GetQueryNameValuePairs(); string UO_Action = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "UO_Action", true) == 0).Value; if (UO_Action == null) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg101))); } UO_Action = UO_Action.ToLower(); //Получаем колекцию "Спецификации" Models.Sklad.Doc.DocSalaryTab[] docSalaryTabCollection = null; if (!String.IsNullOrEmpty(docSalary.recordsDocSalaryTab)) { JavaScriptSerializer serializer = new JavaScriptSerializer(); docSalaryTabCollection = serializer.Deserialize <Models.Sklad.Doc.DocSalaryTab[]>(docSalary.recordsDocSalaryTab); } #endregion #region Проверки //1. if (!ModelState.IsValid) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91))); //return BadRequest(ModelState); } if (id < 1 || id != docSalary.DocSalaryID || docSalary.DocID < 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg8))); //return BadRequest(); } //2. Получаем "docSalary.DocID" из БД, если он отличается от пришедшего от клиента "docSalary.DocID" выдаём ошибку //Были проблемы, кодга на один "DocID" числилось 2-а документа, а то и больше var query = await Task.Run(() => ( from x in dbRead.DocSalaries where x.DocSalaryID == docSalary.DocSalaryID select x ).ToListAsync()); if (query.Count() > 0) { if (query[0].DocID != docSalary.DocID) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg8))); //return BadRequest(); } } //3. Проверяем, если документ Models.Sklad.Doc.Doc docTemp = await dbRead.Docs.FindAsync(docSalary.DocID); //3.1. проведён и мы пытаемся его сохранить или провести - выдать Эксепшн if (Convert.ToBoolean(docTemp.Held) && (UO_Action == "save" || UO_Action == "save_close" || UO_Action == "held")) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg12_1))); } //3.2. НЕ проведён и мы пытаемся Снять Проводку - выдать Эксепшн if (!Convert.ToBoolean(docTemp.Held) && UO_Action == "held_cancel") { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg12_2))); } //4. Подстановки - некоторые поля надо заполнить, если они не заполены (Юридические реквизиты) docSalary.Substitute(); #endregion #region Сохранение //using (TransactionScope ts = new TransactionScope()) using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { db.Configuration.AutoDetectChangesEnabled = false; try { //Используем метод, что бы было всё в одном потоке docSalary = await Task.Run(() => mPutPostDocSalary(db, dbRead, UO_Action, docSalary, EntityState.Modified, docSalaryTabCollection, field)); //sysSetting ts.Commit(); //.Complete(); } catch (Exception ex) { try { ts.Rollback(); ts.Dispose(); } catch { } try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { } return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } } #region 6. JourDisp *** *** *** *** *** *** *** *** *** * Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp(); sysJourDisp.DirDispOperationID = 4; //Изменение записи sysJourDisp.DirEmployeeID = field.DirEmployeeID; sysJourDisp.ListObjectID = ListObjectID; sysJourDisp.TableFieldID = docSalary.DocSalaryID; sysJourDisp.Description = ""; try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { } #endregion dynamic collectionWrapper = new { DocID = docSalary.DocID, DocSalaryID = docSalary.DocSalaryID }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
/// <summary> /// Copies the fileId to this Folder. /// </summary> /// <param name="destination"></param> /// <param name="fileId"></param> /// <param name="destinationName"></param> /// <param name="user"></param> /// <param name="context"></param> /// <param name="dbcxtransaction"></param> public static void CopyFileHere(this Folder destination, Guid fileId, string destinationName, Principal user, OnlineFilesEntities context = null, DbContextTransaction dbcxtransaction = null) { bool createdContext = false; bool createdTransaction = false; bool didRollback = false; if (context == null) { createdContext = true; context = new OnlineFilesEntities(); } if (dbcxtransaction == null) { dbcxtransaction = context.Database.BeginTransaction(); createdTransaction = true; } try { var destSecurity = context.FolderSecurities.Where(d => d.fk_FolderId == destination.pk_FolderId); //Can the user create files at the destination location? if (destSecurity.Any(d => d.canCreateFiles && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId))) { var file = context.Files .Include(x => x.FileSecurities) .Include(x => x.FileDatas) .FirstOrDefault(d => d.pk_FileId == fileId); //Can the user Read the file to be copied? if (file.FileSecurities.Any(f => user.UserProfile.mySecurityGroups.Contains(f.SecurityObjectId) && f.canRead)) { File newFile = File.Create(destination.pk_FolderId, file.Name, user.UserProfile, true); context.SaveChanges(); //Copy the file data using (Stream s = file.OpenReadStream(user)) using (Stream d = newFile.OpenWriteStream(user)) s.CopyTo(d); //Copy the file Security foreach (FileSecurity security in file.FileSecurities) { FileSecurity nsec = context.FileSecurities.FirstOrDefault(d => d.fk_FileId == newFile.pk_FileId && d.SecurityObjectId == security.SecurityObjectId); if (nsec == null) { nsec = new FileSecurity() { canRead = security.canRead, canWrite = security.canWrite, CanDelete = security.CanDelete, fk_FileId = newFile.pk_FileId, SecurityObjectId = security.SecurityObjectId }; context.FileSecurities.Add(nsec); } else { nsec.canRead = nsec.canRead || security.canRead; nsec.CanDelete = nsec.CanDelete || security.CanDelete; nsec.canWrite = nsec.canWrite || security.canWrite; } } context.SaveChanges(); } else { throw new SecurityException("Not Authorized."); } } else { throw new SecurityException("Not Authorized."); } } catch (Exception) { //If we got an error and we created the transaction, roll it back. if (createdTransaction) { dbcxtransaction.Rollback(); didRollback = true; } throw; } finally { if (createdTransaction) { //If we didn't roll back the transaction, commit it. if (!didRollback) dbcxtransaction.Commit(); dbcxtransaction.Dispose(); } if (createdContext) context.Dispose(); } }
/// <summary> /// Set the permission on a file for the target User. /// </summary> /// <param name="fileId"></param> /// <param name="user"></param> /// <param name="targetUser"></param> /// <param name="canRead"></param> /// <param name="canWrite"></param> /// <param name="canDelete"></param> /// <param name="context"></param> /// <param name="dbcxtransaction"></param> public static void SetPermissions(Guid fileId, Principal user, Principal targetUser, bool canRead, bool canWrite, bool canDelete, OnlineFilesEntities context = null, DbContextTransaction dbcxtransaction = null) { bool createdContext = false; bool createdTransaction = false; bool didRollback = false; if (context == null) { createdContext = true; context = new OnlineFilesEntities(); } if (dbcxtransaction == null) { dbcxtransaction = context.Database.BeginTransaction(); createdTransaction = true; } try { File targetfile = context.Files .Include(d => d.FileSecurities) .FirstOrDefault(d => d.pk_FileId == fileId); if (targetfile == null) throw new Exception("File does not exist."); Folder target = context.Folders.Include(d => d.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == targetfile.fk_FolderId); if (target == null) throw new Exception("Parent Folder does not exist."); //Can the user Change Permissions if (target.FolderSecurities.Any(d => d.canChangePermissions && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId))) { var secRecord = targetfile.FileSecurities.FirstOrDefault(d => d.SecurityObjectId == targetUser.UserProfile.SecurityObjectId); if (secRecord == null) { secRecord = new FileSecurity { fk_FileId = targetfile.pk_FileId, CanDelete = canDelete, canRead = canRead, canWrite = canWrite, SecurityObjectId = targetUser.UserProfile.SecurityObjectId }; targetfile.FileSecurities.Add(secRecord); } else { secRecord.canRead = canRead; secRecord.CanDelete = canDelete; secRecord.canWrite = canWrite; } context.SaveChanges(); } else { throw new SecurityException("Not Authorized."); } } catch (Exception) { if (!createdTransaction) throw; didRollback = true; dbcxtransaction.Rollback(); throw; } finally { if (createdTransaction) { if (!didRollback) dbcxtransaction.Commit(); dbcxtransaction.Dispose(); } if (createdContext) context.Dispose(); } }
public async Task <IHttpActionResult> PostDocServicePurch2Tab(DocServicePurch2Tab docServicePurch2Tab) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocServicePurch2Tabs")); if (iRight != 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Параметры //Получаем колекцию "Спецификации" Models.Sklad.Doc.DocServicePurch2Tab[] DocServicePurch2TabCollection = null; if (!String.IsNullOrEmpty(docServicePurch2Tab.recordsDataX)) { JavaScriptSerializer serializer = new JavaScriptSerializer(); DocServicePurch2TabCollection = serializer.Deserialize <Models.Sklad.Doc.DocServicePurch2Tab[]>("[" + docServicePurch2Tab.recordsDataX + "]"); } if (DocServicePurch2TabCollection.Length > 0) { docServicePurch2Tab = DocServicePurch2TabCollection[0]; docServicePurch2Tab.PriceVAT = docServicePurch2Tab.PriceCurrency; //if (docServicePurch2Tab.DirServiceJobNomenID == 0) docServicePurch2Tab.DirServiceJobNomenID = null; if (docServicePurch2Tab.DocServicePurch2TabID == null || docServicePurch2Tab.DocServicePurch2TabID < 1) { docServicePurch2Tab.DocServicePurch2TabID = null; docServicePurch2Tab.DirEmployeeID = field.DirEmployeeID; docServicePurch2Tab.DirCurrencyID = sysSetting.DirCurrencyID; docServicePurch2Tab.DirCurrencyRate = 1; docServicePurch2Tab.DirCurrencyMultiplicity = 1; } } //Проверка точки === === === Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch2Tab.DocServicePurchID); if (field.DirEmployeeID != 1) { int?DirWarehouseID = docServicePurch.DirWarehouseID; var query = await ( from x in db.DirEmployeeWarehouse where x.DirEmployeeID == field.DirEmployeeID && x.DirWarehouseID == DirWarehouseID select x ).ToListAsync(); if (query.Count() == 0) { return(Ok(returnServer.Return(false, "У Вас нет доступа к этой точке!"))); } } #endregion #region Сохранение using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { db.Configuration.AutoDetectChangesEnabled = false; try { docServicePurch2Tab = await Task.Run(() => mPutPostDocServicePurch2Tab(db, docServicePurch, docServicePurch2Tab, field)); ts.Commit(); } catch (Exception ex) { try { ts.Rollback(); ts.Dispose(); } catch { } try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { } return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } } dynamic collectionWrapper = new { DocServicePurch2TabID = docServicePurch2Tab.DocServicePurch2TabID, DirEmployeeID = docServicePurch2Tab.DirEmployeeID, DirCurrencyID = docServicePurch2Tab.DirCurrencyID, DirCurrencyRate = docServicePurch2Tab.DirCurrencyRate, DirCurrencyMultiplicity = docServicePurch2Tab.DirCurrencyMultiplicity }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
public async Task <IHttpActionResult> DeleteDocPurchTab(int id, HttpRequestMessage request) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocPurches")); if (iRight != 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Параметры //save, save_close, held, held_cancel //var paramList = request.GetQueryNameValuePairs(); //docPurchTab.DocPurchID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocPurchID", true) == 0).Value); #endregion #region Проверки if (!ModelState.IsValid) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91))); //return BadRequest(ModelState); } //Если документ "docPurchTab.DocPurchID" проведён, то выдать Эксепшн Models.Sklad.Doc.DocPurchTab docPurchTab = await db.DocPurchTabs.FindAsync(id); //Models.Sklad.Doc.Doc doc = await db.Docs.FindAsync(docPurch.DocID); if (Convert.ToBoolean(docPurchTab.docPurch.doc.Held)) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57_3))); } //Подстановки - некоторые поля надо заполнить, если они не заполены (Юридические реквизиты) //docPurchTab.Substitute(); #endregion #region Сохранение //using (TransactionScope ts = new TransactionScope()) using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { db.Configuration.AutoDetectChangesEnabled = false; try { //db.DocPurchTabs.Remove(docPurchTab); //await db.SaveChangesAsync(); db.Entry(docPurchTab).State = EntityState.Deleted; await db.SaveChangesAsync(); ts.Commit(); //.Complete(); } catch (Exception ex) { try { ts.Rollback(); ts.Dispose(); } catch { } try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { } return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } } #region 6. JourDisp *** *** *** *** *** *** *** *** *** * Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp(); sysJourDisp.DirDispOperationID = 5; //Удаление записи sysJourDisp.DirEmployeeID = field.DirEmployeeID; sysJourDisp.ListObjectID = ListObjectID; sysJourDisp.TableFieldID = docPurchTab.DocPurchID; sysJourDisp.Description = ""; try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { } #endregion dynamic collectionWrapper = new { ID = id, Msg = Classes.Language.Sklad.Language.msg19 }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
public void Calling_Dispose_on_DbContextTransaction_which_opened_the_connection_closes_the_connection() { var connectionState = ConnectionState.Closed; var mockEntityTransaction = new Mock<EntityTransaction>(); mockEntityTransaction.Protected().Setup("Dispose", true).Verifiable(); var mockEntityConnection = new Mock<EntityConnection>(); mockEntityConnection.SetupGet(m => m.State).Returns(() => connectionState); mockEntityConnection.Setup(m => m.Open()).Callback(() => connectionState = ConnectionState.Open); mockEntityConnection.Setup(m => m.Close()).Callback(() => connectionState = ConnectionState.Closed); mockEntityConnection.Setup(m => m.BeginTransaction()).Returns(mockEntityTransaction.Object); var dbContextTransaction = new DbContextTransaction(mockEntityConnection.Object); Assert.Equal(ConnectionState.Open, connectionState); dbContextTransaction.Dispose(); mockEntityTransaction.Protected().Verify("Dispose", Times.Once(), true); Assert.Equal(ConnectionState.Closed, connectionState); }
public void Calling_Rollback_on_an_already_disposed_DbContextTransaction_still_calls_Rollback_on_underlying_EntityTransaction() { var mockEntityTransaction = new Mock<EntityTransaction>(); var mockEntityConnection = new Mock<EntityConnection>(); mockEntityConnection.SetupGet(m => m.State).Returns(ConnectionState.Open); mockEntityConnection.Setup(m => m.BeginTransaction()).Returns(mockEntityTransaction.Object); var dbContextTransaction = new DbContextTransaction(mockEntityConnection.Object); dbContextTransaction.Dispose(); dbContextTransaction.Rollback(); mockEntityTransaction.Verify(m => m.Rollback(), Times.Once()); }
public async Task <IHttpActionResult> DeleteDocSalary(int id) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocSalaries")); if (iRight != 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Проверки try { //Документ проведён!<BR>Перед удалением, нужно отменить проводку! var queryHeld = await Task.Run(() => ( from x in dbRead.DocSalaries where x.DocSalaryID == id select x ).ToListAsync()); if (queryHeld.Count() > 0) { if (Convert.ToBoolean(queryHeld[0].doc.Held)) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg18))); //return BadRequest(); } } } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } #endregion #region Удаление //Алгоритм. //Удаляем по порядку: //1. RemParties //2. DocSalaryTabs //3. DocSalaries //4. Docs //Сотрудник Models.Sklad.Doc.DocSalary docSalary = await db.DocSalaries.FindAsync(id); if (docSalary == null) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg99))); } using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { try { #region 1. Ищим DocID *** *** *** *** *** //1.1. Ищим DocID int iDocID = 0; var queryDocs1 = await ( from x in db.DocSalaries where x.DocSalaryID == id select x ).ToListAsync(); if (queryDocs1.Count() > 0) { iDocID = Convert.ToInt32(queryDocs1[0].DocID); } else { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg99))); } #endregion #region 2. DocSalaryTabs *** *** *** *** *** var queryDocSalaryTabs = await ( from x in db.DocSalaryTabs where x.DocSalaryID == id select x ).ToListAsync(); for (int i = 0; i < queryDocSalaryTabs.Count(); i++) { Models.Sklad.Doc.DocSalaryTab docSalaryTab = await db.DocSalaryTabs.FindAsync(queryDocSalaryTabs[i].DocSalaryTabID); db.DocSalaryTabs.Remove(docSalaryTab); await db.SaveChangesAsync(); } #endregion #region 3. DocSalaries *** *** *** *** *** var queryDocSalaries = await ( from x in db.DocSalaries where x.DocSalaryID == id select x ).ToListAsync(); for (int i = 0; i < queryDocSalaries.Count(); i++) { Models.Sklad.Doc.DocSalary docSalary1 = await db.DocSalaries.FindAsync(queryDocSalaries[i].DocSalaryID); db.DocSalaries.Remove(docSalary1); await db.SaveChangesAsync(); } #endregion #region 4. Doc *** *** *** *** *** var queryDocs2 = await ( from x in db.Docs where x.DocID == iDocID select x ).ToListAsync(); for (int i = 0; i < queryDocs2.Count(); i++) { Models.Sklad.Doc.Doc doc = await db.Docs.FindAsync(queryDocs2[i].DocID); db.Docs.Remove(doc); await db.SaveChangesAsync(); } #endregion ts.Commit(); #region 6. JourDisp *** *** *** *** *** *** *** *** *** * Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp(); sysJourDisp.DirDispOperationID = 5; //Удаление записи sysJourDisp.DirEmployeeID = field.DirEmployeeID; sysJourDisp.ListObjectID = ListObjectID; sysJourDisp.TableFieldID = id; sysJourDisp.Description = ""; try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { } #endregion dynamic collectionWrapper = new { ID = id, Msg = Classes.Language.Sklad.Language.msg19 }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); } catch (Exception ex) { try { ts.Rollback(); ts.Dispose(); } catch { } try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { } return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } //catch } //DbContextTransaction #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
public async Task <IHttpActionResult> DeleteDocServicePurch2Tab(int id) { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) bool bRight = await Task.Run(() => accessRight.AccessCheck(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocServiceWorkshopsTab2ReturnCheck")); if (!bRight) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Удаление try { DocServicePurch2Tab docServicePurch2Tab = await db.DocServicePurch2Tabs.FindAsync(id); if (docServicePurch2Tab == null) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg99))); } //Проверка точки === === === Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch2Tab.DocServicePurchID); if (field.DirEmployeeID != 1) { int?DirWarehouseID = docServicePurch.DirWarehouseID; var query = await ( from x in db.DirEmployeeWarehouse where x.DirEmployeeID == field.DirEmployeeID && x.DirWarehouseID == DirWarehouseID select x ).ToListAsync(); if (query.Count() == 0) { return(Ok(returnServer.Return(false, "У Вас нет доступа к этой точке!"))); } } using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { db.Configuration.AutoDetectChangesEnabled = false; try { #region Лог //Пишем в Лог о смене статуса и мастера, если такое было logService.DocServicePurchID = docServicePurch2Tab.DocServicePurchID; logService.DirServiceLogTypeID = 6; logService.DirEmployeeID = field.DirEmployeeID; logService.DirServiceStatusID = null; logService.Msg = "Удаление записи " + docServicePurch2Tab.DirNomenName + " на сумму " + docServicePurch2Tab.PriceCurrency; await logServicesController.mPutPostLogServices(db, logService, EntityState.Added); #endregion #region Save db.DocServicePurch2Tabs.Remove(docServicePurch2Tab); await db.SaveChangesAsync(); #endregion #region Партии //Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch2Tab.DocServicePurchID); //Models.Sklad.Rem.RemPartyMinus remPartyMinus = db.RemPartyMinuses.Where(x => x.DocID == docServicePurch.DocID && x.FieldID == id).ToList().First(); var query2 = await db.RemPartyMinuses.Where(x => x.DocID == docServicePurch.DocID && x.FieldID == id).ToListAsync(); if (query2.Count() > 0) { Models.Sklad.Rem.RemPartyMinus remPartyMinus = query2[0]; db.RemPartyMinuses.Remove(remPartyMinus); await db.SaveChangesAsync(); } #endregion ts.Commit(); } catch (Exception ex) { try { ts.Rollback(); ts.Dispose(); } catch { } try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { } return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } } dynamic collectionWrapper = new { ID = docServicePurch2Tab.DocServicePurch2TabID, Msg = Classes.Language.Sklad.Language.msg19 }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "") } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } #endregion }
/// <summary> /// Copies the folderId to this Folder /// </summary> /// <param name="destination"></param> /// <param name="folderId"></param> /// <param name="destinationName"></param> /// <param name="user"></param> /// <param name="context"></param> /// <param name="recursive"></param> /// <param name="dbcxtransaction"></param> public static void CopyFolderHere(this Folder destination, Guid folderId, string destinationName, Principal user, OnlineFilesEntities context = null, bool recursive = true, DbContextTransaction dbcxtransaction = null) { bool createdContext = false; bool createdTransaction = false; bool didRollback = false; if (context == null) { createdContext = true; context = new OnlineFilesEntities(); } if (dbcxtransaction == null) { dbcxtransaction = context.Database.BeginTransaction(); createdTransaction = true; } try { var destSecurity = context.FolderSecurities.Where(d => d.fk_FolderId == destination.pk_FolderId); //Can the user create folders at the destination location? if (destSecurity.Any(d => d.canCreateFolders && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId))) { Folder folderToMove = context.Folders.Include(d => d.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == folderId); if (folderToMove == null) throw new Exception("Cannot move a non existant folder"); Folder parentToFolderToMove = context.Folders.Include(x => x.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == folderToMove.fk_ParentFolderId); if (parentToFolderToMove == null) throw new Exception("No parent to folder being moved."); //Does the user have read permission in the folder the item is comming from? if (parentToFolderToMove.FolderSecurities.Any(d => user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId) && d.canListObjects)) { Folder newFolder = Folder.Create(destinationName, destination.pk_FolderId, user.UserProfile, true); context.SaveChanges(); if (recursive) { //Get all the files that are in the folder being copied. var files = context.Files.Where(d => d.fk_FolderId == folderToMove.pk_FolderId); foreach (File file in files) newFolder.CopyFileHere(file.pk_FileId, file.Name, user, context, dbcxtransaction); //Get all the folders inside the folder we are moving. var folders = context.Folders.Where(d => d.fk_ParentFolderId == folderToMove.pk_FolderId); //Copy the folders to the new location foreach (var folder in folders) newFolder.CopyFolderHere(folder.pk_FolderId, folder.Name, user, context, recursive, dbcxtransaction); } context.SaveChanges(); } else { throw new SecurityException("Not Authorized."); } } else { throw new SecurityException("Not Authorized."); } } catch (Exception) { if (createdTransaction) { didRollback = true; dbcxtransaction.Rollback(); } throw; } finally { if (createdTransaction) { if (!didRollback) dbcxtransaction.Commit(); dbcxtransaction.Dispose(); } if (createdContext) context.Dispose(); } }