protected override async Task <TResult> InterceptAsync <TResult>(IInvocation invocation, IInvocationProceedInfo proceedInfo, Func <IInvocation, IInvocationProceedInfo, Task <TResult> > proceed) { MethodInfo methodInfo = invocation.MethodInvocationTarget; TransactionAttribute transactionAttribute = TransactionUtils.FindTransactionAttribute(methodInfo); bool bindingRequired = transactionAttribute != null; if (bindingRequired) { using (SessionWrapper sessionWrapper = sessionService.GetCurrentSession(transactionAttribute.ReadOnly)) { using (TransactionWrapper transactionWrapper = sessionWrapper.BuildTransaction( transactionAttribute.ReadOnly, transactionAttribute.IsolationLevel)) { TResult retObject = await proceed(invocation, proceedInfo).ConfigureAwait(false); await transactionWrapper.Commit().ConfigureAwait(false); return(retObject); } } } { TResult retObject = await proceed(invocation, proceedInfo).ConfigureAwait(false); return(retObject); } }
public void Send(TransportMessage toSend, IEnumerable <string> destinations) { TransactionWrapper.RunInTransaction(transaction => { toSend.TimeSent = DateTime.UtcNow; toSend.ReturnAddress = this.ReturnAddress; var serializedMessage = string.Empty; using (var stream = new MemoryStream()) { TransportMessageSerializer.Serialize(toSend, stream); foreach (var destination in destinations) { var conversationHandle = ServiceBrokerWrapper.SendOne(transaction, ReturnAddress, destination, NServiceBusTransportMessageContract, NServiceBusTransportMessage, stream.ToArray()); toSend.Id = conversationHandle.ToString(); if (Logger.IsDebugEnabled) { Logger.Debug(string.Format("Sending message {0} with ID {1} to destination {2}.\n" + "ToString() of the message yields: {3}\n" + "Message headers:\n{4}", toSend.Body[0].GetType().AssemblyQualifiedName, toSend.Id, destination, toSend.Body[0], string.Join(", ", toSend.Headers.Select(h => h.Key + ":" + h.Value).ToArray()) )); } } } }); }
public async Task <QuestionInfo> RandomSelect(QuestionCategory questionCategory, int minDifficult) { if (minDifficult < QuestionConstants.QuestionMinDifficult || minDifficult > QuestionConstants.QuestionMaxDifficult) { throw new ArgumentOutOfRangeException(nameof(minDifficult)); } int questionCount = await questionInfoStatisticService.GetQuestionCount(questionCategory, minDifficult); if (questionCount <= 0) { throw new ApplicationException($"Can't find any question with {questionCategory} and {minDifficult}."); } int skipNum = random.Next(0, questionCount); int maxDifficult = minDifficult + QuestionConstants.QuestionSelectDifficultRange; using SessionWrapper sessionWrapper = questionInfoRepository.GetSessionWrapper(true); using TransactionWrapper transactionWrapper = sessionWrapper.BuildTransaction(true); IQueryable <QuestionInfo> questionInfoQuery = questionInfoRepository.GetQueryable(sessionWrapper); questionInfoQuery = questionInfoQuery.Where(m => m.QuestionCategory == questionCategory); questionInfoQuery = questionInfoQuery.Where(m => m.Difficult >= minDifficult && m.Difficult < maxDifficult); return(await questionInfoQuery.Skip(skipNum).Take(1).FirstOrDefaultAsync()); }
public void TestZone() { Point3d test_pt; ObjectId pickEnt; if (Selector.Entity("Selecciona una compuerta", out pickEnt, out test_pt)) { //Buscamos la compuerta por ObjectId Compuerta cmp = this.Compuertas.Values.FirstOrDefault(x => x.Block.Id == pickEnt); Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; if (cmp != null) { TransactionWrapper t = new TransactionWrapper(); //Se dibujan las zonas ObjectIdCollection ids = t.Run(DrawZonesTask, cmp) as ObjectIdCollection; ed.Regen(); //Se realizan las pruebas de contacto t.Run(TestZoneTask, cmp); //Se eliminan los rectangulos dibujados de la zona t.Run(EraseZonesTask, ids); } else { ed.WriteMessage("No es una compuerta"); } } }
private void button8_Click(object sender, EventArgs e) { TransactionWrapper wrapper = (TransactionWrapper)propertyGrid1.SelectedObject; ContractParametersContext context = new ContractParametersContext(Program.Service.NeoSystem.StoreView, wrapper.Unwrap(), Program.Service.NeoSystem.Settings.Network); InformationBox.Show(context.ToString(), "ParametersContext", "ParametersContext"); }
private void button5_Click(object sender, EventArgs e) { TransactionWrapper tx = (TransactionWrapper)propertyGrid1.SelectedObject; TransactionAttributeWrapper attribute = tx.Attributes.FirstOrDefault(p => p.Usage == TransactionAttributeUsage.Remark); bool found = attribute != null; if (!found) { attribute = new TransactionAttributeWrapper { Usage = TransactionAttributeUsage.Remark, Data = new byte[0] }; } string remark = Encoding.UTF8.GetString(attribute.Data); remark = InputBox.Show(Strings.EnterRemarkMessage, Strings.EnterRemarkTitle, remark); if (remark != null) { attribute.Data = Encoding.UTF8.GetBytes(remark); if (!found) { tx.Attributes.Add(attribute); } } }
public void DPulso() { Point3d insPt; Random r = new Random((int)DateTime.Now.Ticks); Boolean[] data = new Boolean[] { false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true }; int pulsoSize; if (Selector.Point("Selecciona el punto de inserción del pulso", out insPt) && Selector.Integer("El tamaño del pulso", out pulsoSize, 4)) { Boolean[] input = new Boolean[pulsoSize]; for (int i = 0; i < input.Length; i++) { input[i] = data[r.Next(data.Length - 1)]; } Pulso p = new Pulso(insPt, input); TransactionWrapper tr = new TransactionWrapper(); tr.Run(DPulsoTask, new Object[] { p }); } }
private void button8_Click(object sender, EventArgs e) { TransactionWrapper wrapper = (TransactionWrapper)propertyGrid1.SelectedObject; ContractParametersContext context = new ContractParametersContext(wrapper.Unwrap()); InformationBox.Show(context.ToString(), "ParametersContext", "ParametersContext"); }
public async Task <Result <GenericResponse> > TransactionSrvAsync(TransactionRequest request) { Result <GenericResponse> response = new Result <GenericResponse>(); Card card = new Card(); Limit limit = new Limit(); try { ValidateTransactionRequest(request); card = await RetrieveCardFromDb(request); await CheckIfTransactionIsAcceptable(card); TransactionWrapper wrapper = CreatetransactionWrapper(card, request); await InsertTransactionInDb(wrapper, limit); await dbContext.SaveChangesAsync(); response.Payload = CreateResponse(); } catch (Exception ex) { logger.LogError(ex.Message); HandleExeptionResult(response, ex.Message); } return(response); }
private void InitServiceBroker() { TransactionWrapper.RunInTransaction(transaction => { // Ensure the service and queue exist ServiceBrokerWrapper.CreateServiceAndQueue(transaction, ReturnAddress, ListenerQueue); }); }
private void Process() { releasedWaitLock = false; needToAbort = false; messageId = string.Empty; try { transactionWaitPool.WaitOne(); TransactionWrapper.RunInTransaction(transaction => { ReceiveMessage(transaction); }); ClearFailuresForMessage(messageId); } catch (AbortHandlingCurrentMessageException) { //in case AbortHandlingCurrentMessage was called //don't increment failures, we want this message kept around. return; } catch (Exception e) { var originalException = e; if (e is TransportMessageHandlingFailedException) { originalException = ((TransportMessageHandlingFailedException)e).OriginalException; } IncrementFailuresForMessage(messageId, originalException); Logger.Error("Error Procesing Message", originalException); OnFailedMessageProcessing(originalException); } finally { if (!releasedWaitLock) { transactionWaitPool.Release(1); } } }
public void BeginTransaction() { if (transaction == null || transaction.IsCommited || transaction.IsRolledBack) { (transaction = transactionWrapperFactory.Create()).Begin(); } }
/// <summary> /// This is a special helper method which will cause the transport to receive messages as if they came off the bus /// </summary> public void ReceiveMessages(object[] messages, IEnumerable <HeaderInfo> headers) { needToAbort = false; messageId = string.Empty; try { TransactionWrapper.RunInTransaction(transaction => { var transportMessage = new TransportMessage() { Id = Guid.NewGuid().ToString(), IdForCorrelation = Guid.NewGuid().ToString(), Body = messages, TimeSent = DateTime.UtcNow, MessageIntent = MessageIntentEnum.Send, Headers = headers.ToList(), }; //care about failures here var exceptionFromMessageHandling = OnTransportMessageReceived(transportMessage); //and here var exceptionFromMessageModules = OnFinishedMessageProcessing(); //but need to abort takes precedence - failures aren't counted here, //so messages aren't moved to the error queue. if (needToAbort) { throw new AbortHandlingCurrentMessageException(); } if (exceptionFromMessageHandling != null) //cause rollback { throw exceptionFromMessageHandling; } if (exceptionFromMessageModules != null) //cause rollback { throw exceptionFromMessageModules; } }); } catch (AbortHandlingCurrentMessageException) { //in case AbortHandlingCurrentMessage was called //don't increment failures, we want this message kept around. return; } catch (Exception e) { var originalException = e; if (originalException is TransportMessageHandlingFailedException) { originalException = ((TransportMessageHandlingFailedException)e).OriginalException; } OnFailedMessageProcessing(originalException); throw; } }
public IDisposable BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted) { if (_transaction == null) { _transaction = new TransactionWrapper(isolationLevel); } return(_transaction); }
private TransactionWrapper CreatetransactionWrapper(Card card, TransactionRequest request) { TransactionWrapper wrapper = new TransactionWrapper(); wrapper.card = card; wrapper.request = request; return(wrapper); }
private void Process() { messageContext = new MessageReceiveProperties(); var wrapper = new TransactionWrapper(); wrapper.RunInTransaction(() => Receive(messageContext), isolationLevel, transactionTimeout); ClearFailuresForMessage(messageContext.MessageId); messageContext = null; }
private Limit CreateTransaction(TransactionWrapper wrapper, Limit limit) { limit.CardNumber = wrapper.card.CardNumber; limit.TransactionCategory = wrapper.request.TransactionType; limit.LimitId = Guid.NewGuid(); limit.TransactionDate = DateTimeOffset.Now.Date; limit.Amount = wrapper.request.Amount; return(limit); }
private void OnTransactionDisposing(TransactionWrapper sender) { Debug.Assert(_transaction == sender); sender.Disposing -= OnTransactionDisposing; sender = null; _transaction = null; }
public void Dictionary() { ObjectId obj; if (Selector.Entity("Selecciona una entidad", out obj)) { TransactionWrapper tr = new TransactionWrapper(); tr.Run(DictionaryTask, obj); } }
public IDatabaseSession CreateSession(string connectionString) { var sqlConnectionProvider = _connectionProvider ?? new SqlConnectionProvider(connectionString); var transactionWrapper = new TransactionWrapper(sqlConnectionProvider); var databaseConnectionManager = new DatabaseCommandProvider(sqlConnectionProvider, transactionWrapper); var databaseCommandCreator = new DatabaseCommandFactory(databaseConnectionManager); var databaseReaderFactory = new SqlDatabaseReaderFactory(); var connectionHandler = new ConnectionHandler(); return new DatabaseSession(databaseCommandCreator, transactionWrapper, databaseReaderFactory, connectionHandler); }
private void InitSqlServerQueue() { TransactionWrapper.RunInTransaction(transaction => { using (var cmd = transaction.Connection.CreateCommand()) { cmd.Transaction = transaction; cmd.CommandText = string.Format(SqlCommands.CreateQueueTable, ListenerQueue.Trim()); cmd.ExecuteNonQuery(); } }); }
public IDbTransaction BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.Serializable) { if (_transaction == null) { _transaction = new TransactionWrapper(Session.BeginTransaction(isolationLevel)); _transaction.Disposing += OnTransactionDisposing; return(_transaction); } return(new TransactionStub(Session, isolationLevel)); }
public virtual async Task Delete(long id) { using (SessionWrapper sessionWrapper = entityRepository.GetSessionWrapper()) { using (TransactionWrapper transactionWrapper = sessionWrapper.BuildTransaction()) { await entityRepository.Delete(id); await transactionWrapper.Commit(); } } }
public void DrawCasita() { Point3d insPt; Point3d endPt; if (Lab2.Selector.Point("Punto de inserción", out insPt) && Lab2.Selector.Point("El tamaño de la casita", out endPt, insPt)) { Casita c = new Casita(insPt.DistanceTo(endPt), insPt); TransactionWrapper tr = new TransactionWrapper(); tr.Run(DrawGeometry, c.Faces.ToArray()); } }
public async Task <IdentityResult> CreateUser(ApplicationUserCreateOptions options) { using (TransactionWrapper.Create(_dbContextIndex["membership"])) { // user var applicationUser = new ApplicationUser { ApplicationId = _applicationUserManager.GetApplicationId(), Email = options.Email, UserName = options.Email, IsApproved = true, EmailConfirmed = true, }; var result = await _applicationUserManager.CreateAsync(applicationUser, options.Password); if (!result.Succeeded) { return(result); } // reload user var user = await _applicationUserManager.FindByEmailAsync(options.Email); // roles if (options.Roles != null && options.Roles.Count > 0) { result = await _applicationUserManager.AddToRolesAsync(user.Id, options.Roles.ToArray()); if (!result.Succeeded) { return(result); } } // claims if (options.Claims != null && options.Claims.Count > 0) { foreach (var claim in options.Claims) { result = await _applicationUserManager.AddClaimAsync(user.Id, claim); if (!result.Succeeded) { return(result); } } } return(result); } }
public override Task <AckMessage> ReceiveTransaction(TransactionMessage request, ServerCallContext context) { RegisterNode(request.SenderAddress, context); XmlSerializer serializer = new XmlSerializer(typeof(TransactionWrapper)); TransactionWrapper wrappedTransaction = (TransactionWrapper)serializer.Deserialize(new StringReader(request.Xml)); var success = chainManipulator.OnReceiveTransaction(wrappedTransaction.Transaction); return(Task.FromResult( new AckMessage() { Status = success ? AckMessage.Types.Status.Ok : AckMessage.Types.Status.Nok } )); }
public virtual async Task <TEntity> Get(long id, bool updateLater = false) { using (SessionWrapper sessionWrapper = entityRepository.GetSessionWrapper(true)) { using (TransactionWrapper transactionWrapper = sessionWrapper.BuildTransaction(true)) { TEntity entity = await entityRepository.Get(id, updateLater); await transactionWrapper.Commit(); return(entity); } } }
public virtual async Task <TEntity> Update(TEntity entity) { using (SessionWrapper sessionWrapper = entityRepository.GetSessionWrapper()) { using (TransactionWrapper transactionWrapper = sessionWrapper.BuildTransaction()) { TEntity updatedEntity = await entityRepository.Update(entity); await transactionWrapper.Commit(); return(updatedEntity); } } }
public void ChecarCables() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; ObjectId compId; if (Selector.Entity("Selecciona una compuerta", out compId)) { Compuerta cmp = this.Compuertas.FirstOrDefault(x => x.Value.Block.ObjectId == compId).Value; cmp.InitBox(); ObjectId cableAId = cmp.Search("INPUTA").OfType <ObjectId>().FirstOrDefault(), cableBId = cmp.Search("INPUTB").OfType <ObjectId>().FirstOrDefault(); TransactionWrapper tr = new TransactionWrapper(); tr.Run(TestConnectionTask, cmp, cableAId, cableBId); } }
public void InsertOR() { if (Compuertas == null) { Compuertas = new Dictionary <Handle, Compuerta>(); } Point3d pt; if (Selector.Point("Selecciona el punto de inserción de la compuerta", out pt)) { TransactionWrapper tr = new TransactionWrapper(); var cmp = tr.Run(InsertCompuertaTask, new OR(2), pt) as Compuerta; Compuertas.Add(cmp.Id, cmp); } }
public void InsertSalida() { if (Compuertas == null) { Compuertas = new Dictionary <Handle, Compuerta>(); } Point3d insPt; if (Selector.Point("Selecciona el punto de inserción de la salida", out insPt)) { TransactionWrapper tr = new TransactionWrapper(); var cmp = tr.Run(InsertCompuertaTask, new Output(), insPt) as Compuerta; Compuertas.Add(cmp.Id, cmp); } }
public void Initialize() { mock = new Mock<ITransaction>(); wrapper = new TransactionWrapper(mock.Object, Encoding.UTF8.GetBytes("prefix:")); }