public void UpdateEntity_ShouldUpdateEntity() { // arrange var obj = new Author { Uid = AuthorUid}; var storageObj = new Author { Uid = AuthorUid }; var stub = new FakeRepository(new Dictionary<Type, IEnumerable<IEntity>> { {typeof (Author), new[] {new Author {Uid = Guid.NewGuid()}, storageObj}} }); var updateCommand = new UpdateCommand<Author>(); // act obj.Name = "foo bar"; obj.About = "sooo some foor"; obj.Company = "rook"; obj.SemanticUid = "foo_bar_rook"; updateCommand.Entity = obj; updateCommand.Execute(stub); // assert Assert.AreEqual(obj.Name, storageObj.Name); Assert.AreEqual(obj.About, storageObj.About); Assert.AreEqual(obj.Company, storageObj.Company); Assert.AreEqual(obj.SemanticUid, storageObj.SemanticUid); }
public async Task<CodeFeatureModel> Disable(string codeFeatureId) { var updateCommand = new UpdateCommand(codeFeatureId, false); await _updateCommandHandler.Execute(updateCommand); return new CodeFeatureModel { CodeFeatureId = updateCommand.CodeFeatureId, Enabled = updateCommand.Enabled, }; }
public static decimal GetNext(Transaction pTransaction, string pIDFieldValue) { decimal lID; // Inicializa operação OperationResult lReturn = new OperationResult(QueryDictionaries.SequencesQD.TableName, QueryDictionaries.SequencesQD.TableName); // Recupera Valor SelectCommand lSelectNext; string lSelectQuery = QueryDictionaries.SequencesQD.qSequencesMax; lSelectQuery += String.Format("WHERE {0} = >>{0}", QueryDictionaries.SequencesQD._SEQ_NAME.Name); object lScalarReturn; lSelectNext = new SelectCommand(lSelectQuery); // Passagem dos Valores de Parametros para a Clausula WHERE [comando SELECT] lSelectNext.Fields.Add(QueryDictionaries.SequencesQD._SEQ_NAME.Name, pIDFieldValue, ItemType.String); // Recupera Valor do Select (Seq_Value) lScalarReturn = lSelectNext.ReturnScalar(pTransaction); if (lScalarReturn == null || lScalarReturn == DBNull.Value) lScalarReturn = 1; lID = Convert.ToDecimal(lScalarReturn); // Altera Valor da Sequence UpdateCommand lUpdate; lUpdate = new UpdateCommand(QueryDictionaries.SequencesQD.TableName); // Identificação dos Campos a serem Alterados lUpdate.Fields.Add(QueryDictionaries.SequencesQD._SEQ_VALUE.Name, lID, (ItemType) QueryDictionaries.SequencesQD._SEQ_VALUE.DBType); string lUpdateQuery; lUpdateQuery = String.Format("WHERE {0} = >>{0}", QueryDictionaries.SequencesQD._SEQ_NAME.Name); lUpdate.Condition = lUpdateQuery; // Passagem dos Valores para a Condição Where do Update lUpdate.Conditions.Add(QueryDictionaries.SequencesQD._SEQ_NAME.Name, pIDFieldValue); // Execução do UPDATE lUpdate.Execute(pTransaction); // Retorna novo valor da chave [SEQUENCE VALUE] return lID; }
public void UpdatePackageAddsPackagesToSharedPackageRepositoryWhenReferencesAreAdded() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var constraintProvider = NullConstraintProvider.Instance; var fileSystem = new MockFileSystem(); var pathResolver = new DefaultPackagePathResolver(fileSystem); var projectSystem = new MockProjectSystem(); var packages = new List <IPackage>(); var package_A10 = PackageUtility.CreatePackage("A", "1.0", content: new[] { "1.txt" }); var package_A12 = PackageUtility.CreatePackage("A", "1.2", content: new[] { "1.txt" }); localRepository.Add(package_A10); sourceRepository.Add(package_A12); var sharedRepository = new Mock <ISharedPackageRepository>(MockBehavior.Strict); sharedRepository.SetupSet(s => s.PackageSaveMode = PackageSaveModes.Nupkg); sharedRepository.Setup(s => s.AddPackage(package_A12)).Callback <IPackage>(p => packages.Add(p)).Verifiable(); sharedRepository.Setup(s => s.GetPackages()).Returns(packages.AsQueryable()); var repositoryFactory = new Mock <IPackageRepositoryFactory>(); repositoryFactory.Setup(s => s.CreateRepository(It.IsAny <string>())).Returns(sourceRepository); var packageSourceProvider = new Mock <IPackageSourceProvider>(); packageSourceProvider.Setup(s => s.LoadPackageSources()).Returns(new[] { new PackageSource("foo-source") }); var updateCommand = new UpdateCommand() { RepositoryFactory = repositoryFactory.Object, SourceProvider = packageSourceProvider.Object }; // Act updateCommand.UpdatePackages(localRepository, fileSystem, sharedRepository.Object, sourceRepository, constraintProvider, pathResolver, projectSystem); // Assert sharedRepository.Verify(); }
public static void Execute(CorrigoService service, int id) { var entity = new WoAssignment { Id = id, EmployeeId = 3, IsPrimary = false }; string[] properties = { "EmployeeId", "IsPrimary" }; var command = new UpdateCommand { Entity = entity, PropertySet = new PropertySet { Properties = properties } }; var response = service.Execute(command) as OperationCommandResponse; Debug.Print(response.ErrorInfo?.Description ?? "Successfully updated WoAssignment!"); }
private void Update() { DateTime oldDate = Entity.Date; string oldContent = Entity.Content; Entity.Date = Date; Entity.Content = Content; UpdateCommand.RaiseCanExecuteChanged(); if (!_apiRequester.Update(Entity, "comment/" + Id)) { Entity.Date = oldDate; Entity.Content = oldContent; } CommentWindow commentWindow = App.Current.Windows.OfType <CommentWindow>().FirstOrDefault(); commentWindow.Close(); //cw.Close(); }
public void Run() { try { var loginResult = LoginCommand.ExecuteCommand(); Console.WriteLine(loginResult); var updateResult = UpdateCommand.ExecuteCommand(); if (updateResult.Contains(SERVICE_UPDATE_SUCCESS)) { Console.WriteLine($"Service [{ServiceName}] update: SUCCESS!"); } else { Console.WriteLine($"Service [{ServiceName}] update: FAILED!"); } } catch (Exception ex) { Console.WriteLine(ex); } }
public override Command[] Process() { XmlDocument document = new XmlDocument(); XmlNode updateContent = document.CreateElement("Update"); XmlNode modifyChild = document.CreateElement("Modify"); updateContent.AppendChild(modifyChild); XmlElement accountBalanceChild = document.CreateElement("AccountBalance"); modifyChild.AppendChild(accountBalanceChild); accountBalanceChild.SetAttribute("AccountID", _command.AccountId.ToString()); accountBalanceChild.SetAttribute("CurrencyID", _command.CurrencyId.ToString()); accountBalanceChild.SetAttribute("Balance", XmlConvert.ToString(_command.Balance)); accountBalanceChild.SetAttribute("TotalPaidAmount", XmlConvert.ToString(_command.TotalPaidAmount)); UpdateCommand command = new UpdateCommand(); command.Content = updateContent; return(new Command[] { command }); }
public void LinqDecreaseTest() { AbstractDatabase fakeDb = DatabaseFactory.CreateDatabase("", "System.Data.SqlClient") as AbstractDatabase; TestEntityRepository repository = new TestEntityRepository(fakeDb); TestEntity entity = new TestEntity() { Test1 = "1", Test2 = 2, Test3 = 3.0, Test4 = DateTime.Now, Test8 = 8 }; String expectedSql = "UPDATE TestTable SET TestColumn2=(TestColumn2-1)"; DataParameter[] expectedParameter = new DataParameter[0]; UpdateCommand cmd = fakeDb.CreateUpdateCommand(repository.TableName).Decrease <TestEntity>(c => c.Test2); String actualSql = cmd.GetCommandText().Trim(); DataParameter[] actualParameter = cmd.GetAllParameters(); Assert.AreEqual(expectedSql, actualSql); Assert.AreEqual(expectedParameter.Length, actualParameter.Length); }
public async Task <SettingsContainer> CaptureSettings(FileSettings settingsIn, VersionChange?change = null) { var logger = Substitute.For <IConfigureLogger>(); var fileSettings = Substitute.For <IFileSettingsCache>(); SettingsContainer settingsOut = null; var engine = Substitute.For <ILocalEngine>(); await engine.Run(Arg.Do <SettingsContainer>(x => settingsOut = x), true); fileSettings.Get().Returns(settingsIn); var command = new UpdateCommand(engine, logger, fileSettings); command.AllowedChange = change; await command.OnExecute(); return(settingsOut); }
private async void OnReceiveCommand(object obj) { SetBusy(true); var api = GetApi(); var response = await api.ListUnreadMessages(); if (response.HasMessages) { foreach (var msg in response.ReceivedMessages) { if (DBContext.Messages.Where(x => x.MtId == msg.MtId).FirstOrDefault() == null) { DBContext.Messages.Add(new MessageModel(msg)); } } await DBContext.SaveChangesAsync(); UpdateCommand.Execute(obj); } }
public IActionResult RemoveMyPromotion([FromBody] UpdateCommand command) { try { var result = context.Tb_UserPromotion.FirstOrDefault(up => up.UserId == command.UserId && up.PromotionId == command.PromotionId); if (result == null) { return(BadRequest()); } else { result.Status = 0; context.SaveChanges(); return(Ok()); } } catch (Exception e) { return(BadRequest(e.Message)); } }
public void SelfUpdateOlderVersionDoesNotUpdate() { // Arrange var factory = new Mock <IPackageRepositoryFactory>(); var sourceProvider = new Mock <IPackageSourceProvider>(); var repository = new MockPackageRepository(); repository.Add(PackageUtility.CreatePackage("NuGet.CommandLine", "1.0")); factory.Setup(m => m.CreateRepository(It.IsAny <string>())).Returns(repository); ConsoleInfo consoleInfo = GetConsoleInfo(); var updateCmd = new UpdateCommand(factory.Object, sourceProvider.Object); updateCmd.Console = consoleInfo.Console; // Act updateCmd.SelfUpdate("c:\foo.exe", new SemanticVersion("2.0")); // Assert Assert.Equal("NuGet.exe is up to date.", consoleInfo.WrittenLines[0]); }
public Output <List <object>, bool> ExecuteCommand(UpdateCommand update, ActionConfig actionConfig = null) { Output <List <object>, bool> result = new Output <List <object>, bool> { Item1 = new List <object>(), Item2 = false }; if (update == null) { return(result); } if (string.IsNullOrWhiteSpace(update.Table)) { update.Table = GetMatchingTable(update.DataType); } using (SqlConnection connection = new SqlConnection(m_ConnectionString)) { connection.Open(); using (SqlCommand command = connection.CreateCommand()) { try { command.CommandText = update.IToSqlCommand(); int nbSuccess = command.ExecuteNonQuery(); result.Item2 = nbSuccess > 0; } catch (Exception e) { Engine.Base.Compute.RecordError(e.Message); } } connection.Close(); } return(result); }
private void Update() { string oldName = Entity.Name; string oldType = Entity.Type; string oldOrganizer = Entity.Organizer; DateTime?oldDate = Entity.Date; string oldLocation = Entity.Location; int? oldTickets = Entity.Tickets; double? oldPrice = Entity.Price; string oldDescription = Entity.Description; Entity.Name = Name; Entity.Type = Type; Entity.Organizer = Organizer; Entity.Date = Date; Entity.Location = Location; Entity.Tickets = Tickets; Entity.Price = Price; Entity.Description = Description; _eventRequester.Update(Id, Entity); UpdateCommand.RaiseCanExecuteChanged(); if (!_eventRequester.Update(Id, Entity)) { Entity.Name = oldName; Entity.Type = oldType; Entity.Organizer = oldOrganizer; Entity.Date = oldDate; Entity.Location = oldLocation; Entity.Tickets = oldTickets; Entity.Price = oldPrice; Entity.Description = oldDescription; } EventWindow eventWindow = App.Current.Windows.OfType <EventWindow>().FirstOrDefault(); eventWindow.Close(); //ew.Close(); }
public void Freeze_order_without_offers() { var order = MakeOrderClean(); var newOffer = new Offer(order.Price, 150); var random = Generator.Random(); newOffer.Id.OfferId += (ulong)random.First(); var catalog = localSession.Query <Catalog>().First(c => !c.HaveOffers); newOffer.ProducerSynonym = catalog.FullName; newOffer.ProductId = catalog.Id; newOffer.CatalogId = catalog.Id; newOffer.ProducerSynonymId = (uint?)random.First(); localSession.Save(newOffer); order.TryOrder(newOffer, 1); var cmd = new UpdateCommand(); Run(cmd); var text = cmd.Results.OfType <DialogResult>() .Select(r => (TextDoc)((DocModel <TextDoc>)r.Model).Model) .Select(m => m.Text) .First(); localSession.Clear(); Assert.That(text, Does.Contain("предложение отсутствует")); order = localSession.Load <Order>(order.Id); Assert.IsTrue(order.Frozen); Assert.AreEqual(1, order.Lines.Count); var orders = localSession.Query <Order>().ToList(); Assert.AreEqual(2, orders.Count); var newOrder = orders.First(o => o.Id != order.Id); Assert.AreEqual(1, newOrder.Lines.Count); }
/// <summary> /// Saves character information. /// </summary> /// <param name="character"></param> /// <returns></returns> public bool SaveCharacter(Character character) { using (var conn = this.GetConnection()) using (var cmd = new UpdateCommand("UPDATE `characters` SET {0} WHERE `characterId` = @characterId", conn)) { cmd.AddParameter("@characterId", character.Id); cmd.Set("name", character.Name); cmd.Set("job", (short)character.Job); cmd.Set("gender", (byte)character.Gender); cmd.Set("hair", character.Hair); cmd.Set("level", character.Level); cmd.Set("zone", character.MapId); cmd.Set("x", character.Position.X); cmd.Set("y", character.Position.Y); cmd.Set("z", character.Position.Z); cmd.Set("exp", character.Exp); cmd.Set("maxExp", character.MaxExp); cmd.Set("hp", character.Hp); cmd.Set("maxHp", character.MaxHp); cmd.Set("sp", character.Sp); cmd.Set("maxSp", character.MaxSp); cmd.Set("stamina", character.Stamina); cmd.Set("maxStamina", character.MaxStamina); cmd.Set("str", character.Str); cmd.Set("con", character.Con); cmd.Set("int", character.Int); cmd.Set("spr", character.Spr); cmd.Set("dex", character.Dex); cmd.Set("statByLevel", character.StatByLevel); cmd.Set("statByBonus", character.StatByBonus); cmd.Set("usedStat", character.UsedStat); cmd.Execute(); } this.SaveCharacterItems(character); this.SaveVariables("character:" + character.Id, character.Variables.Perm); return(false); }
// Override of base.VisitUpdate to provide for aliasing the table name to deal with some poorly named fields protected override Expression VisitUpdate(UpdateCommand update) { this.Write("UPDATE t0 "); this.WriteLine(Indentation.Same); bool saveHide = this.HideColumnAliases; this.HideColumnAliases = true; this.Write("SET "); for (int i = 0, n = update.Assignments.Count; i < n; i++) { ColumnAssignment ca = update.Assignments[i]; if (i > 0) { this.Write(", "); } this.Write("t0."); this.Visit(ca.Column); this.Write(" = "); this.Visit(ca.Expression); } this.WriteLine(Indentation.Same); this.Write(" FROM "); this.WriteTableName(update.Table.Name); this.Write(" t0 "); if (update.Where != null) { this.WriteLine(Indentation.Same); this.Write("WHERE "); this.Visit(update.Where); } this.HideColumnAliases = saveHide; return(update); }
public int Update(InventoryItem inventoryItem) { UpdateCommand.Parameters["@ID"].Value = inventoryItem.ID; UpdateCommand.Parameters["@ItemCode"].Value = inventoryItem.ItemCode; UpdateCommand.Parameters["@ItemName"].Value = inventoryItem.ItemName; UpdateCommand.Parameters["@UnitID"].Value = inventoryItem.UnitID; UpdateCommand.Parameters["@UnitName"].Value = inventoryItem.UnitName; UpdateCommand.Parameters["@PurchasePrice"].Value = inventoryItem.PurchasePrice; UpdateCommand.Parameters["@SalePrice"].Value = inventoryItem.SalePrice; UpdateCommand.Parameters["@Description"].Value = inventoryItem.Description; UpdateCommand.Parameters["@CustomIncomeAccountID"].Value = inventoryItem.CustomIncomeAccountID; UpdateCommand.Parameters["@CustomIncomeAccountName"].Value = inventoryItem.CustomIncomeAccountName; UpdateCommand.Parameters["@CustomExpenseAccountID"].Value = inventoryItem.CustomExpenseAccountID; UpdateCommand.Parameters["@CustomExpenseAccountName"].Value = inventoryItem.CustomExpenseAccountName; UpdateCommand.Parameters["@QtyToReceive"].Value = inventoryItem.QtyToReceive; UpdateCommand.Parameters["@QtyOnHand"].Value = inventoryItem.QtyOnHand; UpdateCommand.Parameters["@QtyToDeliver"].Value = inventoryItem.QtyToDeliver; UpdateCommand.Parameters["@QtyOwned"].Value = inventoryItem.QtyOwned; UpdateCommand.Parameters["@AverageCost"].Value = inventoryItem.AverageCost; UpdateCommand.Parameters["@TotalCost"].Value = inventoryItem.TotalCost; UpdateCommand.Parameters["@CreatedDate"].Value = inventoryItem.CreatedDate; UpdateCommand.Parameters["@Status"].Value = inventoryItem.Status; int returnValue = -1; try { UpdateCommand.Connection.Open(); returnValue = UpdateCommand.ExecuteNonQuery(); } catch (SqlException ex) { Logger.Write(ex); } finally { UpdateCommand.Connection.Close(); } return(returnValue); }
public void TestToolCommands() { var crc = new CreateRelativeCommand(string.Empty, string.Empty); var cac = new CreateAbsoluteCommand(string.Empty, string.Empty); var uc = new UpdateCommand(string.Empty, string.Empty); var tmpFile = Path.GetTempFileName(); crc.Arguments.Add(tmpFile); crc.Arguments.Add("ShellifyTool.exe"); crc.Execute(); crc.Arguments[1] = @"c:\foo"; try { crc.Execute(); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(ArgumentException)); } crc.Arguments[1] = @"foo"; crc.Execute(); cac.Arguments.Add(tmpFile); cac.Arguments.Add("ShellifyTool.exe"); cac.Execute(); cac.Arguments[1] = @"foo"; cac.Execute(); cac.Arguments[1] = "."; cac.Execute(); var on = ProgramContext.Options.ToList().First(o => o.Tag == "name"); on.Arguments.Add(string.Empty); uc.Arguments.Add(tmpFile); uc.Options.Add(on); uc.Execute(); }
public void TaskUpdate_ExecuteGenericService_ReturnsSuccessMessage() { _externalServiceService.Setup(s => s.GetExternalServiceByName("generic-service")).ReturnsAsync((string name) => new ExternalServiceDto { Id = 1, Name = name, ExternalServiceTypeName = ExternalServiceTypeName.Generic }); _jobDefinitionService.Setup(x => x.GetJobTaskDefinitionByName(1, 1, "Deploy")).ReturnsAsync((int projectId, int jobId, string taskName) => new JobTaskDefinitionDto { Id = 1, Type = "Deploy", JobDefinitionId = jobId, Name = taskName, Provider = "AzureAppService", Configs = new Dictionary <string, string> { { "AzureAppServiceExternalService", "azure-default" } }, AdditionalConfigs = new Dictionary <string, string> { { "SubscriptionId", "test" }, { "AppKey", "test" } } }); _consoleReader.Setup(x => x.GetPassword(It.IsAny <string>(), null, null)).Returns("testPassword"); var console = new TestConsole(_output, "generic-service"); var command = new UpdateCommand(console, LoggerMock.GetLogger <UpdateCommand>().Object, _consoleReader.Object, _projectService.Object, _jobDefinitionService.Object, _providerService.Object, _externalServiceService.Object, _externalServiceTypeService.Object) { Project = "Project 1", Job = "Default", Name = "Deploy" }; var resultMessage = command.Execute(); Assert.Equal("Task Deploy has been updated successfully", resultMessage); _jobDefinitionService.Verify(x => x.UpdateJobTaskDefinition(1, 1, 1, It.Is <UpdateJobTaskDefinitionDto>(t => t.AdditionalConfigs.Count == 2)), Times.Once); }
public void UpdateImage(int image, UpdateCommand cmd, UpdateFlags updateFlags) { ErrorCode ret; switch (IntPtr.Size) { case 4: UpdateCommand32[] cmds32 = new UpdateCommand32[1] { cmd.ToNativeStruct32() }; try { ret = NativeMethods.UpdateImage32(_ptr, image, cmds32, 1u, updateFlags); } finally { cmds32[0].Free(); } break; case 8: UpdateCommand64[] cmds64 = new UpdateCommand64[1] { cmd.ToNativeStruct64() }; try { ret = NativeMethods.UpdateImage64(_ptr, image, cmds64, 1u, updateFlags); } finally { cmds64[0].Free(); } break; default: throw new PlatformNotSupportedException(); } WimLibException.CheckWimLibError(ret); }
public void TestUpdateCommand_NotInstalled() { var command = new UpdateCommand(HostEnvironment); command.Configure(null); string contents = @"{ ""version"": ""1.0"", ""defaultProvider"": ""cdnjs"", ""defaultDestination"": ""wwwroot"", ""libraries"": [ { ""library"": ""[email protected]"", ""files"": [ ""jquery.min.js"", ""jquery.js"" ] } ] }"; string libmanjsonPath = Path.Combine(WorkingDir, "libman.json"); File.WriteAllText(libmanjsonPath, contents); var restoreCommand = new RestoreCommand(HostEnvironment); restoreCommand.Configure(null); restoreCommand.Execute(); int result = command.Execute("jqu"); string actualText = File.ReadAllText(libmanjsonPath); Assert.AreEqual(StringHelper.NormalizeNewLines(contents), StringHelper.NormalizeNewLines(actualText)); var logger = HostEnvironment.Logger as TestLogger; string message = "No library found with name \"jqu\" to update.\r\nPlease specify a library name without the version information to update."; Assert.AreEqual(StringHelper.NormalizeNewLines(message), StringHelper.NormalizeNewLines(logger.Messages.Last().Value)); }
public override void Write(byte[] buffer, int offset, int count) { byte[] data = buffer; if (offset != 0 || count != buffer.Length) { data = new byte[count]; Array.Copy(buffer, offset, data, 0, count); } if (0 == Position && null != InsertCommand) { InsertDataParam.Value = data; InsertCommand.ExecuteNonQuery(); } else { UpdateDataParam.Value = data; UpdateCommand.ExecuteNonQuery(); } Position += count; }
public IActionResult GetCodePromotion([FromBody] UpdateCommand command) { try { var result = context.Tb_UserPromotion.FirstOrDefault(up => up.UserId == command.UserId && up.PromotionId == command.PromotionId && up.Status == 1); if (result == null) { return(BadRequest()); } else { result.History = true; context.SaveChanges(); string code = RandomCode(); return(Ok(code)); } } catch (Exception e) { return(BadRequest(e.Message)); } }
public async Task <DbStatus> Update(Category entity) { // Category with specified id doesn't exists Category existingCategory = await GetByPrimaryKey(entity); if (existingCategory == null) { return(DbStatus.NOT_FOUND); } Category categoryWithSameName = await GetByUniqueIdentifiers(new string[] { "Name" }, entity); if (categoryWithSameName != null && existingCategory.Name != entity.Name) { return(DbStatus.EXISTS); } DbCommand <Category> updateCommand = new UpdateCommand <Category>(); DbStatus status = await ServiceHelper <Category> .ExecuteCRUDCommand(updateCommand, entity); return(status); }
public void ShouldContainNoErrors() { // Arrange Optional <string> login = new Optional <string>("Login"); Optional <string> password = new Optional <string>("Password$my"); Optional <string> firstName = new Optional <string>("FirstName"); Optional <string> lastName = new Optional <string>("LastName"); var command = new UpdateCommand(id: Guid.NewGuid(), login: login, password: password, firstName: firstName, lastName: lastName, version: 0); // Act var validationResult = _validator.Validate(command); var exists = validationResult.Errors.Count > 0; // Assert exists.Should().BeFalse(); }
/// <summary> /// Update Location Address /// </summary> /// <param name="corrigoService"></param> /// <param name="location"></param> /// <returns></returns> public static void UpdateLocationAddress(CorrigoService corrigoService, Location location) { if (location?.Address == null) { return; } location.Address.Street = $"Disneyland {location.Address.Street ?? ""}"; var command = new UpdateCommand { Entity = location, PropertySet = new PropertySet { Properties = new[] { "Address.Street" } } }; var response = corrigoService.Execute(command) as OperationCommandResponse; Console.WriteLine(response?.ErrorInfo?.Description ?? $"Successfully updated Location with id {location.Id}"); //Console.ReadKey(); }
public virtual async Task <IActionResult> Update(int id, T model, [FromServices] IMediator mediator) { if (model.Id != id) //ModelState.IsValid & model != null checked automatically due to [ApiController] { return(Problem(statusCode: StatusCodes.Status400BadRequest, detail: $"Different ids: {id} vs {model.Id}")); } else { var query = new GetSingleItemQuery <T>(id); var item = await mediator.Send(query); if (item == null) { return(Problem(statusCode: StatusCodes.Status404NotFound, detail: $"Invalid id = {id}")); } var command = new UpdateCommand <T>(model); await mediator.Send(command); return(NoContent()); } }
public void Update() { string sampleDir = Path.Combine(TestSetup.SampleDir); Update_Template("XPRESS.wim", new UpdateCommand[2] { UpdateCommand.SetAdd(Path.Combine(sampleDir, "Append01", "Z.txt"), "ADD", null, AddFlags.DEFAULT), UpdateCommand.SetAdd(Path.Combine(sampleDir, "Src03", "가"), "유니코드", null, AddFlags.DEFAULT), }); Update_Template("LZX.wim", new UpdateCommand[2] { UpdateCommand.SetDelete("ACDE.txt", DeleteFlags.DEFAULT), UpdateCommand.SetDelete("ABCD", DeleteFlags.RECURSIVE), }); Update_Template("LZMS.wim", new UpdateCommand[2] { UpdateCommand.SetRename("ACDE.txt", "FILE"), UpdateCommand.SetRename("ABCD", "DIR"), }); }
internal DataProvider(Type type, ICache cache, IDataAccess access, ISqlCommandGenerator sqlCommandGenerator) { EntityType = type; SqlCommandGenerator = sqlCommandGenerator; Cache = cache; Access = access; MetaData = DataProviderMetaDataGenerator.Generate(type); DeleteCommand = SqlCommandGenerator.GenerateDeleteCommand(MetaData); UpdateCommand = SqlCommandGenerator.GenerateUpdateCommand(MetaData); InsertCommand = SqlCommandGenerator.GenerateInsertCommand(MetaData); if (UpdateCommand.IsEmpty()) { UpdateSelf = entity => Task.CompletedTask; } else { UpdateSelf = UpdateSelfImpl; } }
public async Task <DbStatus> Update(Account entity) { // Account with specified id doesn't exists Account existingAccount = await GetByPrimaryKey(entity); if (existingAccount == null) { return(DbStatus.NOT_FOUND); } Account accountWithSameUsername = await GetByUniqueIdentifiers(new string[] { "Username" }, entity); if (accountWithSameUsername != null && existingAccount.Username != entity.Username) { return(DbStatus.EXISTS); } DbCommand <Account> updateCommand = new UpdateCommand <Account>(); DbStatus status = await ServiceHelper <Account> .ExecuteCRUDCommand(updateCommand, entity); return(status); }
public KeepAliveViewModel(ISourcesCacheProvider cacheProvider) { KeepAliveSource = new SourceList <KeepAliveItem>(); KeepAliveSource .Connect() .ObserveOnDispatcher() .Bind(out var keepAliveItems) .Subscribe() .DisposeWith(Disposables); KeepAliveList = keepAliveItems; _model = new KeepAliveModel { Caption = "KeepAlives", Cache = cacheProvider.CurrentCache }; Disposables.Add(_model); _model.WhenAnyValue(x => x.Caption, x => x.Online) .Subscribe(v => Title = v.Item1 + (v.Item2 ? " >" : " ||")); var canStart = _model.WhenAny(x => x.Online, x => !x.Value); StartCommand = ReactiveCommand.Create(OnStart, canStart); var canStop = _model.WhenAny(x => x.Online, x => x.Value); StopCommand = ReactiveCommand.Create(OnStop, canStop); UpdateCommand = ReactiveCommand.Create(OnUpdate, canStop); UpdateCommand.Subscribe(results => KeepAliveSource.Edit(innerList => { innerList.Clear(); innerList.AddRange(results); })); }
public override Expression GetUpdateExpression(MappingEntity entity, Expression instance, LambdaExpression updateCheck, LambdaExpression selector, Expression @else) { var tableAlias = new TableAlias(); var table = new TableExpression(tableAlias, entity, this.mapping.GetTableName(entity)); var where = this.GetIdentityCheck(table, entity, instance); if (updateCheck != null) { Expression typeProjector = this.GetEntityExpression(table, entity); Expression pred = DbExpressionReplacer.Replace(updateCheck.Body, updateCheck.Parameters[0], typeProjector); where = where.And(pred); } var assignments = this.GetColumnAssignments(table, instance, entity, (e, m) => this.mapping.IsUpdatable(e, m)); Expression update = new UpdateCommand(table, where, assignments); if (selector != null) { return new BlockCommand( update, new IFCommand( this.translator.Linguist.Language.GetRowsAffectedExpression(update).GreaterThan(Expression.Constant(0)), this.GetUpdateResult(entity, instance, selector), @else ) ); } else if (@else != null) { return new BlockCommand( update, new IFCommand( this.translator.Linguist.Language.GetRowsAffectedExpression(update).LessThanOrEqual(Expression.Constant(0)), @else, null ) ); } else { return update; } }
//Update Command private void SendUpdateCommandBtn_Click(object sender, RoutedEventArgs e) { string appDir = System.IO.Path.Combine(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.LastIndexOf(System.IO.Path.DirectorySeparatorChar))); string rootpath = GetDestDirName(appDir); string xmlPath = string.Empty; ComboBoxItem item = (ComboBoxItem)this.UpdateNameComboBox.SelectedItem; string updateName = item.Content.ToString(); UpdateCommand updateCommand = new UpdateCommand(); XmlDocument doc = new XmlDocument(); switch (updateName) { case "PrivateDailyQuotation": xmlPath = System.IO.Path.Combine(rootpath, "Commands\\AccountUpdate.xml"); break; case "SystemParameter": break; case "Instruments": break; case "Instrument": break; case "Account": xmlPath = System.IO.Path.Combine(rootpath, "Commands\\AccountUpdate.xml"); break; case "Customers": break; case "Customer": break; case "QuotePolicy": break; case "QuotePolicyDetails": break; case "QuotePolicyDetail": break; case "TradePolicy": break; case "TradePolicyDetail": break; case "TradePolicyDetails": break; case "DealingConsoleInstrument": break; } doc.Load(xmlPath); updateCommand.Content = doc.DocumentElement; ManagerClient.AddCommand(updateCommand); }
protected override Expression VisitUpdate(UpdateCommand update) { this.Append("UPDATE "); WriteTableName(update.Table.Mapping); //if (Dialect.SupportSchema && !string.IsNullOrEmpty(update.Table.Mapping.Schema)) //{ // sb.Append(Dialect.Quote(update.Table.Mapping.Schema)); // sb.Append("."); //} //this.AppendTableName(update.Table.Name); this.AppendLine(Indentation.Same); bool saveHide = this.HideColumnAliases; this.HideColumnAliases = true; this.Append("SET "); for (int i = 0, n = update.Assignments.Count; i < n; i++) { ColumnAssignment ca = update.Assignments[i]; if (i > 0) this.Append(", "); this.Visit(ca.Column); this.Append(" = "); this.Visit(ca.Expression); } if (update.Where != null) { this.AppendLine(Indentation.Same); this.Append("WHERE "); this.VisitPredicate(update.Where); } this.HideColumnAliases = saveHide; return update; }
public static OperationResult ExcluirTodos( DataFieldCollection pValues, Transaction pTransactionAtivo, ConnectionInfo pInfo ) { Transaction pTransaction; bool lLocalTransaction = (pTransactionAtivo == null); if (lLocalTransaction) pTransaction = new Transaction(Instance.CreateDatabase(pInfo)); else pTransaction = pTransactionAtivo; UpdateCommand lUpdate; OperationResult lReturn = new OperationResult(SituacaoFamiliarResideQD.TableName, SituacaoFamiliarResideQD.TableName); ValidateUpdate(pValues, lReturn); if (lReturn.IsValid) { try { lUpdate = new UpdateCommand(SituacaoFamiliarResideQD.TableName); foreach (DataField lField in pValues.Keys) { if ((lField.Name != SituacaoFamiliarResideQD._STFAM_ID.Name)) lUpdate.Fields.Add(lField.Name, pValues[lField], (ItemType)lField.DBType); } string lSql = ""; lSql = String.Format("WHERE {0} = <<{0}", SituacaoFamiliarResideQD._STFAM_ID.Name); lUpdate.Condition = lSql; lUpdate.Conditions.Add(SituacaoFamiliarResideQD._STFAM_ID.Name, pValues[SituacaoFamiliarResideQD._STFAM_ID].DBToDecimal()); lUpdate.Execute(pTransaction); if (!lReturn.HasError) { if (lLocalTransaction) { if (!lReturn.HasError) { pTransaction.Commit(); } else { pTransaction.Rollback(); } } } else { if (lLocalTransaction) pTransaction.Rollback(); } } catch (Exception ex) { lReturn.OperationException = new SerializableException(ex); if (lLocalTransaction) pTransaction.Rollback(); } } return lReturn; }
protected override Expression VisitUpdate(UpdateCommand update) { this.Write("UPDATE "); this.WriteTableName(update.Table.Name); this.WriteLine(Indentation.Same); bool saveHide = this.HideColumnAliases; this.HideColumnAliases = true; this.Write("SET "); for (int i = 0, n = update.Assignments.Count; i < n; i++) { ColumnAssignment ca = update.Assignments[i]; if (i > 0) this.Write(", "); this.Visit(ca.Column); this.Write(" = "); this.Visit(ca.Expression); } if (update.Where != null) { this.WriteLine(Indentation.Same); this.Write("WHERE "); this.VisitPredicate(update.Where); } this.HideColumnAliases = saveHide; return update; }
public ZipUpdate(UpdateCommand command, ZipEntry entry) { command_ = command; entry_ = ( ZipEntry )entry.Clone(); #if FORCE_ZIP64 entry_.ForceZip64(); #endif }
public ZipUpdate(string fileName, string entryName, CompressionMethod compressionMethod) { command_ = UpdateCommand.Add; entry_ = new ZipEntry(entryName); entry_.CompressionMethod = compressionMethod; filename_ = fileName; }
public ZipUpdate(string fileName, ZipEntry entry) { command_ = UpdateCommand.Add; entry_ = entry; filename_ = fileName; }
public static OperationResult Update( DataFieldCollection pValues, ConnectionInfo pInfo ) { Transaction pTransaction; pTransaction = new Transaction(Instance.CreateDatabase(pInfo)); bool lLocalTransaction = (pTransaction != null); UpdateCommand lUpdate; OperationResult lReturn = new OperationResult(NucleoQD.TableName, NucleoQD.TableName); ValidateUpdate(pValues, lReturn); if (lReturn.IsValid) { try { if (lLocalTransaction) { lReturn.Trace("Transação local, instanciando banco..."); } //16/10/2012 Ricardo Almeida - retirada da função, pois registro não pode ser excluido se estiver usuário cadastrado //lReturn = NucleoxAreaAtuacaoDo.Exluir_ByNUC_ID(pValues[NucleoQD._NUC_ID].DBToDecimal(), pInfo); //if (lReturn.HasError) //{ // if (lLocalTransaction) // pTransaction.Rollback(); // return lReturn; //} lReturn = NucleoxSecretariaDo.Exluir_ByNUC_ID(pValues[NucleoQD._NUC_ID].DBToDecimal(), pInfo); if (!lReturn.HasError) { lUpdate = new UpdateCommand(NucleoQD.TableName); lReturn.Trace("Adicionando campos ao objeto de update"); foreach (DataField lField in pValues.Keys) { if ((lField.Name != NucleoQD._NUC_ID.Name)) lUpdate.Fields.Add(lField.Name, pValues[lField], (ItemType)lField.DBType); } string lSql = ""; lSql = String.Format("WHERE {0} = <<{0}", NucleoQD._NUC_ID.Name); lUpdate.Condition = lSql; lUpdate.Conditions.Add(NucleoQD._NUC_ID.Name, pValues[NucleoQD._NUC_ID].DBToDecimal()); lReturn.Trace("Executando o Update"); lUpdate.Execute(pTransaction); } if (!lReturn.HasError) { if (lLocalTransaction) { if (!lReturn.HasError) { lReturn.Trace("Update finalizado, executando commit"); pTransaction.Commit(); } else { pTransaction.Rollback(); } } } else { if (lLocalTransaction) pTransaction.Rollback(); } } catch (Exception ex) { lReturn.OperationException = new SerializableException(ex); if (lLocalTransaction) pTransaction.Rollback(); } } return lReturn; }
public virtual Expression GetUpdateExpression(IEntityMapping mapping, Expression instance, LambdaExpression updateCheck, LambdaExpression selector, Expression @else) { var tableAlias = new TableAlias(); var table = new TableExpression(tableAlias, mapping); var where = this.GetIdentityCheck(table, mapping, instance); if (updateCheck != null) { Expression typeProjector = this.GetEntityExpression(table, mapping); Expression pred = DbExpressionReplacer.Replace(updateCheck.Body, updateCheck.Parameters[0], typeProjector); where = where != null ? where.And(pred) : pred; } var assignments = this.GetColumnAssignments(table, instance, mapping, m => m.IsUpdatable && !m.IsVersion); var version = mapping.Version; bool supportsVersionCheck = false; if (version != null) { var versionValue = GetVersionValue(mapping, instance); var versionExp = Expression.Constant(versionValue, version.MemberType); var memberExpression = GetMemberExpression(table, mapping, mapping.Version); var versionCheck = memberExpression.Equal(versionExp); where = (where != null) ? where.And(versionCheck) : versionCheck; if (version.MemberType.IsNullable()) { var versionAssignment = new ColumnAssignment( memberExpression as ColumnExpression, versionValue == null ? (Expression)Expression.Constant(1, version.MemberType) : Expression.Add(memberExpression, Expression.Constant(1, version.MemberType)) ); assignments.Add(versionAssignment); supportsVersionCheck = true; } else { var versionAssignment = new ColumnAssignment( memberExpression as ColumnExpression, Expression.Add(memberExpression, Expression.Constant(1, version.MemberType)) ); assignments.Add(versionAssignment); supportsVersionCheck = true; } } object o = null; var c = instance as ConstantExpression; if (c != null) o = c.Value; Expression update = new UpdateCommand(table, where, o, supportsVersionCheck, assignments); if (selector != null) { return new BlockCommand( update, new IFCommand( this.GetRowsAffectedExpression(update).GreaterThan(Expression.Constant(0)), this.GetUpdateResult(mapping, instance, selector), @else ) ); } else if (@else != null) { return new BlockCommand( update, new IFCommand( this.GetRowsAffectedExpression(update).LessThanOrEqual(Expression.Constant(0)), @else, null ) ); } else { return update; } }
public ZipUpdate(string fileName, string entryName) { command_ = UpdateCommand.Add; entry_ = new ZipEntry(entryName); filename_ = fileName; }
protected UpdateCommand UpdateUpdate(UpdateCommand update, TableExpression table, Expression where, IEnumerable<ColumnAssignment> assignments) { if (table != update.Table || where != update.Where || assignments != update.Assignments) { return new UpdateCommand(table, where, assignments); } return update; }
protected virtual bool CompareUpdate(UpdateCommand x, UpdateCommand y) { return this.Compare(x.Table, y.Table) && this.Compare(x.Where, y.Where) && this.CompareColumnAssignments(x.Assignments, y.Assignments); }
private IEnumerable<IEntityStateEntry> DetermineStateEntriesFromSource(UpdateCommand source) { if (null == source) { return Enumerable.Empty<IEntityStateEntry>(); } return source.GetStateEntries(this); }
public static OperationResult Exluir_ByNUC_ID( decimal pNUC_ID, ConnectionInfo pInfo ) { Transaction pTransaction; pTransaction = new Transaction(Instance.CreateDatabase(pInfo)); bool lLocalTransaction = (pTransaction != null); UpdateCommand lUpdate; OperationResult lReturn = new OperationResult(NucleoxSecretariaQD.TableName, NucleoxSecretariaQD.TableName); if (lReturn.IsValid) { try { if (lLocalTransaction) { lReturn.Trace("Transação local, instanciando banco..."); } lUpdate = new UpdateCommand(NucleoxSecretariaQD.TableName); lReturn.Trace("Adicionando campos ao objeto de update"); lUpdate.Fields.Add(NucleoxSecretariaQD._NUCSCT_STATUS.Name, "I", (ItemType)NucleoxSecretariaQD._NUCSCT_STATUS.DBType); string lSql = ""; lSql = String.Format("WHERE {0} = <<{0}", NucleoxSecretariaQD._NUC_ID.Name); lUpdate.Condition = lSql; lUpdate.Conditions.Add(NucleoxSecretariaQD._NUC_ID.Name, pNUC_ID); lReturn.Trace("Executando o Update"); lUpdate.Execute(pTransaction); if (!lReturn.HasError) { if (lLocalTransaction) { if (!lReturn.HasError) { lReturn.Trace("Update finalizado, executando commit"); pTransaction.Commit(); } else { pTransaction.Rollback(); } } } else { if (lLocalTransaction) pTransaction.Rollback(); } } catch (Exception ex) { lReturn.OperationException = new SerializableException(ex); if (lLocalTransaction) pTransaction.Rollback(); } } return lReturn; }
public ZipUpdate(IStaticDataSource dataSource, string entryName, CompressionMethod compressionMethod) { command_ = UpdateCommand.Add; entry_ = new ZipEntry(entryName); entry_.CompressionMethod = compressionMethod; dataSource_ = dataSource; }
protected virtual Expression VisitUpdate(UpdateCommand update) { var table = (TableExpression)this.Visit(update.Table); var where = this.Visit(update.Where); var assignments = this.VisitColumnAssignments(update.Assignments); return this.UpdateUpdate(update, table, where, assignments); }
public ZipUpdate(IStaticDataSource dataSource, ZipEntry entry) { command_ = UpdateCommand.Add; entry_ = entry; dataSource_ = dataSource; }
internal override int CompareToType(UpdateCommand otherCommand) { Debug.Assert(!ReferenceEquals(this, otherCommand), "caller is supposed to ensure otherCommand is different reference"); var other = (DynamicUpdateCommand)otherCommand; // order by operation type var result = (int)Operator - (int)other.Operator; if (0 != result) { return result; } // order by Container.Table result = StringComparer.Ordinal.Compare(_processor.Table.Name, other._processor.Table.Name); if (0 != result) { return result; } result = StringComparer.Ordinal.Compare(_processor.Table.EntityContainer.Name, other._processor.Table.EntityContainer.Name); if (0 != result) { return result; } // order by table key var thisResult = (Operator == ModificationOperator.Delete ? OriginalValues : CurrentValues); var otherResult = (other.Operator == ModificationOperator.Delete ? other.OriginalValues : other.CurrentValues); for (var i = 0; i < _processor.KeyOrdinals.Length; i++) { var keyOrdinal = _processor.KeyOrdinals[i]; var thisValue = thisResult.GetMemberValue(keyOrdinal).GetSimpleValue(); var otherValue = otherResult.GetMemberValue(keyOrdinal).GetSimpleValue(); result = ByValueComparer.Default.Compare(thisValue, otherValue); if (0 != result) { return result; } } // If the result is still zero, it means key values are all the same. Switch to synthetic identifiers // to differentiate. for (var i = 0; i < _processor.KeyOrdinals.Length; i++) { var keyOrdinal = _processor.KeyOrdinals[i]; var thisValue = thisResult.GetMemberValue(keyOrdinal).Identifier; var otherValue = otherResult.GetMemberValue(keyOrdinal).Identifier; result = thisValue - otherValue; if (0 != result) { return result; } } return result; }
public BlubbUpdate( UpdateCommand command, BlubbZipEntry entry ) { command_ = command; entry_ = (BlubbZipEntry)entry.Clone(); }
public static OperationResult Update( DataFieldCollection pValues, List<DataFieldCollection> pListValuesSFR, DataFieldCollection pValuesSFRExcluir, ConnectionInfo pInfo ) { Transaction pTransaction; pTransaction = new Transaction(Instance.CreateDatabase(pInfo)); bool lLocalTransaction = (pTransaction != null); UpdateCommand lUpdate; OperationResult lReturn = new OperationResult(SituacaoFamiliarQD.TableName, SituacaoFamiliarQD.TableName); ValidateUpdate(pValues, lReturn); if (lReturn.IsValid) { try { lUpdate = new UpdateCommand(SituacaoFamiliarQD.TableName); foreach (DataField lField in pValues.Keys) { if ((lField.Name != SituacaoFamiliarQD._PES_ID.Name) && (lField.Name != SituacaoFamiliarQD._STFAM_ID.Name)) lUpdate.Fields.Add(lField.Name, pValues[lField], (ItemType)lField.DBType); } string lSql = ""; lSql = String.Format("WHERE {0} = <<{0}", SituacaoFamiliarQD._PES_ID.Name); lUpdate.Condition = lSql; lUpdate.Conditions.Add(SituacaoFamiliarQD._PES_ID.Name, pValues[SituacaoFamiliarQD._PES_ID].DBToDecimal()); lUpdate.Execute(pTransaction); if (!lReturn.HasError) { if (pListValuesSFR.Count > 0) { //1º Exclui todos os registros ja salvos lReturn = SituacaoFamiliarResideDo.ExcluirTodos(pValuesSFRExcluir, pTransaction, pInfo); if (lReturn.HasError) { pTransaction.Rollback(); return lReturn; } //2º inclui os novos registros foreach (DataFieldCollection lFields in pListValuesSFR) { lFields.Add(SituacaoFamiliarResideQD._STFAM_ID, pValues[SituacaoFamiliarQD._STFAM_ID].DBToDecimal()); lReturn = SituacaoFamiliarResideDo.Insert(lFields, pTransaction, pInfo); if (lReturn.HasError) { pTransaction.Rollback(); return lReturn; } } } if (lLocalTransaction) { if (!lReturn.HasError) { pTransaction.Commit(); } else { pTransaction.Rollback(); } } } else { if (lLocalTransaction) pTransaction.Rollback(); } } catch (Exception ex) { lReturn.OperationException = new SerializableException(ex); if (lLocalTransaction) pTransaction.Rollback(); } } return lReturn; }
public ZipUpdate(UpdateCommand command, ZipEntry entry) { command_ = command; entry_ = ( ZipEntry )entry.Clone(); }
internal override int CompareToType(UpdateCommand otherCommand) { Debug.Assert(!ReferenceEquals(this, otherCommand), "caller should ensure other command is different"); var other = (FunctionUpdateCommand)otherCommand; // first state entry is the 'main' state entry for the command (see ctor) var thisParent = _stateEntries[0]; var otherParent = other._stateEntries[0]; // order by operator var result = (int)GetModificationOperator(thisParent.State) - (int)GetModificationOperator(otherParent.State); if (0 != result) { return result; } // order by entity set result = StringComparer.Ordinal.Compare(thisParent.EntitySet.Name, otherParent.EntitySet.Name); if (0 != result) { return result; } result = StringComparer.Ordinal.Compare(thisParent.EntitySet.EntityContainer.Name, otherParent.EntitySet.EntityContainer.Name); if (0 != result) { return result; } // order by key values var thisInputIdentifierCount = (null == _inputIdentifiers ? 0 : _inputIdentifiers.Count); var otherInputIdentifierCount = (null == other._inputIdentifiers ? 0 : other._inputIdentifiers.Count); result = thisInputIdentifierCount - otherInputIdentifierCount; if (0 != result) { return result; } for (var i = 0; i < thisInputIdentifierCount; i++) { var thisParameter = _inputIdentifiers[i].Value; var otherParameter = other._inputIdentifiers[i].Value; result = ByValueComparer.Default.Compare(thisParameter.Value, otherParameter.Value); if (0 != result) { return result; } } // If the result is still zero, it means key values are all the same. Switch to synthetic identifiers // to differentiate. for (var i = 0; i < thisInputIdentifierCount; i++) { var thisIdentifier = _inputIdentifiers[i].Key; var otherIdentifier = other._inputIdentifiers[i].Key; result = thisIdentifier - otherIdentifier; if (0 != result) { return result; } } return result; }
public static OperationResult Update( DataFieldCollection pValues, List<DataFieldCollection> pListAtuaInc, List<DataFieldCollection> pListAtuaUpd, DataFieldCollection pValuesAtuaExcluir, List<DataFieldCollection> pListPermissao, ConnectionInfo pInfo ) { Transaction pTransaction; pTransaction = new Transaction(Instance.CreateDatabase(pInfo)); bool lLocalTransaction = (pTransaction != null); UpdateCommand lUpdate; OperationResult lReturn = new OperationResult(PessoaFuncaoQD.TableName, PessoaFuncaoQD.TableName); ValidateUpdate(pValues, lReturn); if (lReturn.IsValid) { try { lUpdate = new UpdateCommand(PessoaFuncaoQD.TableName); foreach (DataField lField in pValues.Keys) { if ((lField.Name != PessoaFuncaoQD._PESF_ID.Name)) lUpdate.Fields.Add(lField.Name, pValues[lField], (ItemType)lField.DBType); } string lSql = ""; lSql = String.Format("WHERE {0} = <<{0}", PessoaFuncaoQD._PESF_ID.Name); lUpdate.Condition = lSql; lUpdate.Conditions.Add(PessoaFuncaoQD._PESF_ID.Name, pValues[PessoaFuncaoQD._PESF_ID].DBToDecimal()); lUpdate.Execute(pTransaction); if (!lReturn.HasError) { //Excluir atuação do núcleo alterado if (pValuesAtuaExcluir.Count > 0) { lReturn = AtuacaoDo.UpdateInativo(pValuesAtuaExcluir, pInfo); if (lReturn.HasError) { pTransaction.Rollback(); return lReturn; } } if (pListAtuaInc.Count > 0) { foreach (DataFieldCollection lFields in pListAtuaInc) { lReturn = AtuacaoDo.Insert(lFields, pTransaction, pInfo); if (lReturn.HasError) { pTransaction.Rollback(); return lReturn; } } } if (pListAtuaUpd.Count > 0) { foreach (DataFieldCollection lFields in pListAtuaUpd) { lReturn = AtuacaoDo.Update(lFields, pTransaction, pInfo); if (lReturn.HasError) { pTransaction.Rollback(); return lReturn; } } } if (pListPermissao.Count > 0) { foreach (DataFieldCollection lFields in pListPermissao) { lReturn = SecurityUsersDtDo.Insert(lFields, pTransaction, pInfo); if (lReturn.HasError) { pTransaction.Rollback(); return lReturn; } } } if (!lReturn.HasError) { pTransaction.Commit(); } else { pTransaction.Rollback(); } } else { if (lLocalTransaction) pTransaction.Rollback(); } } catch (Exception ex) { lReturn.OperationException = new SerializableException(ex); if (lLocalTransaction) pTransaction.Rollback(); } } return lReturn; }
public static OperationResult UpdateInativo( DataFieldCollection pValues, ConnectionInfo pInfo ) { Transaction pTransaction; pTransaction = new Transaction(Instance.CreateDatabase(pInfo)); bool lLocalTransaction = (pTransaction != null); UpdateCommand lUpdate; OperationResult lReturn = new OperationResult(AtuacaoQD.TableName, AtuacaoQD.TableName); if (lReturn.IsValid) { try { lUpdate = new UpdateCommand(AtuacaoQD.TableName); foreach (DataField lField in pValues.Keys) { if ((lField.Name != AtuacaoQD._PESF_ID.Name)) lUpdate.Fields.Add(lField.Name, pValues[lField], (ItemType)lField.DBType); } string lSql = ""; lSql = String.Format("WHERE {0} = <<{0}", AtuacaoQD._PESF_ID.Name); lUpdate.Condition = lSql; lUpdate.Conditions.Add(AtuacaoQD._PESF_ID.Name, pValues[AtuacaoQD._PESF_ID].DBToDecimal()); lUpdate.Execute(pTransaction); if (!lReturn.HasError) { if (lLocalTransaction) { if (!lReturn.HasError) { pTransaction.Commit(); } else { pTransaction.Rollback(); } } } else { if (lLocalTransaction) pTransaction.Rollback(); } } catch (Exception ex) { lReturn.OperationException = new SerializableException(ex); if (lLocalTransaction) pTransaction.Rollback(); } } return lReturn; }
public static OperationResult Update( DataFieldCollection pValues, ConnectionInfo pInfo ) { Transaction pTransaction; pTransaction = new Transaction(Instance.CreateDatabase(pInfo)); bool lLocalTransaction = (pTransaction != null); UpdateCommand lUpdate; OperationResult lReturn = new OperationResult(PLANOINTERNOQD.TableName, PLANOINTERNOQD.TableName); ValidateUpdate(pValues, lReturn); if (lReturn.IsValid) { try { if (lLocalTransaction) { lReturn.Trace("Transação local, instanciando banco..."); } lUpdate = new UpdateCommand(PLANOINTERNOQD.TableName); lReturn.Trace("Adicionando campos ao objeto de update"); foreach (DataField lField in pValues.Keys) { if ((lField.Name != PLANOINTERNOQD._PLANI_ID.Name)) lUpdate.Fields.Add(lField.Name, pValues[lField], (ItemType)lField.DBType); } string lSql = ""; lSql = String.Format("WHERE {0} = <<{0}", PLANOINTERNOQD._PLANI_ID.Name); lUpdate.Condition = lSql; lUpdate.Conditions.Add(PLANOINTERNOQD._PLANI_ID.Name, pValues[PLANOINTERNOQD._PLANI_ID].DBToDecimal()); lReturn.Trace("Executando o Update"); lUpdate.Execute(pTransaction); if (!lReturn.HasError) { if (lLocalTransaction) { if (!lReturn.HasError) { lReturn.Trace("Update finalizado, executando commit"); pTransaction.Commit(); } else { pTransaction.Rollback(); } } } else { if (lLocalTransaction) pTransaction.Rollback(); } } catch (Exception ex) { lReturn.OperationException = new SerializableException(ex); if (lLocalTransaction) pTransaction.Rollback(); } } return lReturn; }
public static string ChangePassword(decimal pSusr_Id, string pSusr_Login, string pSusr_Password_old, string pSusr_Password_new, ConnectionInfo pConnectionInfo) { bool lPasswordOK; string lPassword; string lResult = ""; OperationResult lReturn; Transaction pTransaction; pTransaction = new Transaction(Instance.CreateDatabase(pConnectionInfo)); // Validando a Senha Digitada. lPassword = GetPassword(pSusr_Login, pConnectionInfo); lPasswordOK = (lPassword == pSusr_Password_old) ? true : false; if (!lPasswordOK) lResult = "Senha Atual Incorreta"; // Verificando Transação bool lLocalTransaction = (pTransaction != null); UpdateCommand lUpdate; lReturn = new OperationResult(SystemUserQD.TableName, SystemUserQD.TableName); if (lPasswordOK) { // Iniciando processo de update... if (lReturn.IsValid) { try { if (lLocalTransaction) { lReturn.Trace("ExternalUser: Transação local, instanciando banco..."); } lUpdate = new UpdateCommand(SystemUserQD.TableName); lReturn.Trace("ExternalUser: Adicionando campos ao objeto de update"); lUpdate.Fields.Add(SystemUserQD._SUSR_PASSWORD.Name, APB.Framework.Encryption.Crypto.Encode(pSusr_Password_new), (ItemType)SystemUserQD._SUSR_PASSWORD.DBType); string lSql = ""; //TODO: Condição where customizada lSql = String.Format("WHERE {0} = >>{0}", SystemUserQD._SUSR_ID.Name); lUpdate.Condition = lSql; lUpdate.Conditions.Add(SystemUserQD._SUSR_ID.Name, pSusr_Id); lReturn.Trace("ExternalUser: Executando o Update"); lUpdate.Execute(pTransaction); if (!lReturn.HasError) { if (lLocalTransaction) { if (!lReturn.HasError) { lReturn.Trace("ExternalUser: Update finalizado, executando commit"); pTransaction.Commit(); } else { pTransaction.Rollback(); } } } else { if (lLocalTransaction) pTransaction.Rollback(); } } catch (Exception ex) { lReturn.OperationException = new SerializableException(ex); if (lLocalTransaction) pTransaction.Rollback(); } } } else { return "Senha atual incorreta"; } if (lReturn.IsValid) lResult = ""; else lResult = lReturn.ToString(); return lResult; }