本文整理汇总了C#中Castle.ActiveRecord.TransactionScope.VoteCommit方法的典型用法代码示例。如果您正苦于以下问题:C# TransactionScope.VoteCommit方法的具体用法?C# TransactionScope.VoteCommit怎么用?C# TransactionScope.VoteCommit使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Castle.ActiveRecord.TransactionScope
的用法示例。
在下文中一共展示了TransactionScope.VoteCommit方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: UpdateConnections
public static void UpdateConnections(DataTable dt)
{
using (var transaction = new TransactionScope(TransactionMode.New))
{
foreach (DataRow row in dt.Rows)
{
int id;
if (Int32.TryParse(row[0].ToString(), out id))
{
var bw = Baseword.Find(id);
var flexions = new string[row.ItemArray.Count() - 1];
for (int i = 1; i < row.ItemArray.Count(); i++)
{
flexions[i - 1] = row.ItemArray[i].ToString();
}
bw.UpdateFlexions(flexions);
Console.Out.WriteLine(string.Format("{3}: Updated Baseword {0}/{1} with id:{2}",
dt.Rows.IndexOf(row), dt.Rows.Count, bw.Id,
DateTime.Now.ToString(CultureInfo.InvariantCulture)));
}
}
transaction.Flush();
transaction.VoteCommit();
}
}
示例2: Registro
public static void Registro()
{
foreach (var archivo in ActiveRecordBase<ConsumoDto>.FindAllByProperty("Procesado", false))
{
var documento = HelperPersona.GetPersona(
archivo.Cuit, archivo.TipoCliente,
archivo.RazonSocial, archivo.NombrePersona,
archivo.NroDocumento, archivo.Empresa);
var cliente = HelperCuenta.GetCuenta(
archivo.Cuit, archivo.NroDocumento, archivo.Empresa);
using (var transac = new TransactionScope())
try
{
var puntos = HelperPuntos.GetPuntos(archivo.Empresa, archivo.FechaHoraComprobante,
archivo.ImportePesosNetoImpuestos);
double acelerador = Double.Parse(archivo.Coeficiente) / 100;
puntos = acelerador > 0 ? acelerador * puntos : puntos;
var cuenta = new CuentaCorrienteDto
{
FechaCompra = archivo.FechaHoraComprobante.Date,
HoraCompra = DateTime.Now,
Key = new KeyCuenta
{
CodEmpresa = archivo.Empresa,
NumeroComprobante = archivo.NroComprobante
},
MontoCompra = archivo.ImportePesosNetoImpuestos,
Movimiento = puntos >= 0 ? HelperMovimiento.FindMovimiento("Suma De Puntos") : HelperMovimiento.FindMovimiento("Anulación Carga"),
NumeroDocumento = documento,
NumeroCuenta = cliente,
Puntos = puntos,
Sucursal = HelperSucursal.GetSucursal(),
Usuario = "web",
Programa = archivo.Programa,
Secretaria = archivo.Secretaria,
Coeficiente = archivo.Coeficiente
};
cuenta.Save();
transac.VoteCommit();
}
catch (Exception ex)
{
archivo.Error = ex.Message;
Log.Fatal(ex);
transac.VoteRollBack();
}
archivo.Procesado = true;
archivo.Save();
}
}
示例3: btnSalvar_Click1
/// <summary>
/// evento disparado pelo botão salvar
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnSalvar_Click1(object sender, EventArgs e)
{
//bisca a lista de moradores selecionados
List<int> lista = (List<int>)ViewState["moradores"];
if (lista.Count > 0)
{
//abre a transação
using (TransactionScope trans = new TransactionScope())
{
try
{
//cria o template da mensagem
Domain.Model.Mensagem mensagem = new Domain.Model.Mensagem();
mensagem.Usuario = txtUsuario.Text;
mensagem.Detalhe = txtMensagem.Text;
mensagem.CreateAndFlush();
Usuario user = new Usuario();
MensagensDosUsuarios mensagemRelacionada;
//envia a mensagem para casa usuário selecionado
foreach (var item in lista)
{
user.Id = item;
mensagemRelacionada = new MensagensDosUsuarios();
mensagemRelacionada.Mensagem = mensagem;
mensagemRelacionada.Usuario = user;
mensagemRelacionada.CreateAndFlush();
}
//commit da transação
trans.VoteCommit();
}
catch (Exception ex)
{
//rollback da transação
trans.VoteRollBack();
//grava o erro em um log
Logger.Error(ex.Message);
base.ExibirMensagemErro();
}
}
base.ExibirMensagemSucesso(Funcionalidade.Mensagem, Operacao.Inclusao);
}
else
{
pnlMensagem.ExibirMensagem("Selecione os usuários para quem você vai enviar a mensagem");
}
}
示例4: GetPaymentUrl
public static string GetPaymentUrl(Transaction idealPayer, string mollieClientNumber, bool testMode, string paymentName, string reportUrl, string landUrl)
{
if(idealPayer.Payed)
throw new Exception("Er is al betaald");
IdealFetch idealFetch = new IdealFetch(mollieClientNumber, testMode, paymentName, reportUrl, landUrl, idealPayer.BankId, idealPayer.Amount);
if (idealFetch.Error)
{
throw new Exception(idealFetch.ErrorMessage);
}
idealPayer.TransactionId = idealFetch.TransactionId;
using( TransactionScope transactionScope = new TransactionScope(TransactionMode.Inherits, OnDispose.Rollback))
{
idealPayer.Save();
transactionScope.VoteCommit();
}
return idealFetch.Url;
}
示例5: EditarFuncionario
/// <summary>
/// funcionalidade de edição de um registro de funcionario
/// </summary>
/// <param name="id"></param>
private void EditarFuncionario(int id)
{
//abre a transação
using (TransactionScope trans = new TransactionScope())
{
try
{
//consulta o funcionário pelo ID
Funcionario funcionario = Funcionario.FindByPrimaryKey(id);
//atribui os dados que estão na página
funcionario.Nome = Request.Form["ctl00$ContentPlaceHolder1$txtNome"]; //txtNome.Text.Trim();
funcionario.Endereco = Request.Form["ctl00$ContentPlaceHolder1$txtEndereco"]; //txtEndereco.Text.Trim();
funcionario.CPF = Request.Form["ctl00$ContentPlaceHolder1$txtCpf"]; //txtCpf.Text.Trim();
funcionario.RG = Request.Form["ctl00$ContentPlaceHolder1$txtRG"]; //txtRG.Text.Trim();
funcionario.Telefone = Request.Form["ctl00$ContentPlaceHolder1$txtTelefone"]; //txtTelefone.Text.Trim();
funcionario.DataNascimento = DateTime.Parse(Request.Form["ctl00$ContentPlaceHolder1$txtDataNascimento"]);
funcionario.DataAdmissao = DateTime.Parse(Request.Form["ctl00$ContentPlaceHolder1$txtDataContratacao"]);
funcionario.NumeroCarteiraTrabalho = Request.Form["ctl00$ContentPlaceHolder1$txtCarteiratrabalho"];// txtCarteiratrabalho.Text.Trim();
funcionario.Cargo = Request.Form["ctl00$ContentPlaceHolder1$txtCargo"];// txtCargo.Text.Trim();
//atualiza o funcionário
funcionario.UpdateAndFlush();
if (Request.Form["ctl00$ContentPlaceHolder1$txtSalario"].Trim() != string.Empty)
{
//verifica se tem salário e se houve alteração do valor
decimal valor = decimal.Parse(Request.Form["ctl00$ContentPlaceHolder1$txtSalario"]);
if (funcionario.SalarioVigente != null)
{
if (funcionario.SalarioVigente.Valor != valor)
{
//atribui o valor da salário
funcionario.SalarioVigente.FinalVigencia = DateTime.Today;
funcionario.SalarioVigente.Vigente = false;
//atualiza o registro
funcionario.SalarioVigente.UpdateAndFlush();
if (valor != 0)
{
Salario salario = new Salario();
salario.InicioVigencia = DateTime.Today;
salario.Vigente = true;
salario.Valor = valor;
salario.FuncionarioDoSalario = funcionario;
salario.CreateAndFlush();
}
}
}
}
else
{
if (funcionario.SalarioVigente != null)
{
funcionario.SalarioVigente.FinalVigencia = DateTime.Today;
funcionario.SalarioVigente.Vigente = false;
funcionario.SalarioVigente.UpdateAndFlush();
}
}
//commit da transação
trans.VoteCommit();
}
catch (Exception ex)
{
//rollback da transação
trans.VoteRollBack();
throw ex;
}
finally
{
trans.Flush();
}
}
}
示例6: CadastrarNovoFuncionario
/// <summary>
/// grava um novo registro de funcionário
/// </summary>
private void CadastrarNovoFuncionario()
{
//abre a transação
using (TransactionScope trans = new TransactionScope())
{
try
{
//atribui os dados da página para o registro de funcionário e salva no banco
Funcionario funcionario = new Funcionario();
funcionario.Nome = txtNome.Text.Trim();
funcionario.Endereco = txtEndereco.Text.Trim();
funcionario.CPF = txtCpf.Text.Trim();
funcionario.RG = txtRG.Text.Trim();
funcionario.Telefone = txtTelefone.Text.Trim();
funcionario.DataNascimento = DateTime.Parse(txtDataNascimento.Text.Trim());
funcionario.DataAdmissao = DateTime.Parse(txtDataContratacao.Text.Trim());
funcionario.NumeroCarteiraTrabalho = txtCarteiratrabalho.Text.Trim();
funcionario.Cargo = txtCargo.Text.Trim();
funcionario.CreateAndFlush();
if (txtSalario.Text.Trim() != string.Empty)
{
decimal valor = decimal.Parse(txtSalario.Text.Trim());
if (valor != 0)
{
//cria o registro do salário
Salario salario = new Salario();
salario.InicioVigencia = DateTime.Parse(txtDataContratacao.Text.Trim());
salario.Vigente = true;
salario.Valor = valor;
salario.FuncionarioDoSalario = funcionario;
salario.CreateAndFlush();
}
}
//commit da transação
trans.VoteCommit();
}
catch (Exception ex)
{
//rollback da transação
trans.VoteRollBack();
//sobe o erro para o método que o chamou, onde será gravado em um arquivo de texto
throw ex;
}
finally
{
//fecha a transasção
trans.Flush();
}
}
}
示例7: ActiveRecordUsingTransactionScopeWithCommitAndInnerSessionScope
public void ActiveRecordUsingTransactionScopeWithCommitAndInnerSessionScope()
{
InitModel();
using (TransactionScope scope = new TransactionScope())
{
using (new SessionScope())
{
new SSAFEntity("example").Save();
Assert.AreEqual(1, SSAFEntity.FindAll().Length);
}
//Assert.AreEqual(1, SSAFEntity.FindAll().Length);
scope.VoteCommit();
}
Assert.AreEqual(1, SSAFEntity.FindAll().Length);
}
示例8: MollieCallback
public void MollieCallback(int id, string transaction_id)
{
Transaction transaction = MollieIdealHelper.GetTransactionByTransactionId(transaction_id);
var enrolment = GetEnrolmentByTransaction(transaction);
if (!enrolment.Active)
{
if (enrolment.CanBeMadeActive())
{
enrolment.Active = true;
ActiveRecordMediator.SaveAndFlush(enrolment);
}
else
{
SendMailForInactiveEnrolment(enrolment);
return;
}
}
transaction.Payed = MollieIdealHelper.IsTransactionPayed(transaction_id, mollieClientNumber, mollieTestMode);
using (TransactionScope transactionScope = new TransactionScope(TransactionMode.Inherits, OnDispose.Rollback))
{
transaction.Save();
transactionScope.VoteCommit();
}
if (transaction.Payed)
{
SendMail(transaction);
}
CancelView();
}
示例9: Pay
public void Pay([ARDataBind("transaction", AutoLoadBehavior.NullIfInvalidKey)] Transaction transaction)
{
Uri uri = Request.Uri;
string siteUrl = uri.AbsoluteUri.Substring(0, uri.AbsoluteUri.IndexOf(uri.AbsolutePath));
string reportUrl = string.Format("{0}/Ideal/MollieCallback", siteUrl);
string landingUrl = string.Format("{0}/Ideal/Landing", siteUrl);
if (mollieUseTestUrls)
{
reportUrl = ConfigurationManager.AppSettings["MollieTestCallback"];
landingUrl = ConfigurationManager.AppSettings["MollieTestLanding"];
}
using (TransactionScope transactionScope = new TransactionScope(TransactionMode.Inherits, OnDispose.Rollback))
{
transaction.Save();
transactionScope.VoteCommit();
}
var enrolment = GetEnrolmentByTransaction(transaction);
string molliePaymentDiscription = GetMollieDescription(enrolment);
RedirectToUrl(MollieIdealHelper.GetPaymentUrl(transaction, mollieClientNumber, mollieTestMode, molliePaymentDiscription,
reportUrl, landingUrl));
}
示例10: ToRender
public void ToRender([ARDataBind("purchase",AutoLoadBehavior.Always)] Purchase purchase, string comment)
{
PurchaseStatusChange psc = new PurchaseStatusChange();
psc.Created = DateTime.Now;
psc.Purchase = purchase;
psc.StatusOld = purchase.Status;
psc.StatusNew =Purchase.StatusPurchase.Entregado;
psc.author = Context.CurrentUser.Identity.Name.ToLower ();
purchase.DateDelivery = System.DateTime.Now;
purchase.Status = Purchase.StatusPurchase.Entregado;
using (TransactionScope t1 = new TransactionScope())
{
try {
purchase.Save ();
psc.Save ();
if (!string.IsNullOrEmpty(comment)) {
PurchaseComment pc = new PurchaseComment();
pc.Comment = comment;
pc.Created = DateTime.Now;
pc.Purchase = purchase;
pc.UserComment = Context.CurrentUser.Identity.Name.ToLower ();
pc.Save ();
}
t1.VoteCommit();
Flash["TypeMsg"] = "alert alert-success";
Flash["Msg"] = "<b>Ok, Solicitud " + purchase.Status +" entregada conforme...</b> ";
} catch (Exception ex) {
t1.VoteRollBack();
if (!purchase.IsValid()) {
Flash["Msg"] = Utilities.GetValidationErrorText(purchase.ValidationErrorMessages);
} else {
Flash["Msg"] = "Error :" + ex.Message + " " + comment.Length.ToString();
}
RedirectToReferrer ();
return;
}
}
PropertyBag["to"] = ConfigurationManager.AppSettings["mailadmin"];
PropertyBag["cc"] = purchase.UserRequest + "@" + ConfigurationManager.AppSettings["defaultdomain"];
PropertyBag["from"] = ConfigurationManager.AppSettings["mailadmin"];
PropertyBag["subject"] = "[compras] Compra recepcionada "+ purchase.Status +" ID:" + purchase.Id.ToString ();
PropertyBag["purchase"] = purchase;
PropertyBag["purchaseproducts"] = purchase.PurchaseProducts;
DeliverEmail(RenderMailMessage ("close",null,PropertyBag));
RenderView ("approval");
}
示例11: ToApprove
public void ToApprove([ARDataBind("purchase",AutoLoadBehavior.Always)] Purchase purchase, string response, string comment)
{
PurchaseStatusChange psc = new PurchaseStatusChange();
psc.Created = DateTime.Now;
psc.Purchase = purchase;
psc.StatusOld = purchase.Status;
switch (response) {
case "approval" : {
purchase.Status = Purchase.StatusPurchase.Aprobada;
break;
}
case "reject" : {
purchase.Status = Purchase.StatusPurchase.Rechazada;
break;
}
default : {
Flash["TypeMsg"] = "alert alert-error";
Flash["Msg"] = "Error :" + response;
RedirectToReferrer ();
return;
}
}
psc.StatusNew = purchase.Status;
psc.author = Context.CurrentUser.Identity.Name.ToLower ();
purchase.DateApproval = System.DateTime.Now;
using (TransactionScope t1 = new TransactionScope())
{
try {
purchase.Save ();
psc.Save ();
if (!string.IsNullOrEmpty(comment)) {
PurchaseComment pc = new PurchaseComment();
pc.Comment = comment;
pc.Created = DateTime.Now;
pc.Purchase = purchase;
pc.UserComment = Context.CurrentUser.Identity.Name.ToLower ();
pc.Save ();
}
t1.VoteCommit();
Flash["TypeMsg"] = "alert alert-success";
Flash["Msg"] = "<b>Ok, Solicitud " + purchase.Status +" enviada a Compras</b> ";
} catch (Exception ex) {
t1.VoteRollBack();
Flash["TypeMsg"] = "alert alert-error";
Flash["Msg"] = "Error :" + ex.Message;
RedirectToReferrer ();
return;
}
}
PropertyBag["to"] = ConfigurationManager.AppSettings["mailadmin"];
PropertyBag["cc"] = purchase.UserRequest + "@" + ConfigurationManager.AppSettings["defaultdomain"];
PropertyBag["from"] = ConfigurationManager.AppSettings["mailadmin"];
PropertyBag["subject"] = "[compras] Compra "+ purchase.Status +" ID:" + purchase.Id.ToString ();
PropertyBag["purchase"] = purchase;
PropertyBag["purchaseproducts"] = purchase.PurchaseProducts;
DeliverEmail(RenderMailMessage ("toapprove",null,PropertyBag));
if (purchase.Status == Purchase.StatusPurchase.Aprobada)
RenderView ("approval");
else
RenderView ("reject");
}
示例12: submit
public void submit([ARDataBind("purchaseproducts")] PurchaseProduct[] purchaseproducts, int companyid, int userapproval, int familyproductid, string comment, HttpPostedFile uploadedFile)
{
Purchase purchase = new Purchase();
purchase.UserRequest = Context.CurrentUser.Identity.Name.ToLower ();
purchase.DateRequest = System.DateTime.Now;
User user = (User) Context.Session["user"];
purchase.MailRequest = user.Mail;
purchase.NameUserRequest = user.Cn;
if (companyid > 0)
purchase.Company = Company.FindById(companyid);
else {
Flash["TypeMsg"] = "alert alert-error";
Flash["Msg"] = "Seleccionar Compañia";
RedirectToAction("new");
return;
}
CompanyApprover ca = new CompanyApprover();
if (userapproval > 0) {
ca = CompanyApprover.FindById(userapproval);
purchase.UserApproval = ca;
} else {
Flash["TypeMsg"] = "alert alert-error";
Flash["Msg"] = "Seleccionar Aprobador";
RedirectToAction("new");
return;
}
if (familyproductid < 1) {
Flash["TypeMsg"] = "alert alert-error";
Flash["Msg"] = "Seleccionar Familia de Productos";
RedirectToAction("new");
return;
}
purchase.Status = Purchase.StatusPurchase.En_Aprobacion;
using (TransactionScope t1 = new TransactionScope())
{
try {
//purchase.BudgetValue = Budget.FindByCompanyFamilyProduct(Company.FindById(companyid), FamilyProduct.FindById(familyproductid)).Value;
purchase.familyproduct = FamilyProduct.FindById(familyproductid);
purchase.Save ();
int cont = 0;
foreach(PurchaseProduct pp in purchaseproducts)
{
if (pp.Checked) {
pp.Purchase = purchase;
//pp.Product = Product.FindById(1);
if (!pp.IsValid()) {
Flash["TypeMsg"] = "alert alert-error";
Flash["Msg"] = Utilities.GetValidationErrorText(pp.ValidationErrorMessages);
t1.VoteRollBack ();
RedirectToAction("new");
return;
}
pp.Save();
cont++;
}
}
if (cont == 0) {
t1.VoteRollBack ();
Flash["TypeMsg"] = "alert alert-error";
Flash["Msg"] = "Seleccionar Productos";
RedirectToAction("new");
return;
}
if (!string.IsNullOrEmpty(comment)) {
PurchaseComment pc = new PurchaseComment();
pc.Comment = comment;
pc.Created = DateTime.Now;
pc.Purchase = purchase;
pc.UserComment = Context.CurrentUser.Identity.Name.ToLower ();
pc.Save ();
}
if (uploadedFile != null) {
PurchaseAttachment pa = new PurchaseAttachment();
pa.Purchase = purchase;
pa.Name = uploadedFile.FileName;
pa.Created = DateTime.Now;
pa.Path = Guid.NewGuid().ToString("N") + uploadedFile.FileName;
pa.Save ();
uploadedFile.SaveAs("../upload_compras/"+pa.Path);
}
t1.VoteCommit ();
Flash["TypeMsg"] = "alert alert-success";
Flash["Msg"] = "Solicitud generada con ID :<b>" + purchase.Id.ToString() + "</b>";
}
catch (Exception ex) {
t1.VoteRollBack ();
Flash["TypeMsg"] = "alert alert-error";
if (!purchase.IsValid()) {
Flash["Msg"] = Utilities.GetValidationErrorText(purchase.ValidationErrorMessages);
//.........这里部分代码省略.........
示例13: OnInit
protected override void OnInit(System.EventArgs e)
{
base.OnInit(e);
ActiveRecordStarter.ResetInitializationFlag();
ActiveRecordStarter.Initialize(typeof(Person).Assembly, ActiveRecordSectionHandler.Instance);
NHibernate.Cfg.Environment.UseReflectionOptimizer = false;
try
{
_log.Debug("Creating database...");
RecreateDatabase();
_log.Debug("...database created");
}
catch (ActiveRecordException exc)
{
_log.Fatal("Did you forget to modify 'connection.connection_string' in web.config to point to a valid database?", exc);
return;
}
Person person;
PhoneNumber homePhoneNumber;
_log.Debug("Writing data to database...");
using (TransactionScope trans = new TransactionScope())
{
person = new Person();
person.Name = "Lazy";
person.Save();
homePhoneNumber = new PhoneNumber();
homePhoneNumber.Number = "867-5309";
homePhoneNumber.PhoneType = "Cell";
homePhoneNumber.Person = person;
homePhoneNumber.Save();
trans.VoteCommit();
}
_log.Debug("...data written");
int personId = person.Id;
person = null;
int homePhoneNumberId = homePhoneNumber.Id;
homePhoneNumber = null;
try
{
using (new SessionScope())
{
Person lazyPerson = Person.TryFind(personId);
_log.Debug("Lazy loading an entity...");
string lazyName = lazyPerson.Name;
_log.Debug("...entity loaded");
}
using (new SessionScope())
{
PhoneNumber home = PhoneNumber.Find(homePhoneNumberId);
_log.Debug("Lazy loading a related entity...");
Person lazyPerson = home.Person;
_log.Debug("...related entity loaded");
}
_log.Debug("Comment out 'proxyfactory.factory_class' in web.config and try again.");
}
catch (ActiveRecordException exc)
{
_log.Error("Cannot generate lazy loading proxies in a Medium Trust environment. Try using NHibernate.ProxyGenerators :)", exc);
}
}