コード例 #1
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var response = new TransactionsStreamResponse();

            var jsonToken = JToken.Load(reader);

            if (jsonToken.Type == JTokenType.Object)
            {
                bool isHeartbeat = jsonToken["type"].Value <string>() == "HEARTBEAT";

                if (isHeartbeat)
                {
                    var heartbeat = new TransactionsHeartbeat();
                    serializer.Populate(jsonToken.CreateReader(), heartbeat);
                    response.heartbeat = heartbeat;
                }
                else
                {
                    ITransaction transaction = TransactionFactory.Create(jsonToken["type"].Value <string>());
                    serializer.Populate(jsonToken.CreateReader(), transaction);
                    response.transaction = transaction;
                }

                return(response);
            }
            else
            {
                throw new ArgumentException(string.Format("Unexpected JTokenType ({0}) in reader.", jsonToken.Type.ToString()));
            }
        }
コード例 #2
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jsonToken = JToken.Load(reader);

            if (jsonToken.Type == JTokenType.Array)
            {
                var transactions = new List <ITransaction>();

                var jsonArray = (JArray)jsonToken;

                foreach (var item in jsonArray)
                {
                    var transaction = TransactionFactory.Create(item["type"].Value <string>());
                    serializer.Populate(item.CreateReader(), transaction);
                    transactions.Add(transaction);
                }

                return(transactions);
            }
            else if (jsonToken.Type == JTokenType.Object)
            {
                ITransaction transaction = TransactionFactory.Create(jsonToken["type"].Value <string>());
                serializer.Populate(jsonToken.CreateReader(), transaction);
                return(transaction);
            }
            else
            {
                throw new ArgumentException(string.Format("Unexpected JTokenType ({0}) in reader.", jsonToken.Type.ToString()));
            }
        }
コード例 #3
0
        public static void FillDictionary()
        {
            ClearData();
            TransactionWork transactionWork = null;

            try
            {
                using (transactionWork = (TransactionWork)TransactionFactory.Create())
                {
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["ApppTpr"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["Gender"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["AdminDivision"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["TypeStreet"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["ChiperRecept"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["BenefitsCategory"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["DisabilityGroup"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["Land"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["RegisterType"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["WhyDeRegister"]);
                    transactionWork.Commit();
                }
            }
            catch (Exception)
            {
                transactionWork?.Rollback();
                throw;
            }
        }
コード例 #4
0
        public static void SaveEntity(string entityName)
        {
            TransactionWork transactionWork = null;

            try
            {
                using (transactionWork = (TransactionWork)TransactionFactory.Create())
                {
                    for (int i = 0; i < _tables.DispancerDataSet.Tables.Count; i++)
                    {
                        if (_tables.DispancerDataSet.Tables[i].TableName == entityName)
                        {
                            transactionWork.UpdateData(_tables.DispancerDataSet.Tables[i]);
                            break;
                        }
                    }

                    transactionWork.Commit();
                }
            }
            catch (Exception)
            {
                transactionWork?.Rollback();
                throw;
            }
        }
コード例 #5
0
        public static void Update()
        {
            TransactionWork transactionWork = null;

            try
            {
                using (transactionWork = (TransactionWork)TransactionFactory.Create())
                {
                    for (int i = 0; i < _tables.DispancerDataSet.Tables.Count; i++)
                    {
                        if (_tables.DispancerDataSet.Tables[i].TableName != _tables.ErrorDataTable.TableName)
                        {
                            transactionWork.UpdateData(_tables.DispancerDataSet.Tables[i]);
                        }
                    }
                    _tables.ErrorDataTable.Clear();
                    transactionWork.Commit();
                }
            }
            catch (Exception)
            {
                transactionWork?.Rollback();
                throw;
            }
        }
コード例 #6
0
        public static void FillCustomerData()
        {
            ClearData();
            TransactionWork transactionWork = null;

            try
            {
                using (transactionWork = (TransactionWork)TransactionFactory.Create())
                {
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["Customer"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["Address"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["Invalid"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["InvalidBenefitsCategory"]);
                    transactionWork.ReadData(_tables.DispancerDataSet.Tables["Register"]);
                    transactionWork.Commit();
                }
                whereClasure = String.Empty;
                value        = null;
                dbType       = string.Empty;
            }
            catch (Exception)
            {
                transactionWork?.Rollback();
                throw;
            }
        }
コード例 #7
0
        private static void GetDataByCriteriaTest(string criteria, object[] parameters, string predicate = "=")
        {
            TransactionWork transactionWork = null;

            SqlParameter[] parameterCustomer    = CreateUSP(criteria, parameters);
            SqlParameter[] parameterReg         = CreateUSP(criteria, parameters);
            SqlParameter[] parameterInv         = CreateUSP(criteria, parameters);
            SqlParameter[] parameterInvBenefits = CreateUSP(criteria, parameters);
            SqlParameter[] parameterAddr        = CreateUSP(criteria, parameters);

            try
            {
                using (transactionWork = (TransactionWork)TransactionFactory.Create())
                {
                    transactionWork.Execute(_tables.CustomerDataTable, $"uspGetCustomerBy{criteria}",
                                            parameterCustomer);
                    transactionWork.Execute(_tables.RegisterDataTable, $"uspGetRegisterBy{criteria}", parameterReg);
                    transactionWork.Execute(_tables.InvalidDataTable, $"uspGetInvalidBy{criteria}", parameterInv);
                    transactionWork.Execute(_tables.InvalidBenefitsDataTable, $"uspGetInvalidBenefitsBy{criteria}",
                                            parameterInvBenefits);
                    transactionWork.Execute(_tables.AddressDataTable, $"uspGetAddressBy{criteria}", parameterAddr);
                    transactionWork.Commit();
                }

                WhereClasure(criteria, parameters, predicate);
            }
            catch (Exception)
            {
                transactionWork?.Rollback();
                throw;
            }
        }
コード例 #8
0
        public void TransactionRollback()
        {
            TestUtilities.ResetDatabase();

            using (var scope = TransactionFactory.Create())
            {
                Company companyGwiSoftware = new Company();
                companyGwiSoftware.Name     = "GWI Software";
                companyGwiSoftware.Location = "Vancouver";
                CompanyService.Save(companyGwiSoftware);

                Customer customerDanGreen = new Customer();
                customerDanGreen.FirstName = "Dan";
                customerDanGreen.LastName  = "Green";
                customerDanGreen.CompanyId = companyGwiSoftware.Id;
                CustomerService.Save(customerDanGreen);

                Assert.AreNotEqual(null, customerDanGreen.Id);
            }

            var companies = CompanyService.GetCollection();

            Assert.AreEqual(1, companies.Count);

            var customers = CustomerService.GetCollection();

            Assert.AreEqual(2, customers.Count);
        }
コード例 #9
0
        public void RollbackTransactionUpdateDataTestMethod()
        {
            ITransactionWork transactionWork = null;

            DataTable customerTable = new DataTable("Customer");

            using (transactionWork = TransactionFactory.Create())
            {
                transactionWork.ReadData(customerTable);
                DataRow newRow = customerTable.NewRow();
                newRow[1]            = 123;
                newRow[2]            = 321;
                newRow["FirstName"]  = "A.";
                newRow["MiddleName"] = "N.";
                newRow["LastName"]   = "Nimus";
                newRow[6]            = DateTime.Now;
                newRow[7]            = 0;
                newRow[8]            = 1;
                newRow[9]            = 2;
                customerTable.Rows.Add(newRow);
                for (int i = 0; i < customerTable.Rows.Count; i++)
                {
                    if ((string)customerTable.Rows[i]["LastName"] == "Nimus" ||
                        (string)customerTable.Rows[i]["FirstName"] == "Nimus")
                    {
                        customerTable.Rows[i].Delete();
                    }
                }
                transactionWork.UpdateData(customerTable);
                transactionWork.Rollback();
            }

            Assert.IsTrue(true);
        }
コード例 #10
0
        private static void GetDataByGlossary(string glossaryName, int id)
        {
            TransactionWork transactionWork      = null;
            string          storageProcedureName = string.Format("uspGet{0}By{1}", "Customer", glossaryName);
            SqlParameter    parameter            = new SqlParameter();

            parameter.DbType        = DbType.Int32;
            parameter.ParameterName = "@ID";
            parameter.Value         = id;
            string       storageProcedureNameReg = string.Format("uspGet{0}By{1}", "Register", glossaryName);
            SqlParameter parameterReg            = new SqlParameter();

            parameterReg.DbType        = DbType.Int32;
            parameterReg.ParameterName = "@ID";
            parameterReg.Value         = id;
            string       storageProcedureNameInv = string.Format("uspGet{0}By{1}", "Invalid", glossaryName);
            SqlParameter parameterInv            = new SqlParameter();

            parameterInv.DbType        = DbType.Int32;
            parameterInv.ParameterName = "@ID";
            parameterInv.Value         = id;

            string       storageProcedureNameInvBenefits = string.Format("uspGet{0}By{1}", "InvalidBenefits", glossaryName);
            SqlParameter parameterInvBenefits            = new SqlParameter();

            parameterInvBenefits.DbType        = DbType.Int32;
            parameterInvBenefits.ParameterName = "@ID";
            parameterInvBenefits.Value         = id;

            string       storageProcedureNameAddr = string.Format("uspGet{0}By{1}", "Address", glossaryName);
            SqlParameter parameterAddr            = new SqlParameter();

            parameterAddr.DbType        = DbType.Int32;
            parameterAddr.ParameterName = "@ID";
            parameterAddr.Value         = id;
            try
            {
                using (transactionWork = (TransactionWork)TransactionFactory.Create())
                {
                    transactionWork.Execute(_tables.CustomerDataTable, storageProcedureName, parameter);
                    transactionWork.Execute(_tables.RegisterDataTable, storageProcedureNameReg, parameterReg);
                    transactionWork.Execute(_tables.InvalidDataTable, storageProcedureNameInv, parameterInv);
                    transactionWork.Execute(_tables.InvalidBenefitsDataTable, storageProcedureNameInvBenefits, parameterInvBenefits);
                    transactionWork.Execute(_tables.AddressDataTable, storageProcedureNameAddr, parameterAddr);
                    transactionWork.Commit();
                }
                WhereClasure(glossaryName, new object[] { id }, "=");
                //whereClasure = "where " + glossaryName + "ID = @param";
                //value = id;
                //dbType = "@param int";
            }
            catch (Exception)
            {
                transactionWork?.Rollback();
                throw;
            }
        }
コード例 #11
0
        public void RollbackTransactionReadDataTestMethod()
        {
            ITransactionWork transactionWork = null;

            using (transactionWork = TransactionFactory.Create())
            {
                transactionWork.ReadData(new DataTable("Customer"));
                transactionWork.Rollback();
            }
            Assert.IsTrue(true);
        }
コード例 #12
0
    /// <inheritdoc />
    public async Task <Result> RespondAsync(IGuildMemberUpdate gatewayEvent, CancellationToken ct = default)
    {
        var guild = gatewayEvent.GuildID;

        var autoroles = await _autoroles.GetAutorolesAsync
                        (
            guild,
            q => q
            .Where(a => a.IsEnabled)
            .Where
            (
                a => a.Conditions.Any
                (
                    c =>
                    c.GetType() == typeof(RoleCondition)
                )
            ),
            ct
                        );

        foreach (var autorole in autoroles)
        {
            using var transaction = TransactionFactory.Create();

            var rolesToLookFor = autorole.Conditions
                                 .Where(c => c is RoleCondition)
                                 .Cast <RoleCondition>()
                                 .Select(c => c.RoleID);

            var userHasAutorole     = gatewayEvent.Roles.Contains(autorole.DiscordRoleID);
            var userHasRelevantRole = gatewayEvent.Roles.Any(r => rolesToLookFor.Contains(r));

            if (userHasAutorole || userHasRelevantRole)
            {
                var updateAutorole = await _autoroleUpdates.UpdateAutoroleForUserAsync
                                     (
                    autorole,
                    guild,
                    gatewayEvent.User.ID,
                    ct
                                     );

                if (!updateAutorole.IsSuccess)
                {
                    return(Result.FromError(updateAutorole));
                }
            }

            transaction.Complete();
        }

        return(Result.FromSuccess());
    }
コード例 #13
0
ファイル: MonthViewModel.cs プロジェクト: Fidru/BudgetPlaner
        public void AddNewTransaction(CategoryType categoryType)
        {
            var newPayment = PaymentFactory.Create(Element, categoryType);

            var newTransaction = TransactionFactory.Create(Element, newPayment);
            var transactionVm  = new TransactionViewModelFacotry(Services).ConvertToVm(newTransaction);

            AddTransaction(transactionVm);
            transactionVm.PaymentViewModel.AddTransaction(transactionVm);
            transactionVm.CurrentMonthVm = this;

            UpdateLists();
        }
コード例 #14
0
        public IEnumerable <PatchId> GetPatchesToInstall()
        {
            List <PatchId> inputPatches = this.checkParams.getPatchesList().OrderBy(patchId => patchId).ToList();

            using (Transaction transaction = TransactionFactory.Create(this.checkParams.DbDriverName, this.checkParams.ConnectionString)) {
                return(Util.RemoveExtra(
                           from patchId in this.checkParams.getPatchesList()
                           orderby patchId ascending
                           select patchId,
                           this.GetInstalledPatches()
                           ));
            }
        }
コード例 #15
0
        public void CreateTest()
        {
            void test <T>(BaseTransactionData r)
            {
                var o = TransactionFactory.Create(r);

                Assert.IsInstanceOfType(o, typeof(T));
            }

            test <Transaction>(GetRandom.Object <TransactionData>());
            test <RequestTransaction>(GetRandom.Object <RequestTransactionData>());
            test <Transaction>(null);
        }
コード例 #16
0
        private static void GetDataByCustomerID(int id)
        {
            TransactionWork transactionWork = null;

            String       storageProcedureName = "uspGetCustomers";
            SqlParameter parameter            = new SqlParameter();

            parameter.DbType        = DbType.Int32;
            parameter.Size          = 4;
            parameter.ParameterName = "@CustomerID";
            parameter.Value         = id;
            SqlParameter parameterReg = new SqlParameter();

            parameterReg.DbType        = DbType.Int32;
            parameterReg.Size          = 4;
            parameterReg.ParameterName = "@CustomerID";
            parameterReg.Value         = id;
            SqlParameter parameterInv = new SqlParameter();

            parameterInv.DbType        = DbType.Int32;
            parameterInv.Size          = 4;
            parameterInv.ParameterName = "@CustomerID";
            parameterInv.Value         = id;
            SqlParameter parameterAddr = new SqlParameter();

            parameterAddr.DbType        = DbType.Int32;
            parameterAddr.Size          = 4;
            parameterAddr.ParameterName = "@CustomerID";
            parameterAddr.Value         = id;
            try
            {
                using (transactionWork = (TransactionWork)TransactionFactory.Create())
                {
                    transactionWork.Execute(_tables.CustomerDataTable, storageProcedureName, parameter);
                    transactionWork.Execute(_tables.RegisterDataTable, "uspGetRegisterByCustomerID", parameterReg);
                    transactionWork.Execute(_tables.InvalidDataTable, "uspGetInvalidByCustomerID", parameterInv);
                    transactionWork.Execute(_tables.AddressDataTable, "uspGetAddressByCustomerID", parameterAddr);
                    transactionWork.Commit();
                }
                whereClasure = "where vgc.CustomerID = @param";
                value        = id;
                dbType       = "@param int";
            }
            catch (Exception)
            {
                transactionWork?.Rollback();
                throw;
            }
        }
コード例 #17
0
        public void TransactionNestedCommit()
        {
            TestUtilities.ResetDatabase();

            using (var scope = TransactionFactory.Create())
            {
                Company companyGwiSoftware = new Company();
                companyGwiSoftware.Name     = "GWI Software";
                companyGwiSoftware.Location = "Vancouver";
                CompanyService.Save(companyGwiSoftware);

                Customer customerDanGreen = new Customer();
                customerDanGreen.FirstName = "Dan";
                customerDanGreen.LastName  = "Green";
                customerDanGreen.CompanyId = companyGwiSoftware.Id;
                CustomerService.Save(customerDanGreen);

                using (var scope2 = TransactionFactory.Create())
                {
                    Company companyLblSoft = new Company();
                    companyLblSoft.Name     = "LblSoft";
                    companyLblSoft.Location = "Vancouver";
                    CompanyService.Save(companyLblSoft);

                    Customer customerLisaKimery = new Customer();
                    customerLisaKimery.FirstName = "Lisa";
                    customerLisaKimery.LastName  = "Kimery";
                    customerLisaKimery.CompanyId = companyLblSoft.Id;
                    CustomerService.Save(customerLisaKimery);

                    Assert.AreNotEqual(null, customerLisaKimery.Id);

                    scope2.Complete();
                }

                Assert.AreNotEqual(null, customerDanGreen.Id);

                scope.Complete();
            }

            var companies = CompanyService.GetCollection();

            Assert.AreEqual(3, companies.Count);

            var customers = CustomerService.GetCollection();

            Assert.AreEqual(4, customers.Count);
        }
コード例 #18
0
    /// <inheritdoc />
    public override async Task <Result> RespondAsync
    (
        IInteractionCreate gatewayEvent,
        CancellationToken ct = default
    )
    {
        using var transaction = TransactionFactory.Create();

        var executionResult = await base.RespondAsync(gatewayEvent, ct);

        if (executionResult.IsSuccess)
        {
            transaction.Complete();
        }

        return(executionResult);
    }
コード例 #19
0
        public void Create_ReturnsTransactionFromReliableStateManager()
        {
            var expectedTransaction = Substitute.For <ITransaction>();
            var reliableStorage     = Substitute.For <IReliableStateManagerReplica>();

            reliableStorage
            .CreateTransaction()
            .Returns(expectedTransaction);

            ITransactionFactory factory = new TransactionFactory(reliableStorage);

            var transaction = factory.Create();

            transaction
            .Should()
            .Be(expectedTransaction);
        }
コード例 #20
0
    /// <inheritdoc />
    protected override async Task <Result> ExecuteCommandAsync
    (
        string content,
        ICommandContext commandContext,
        CancellationToken ct = default
    )
    {
        using var transaction = TransactionFactory.Create();

        var executionResult = await base.ExecuteCommandAsync(content, commandContext, ct);

        if (executionResult.IsSuccess)
        {
            transaction.Complete();
        }

        return(executionResult);
    }
コード例 #21
0
    /// <inheritdoc />
    public async Task <Result> RespondAsync(IMessageReactionAdd gatewayEvent, CancellationToken ct = default)
    {
        if (!gatewayEvent.GuildID.IsDefined(out var guildID))
        {
            return(Result.FromSuccess());
        }

        var autoroles = await _autoroles.GetAutorolesAsync
                        (
            guildID,
            q => q
            .Where(a => a.IsEnabled)
            .Where
            (
                a => a.Conditions.Any
                (
                    c =>
                    c is ReactionCondition &&
                    ((ReactionCondition)c).MessageID == gatewayEvent.MessageID &&
                    ((ReactionCondition)c).ChannelID == gatewayEvent.ChannelID &&
                    ((ReactionCondition)c).EmoteName == gatewayEvent.Emoji.Name
                )
            ),
            ct
                        );

        var user = gatewayEvent.UserID;

        foreach (var autorole in autoroles)
        {
            using var transaction = TransactionFactory.Create();

            var updateAutorole = await _autoroleUpdates.UpdateAutoroleForUserAsync(autorole, guildID, user, ct);

            if (!updateAutorole.IsSuccess)
            {
                return(Result.FromError(updateAutorole));
            }

            transaction.Complete();
        }

        return(Result.FromSuccess());
    }
コード例 #22
0
 public IEnumerable <PatchId> GetInstalledPatches()
 {
     using (Transaction transaction = TransactionFactory.Create(this.checkParams.DbDriverName, this.checkParams.ConnectionString)) {
         return((
                    from row in transaction.ExecuteReader(
                        string.Format(
                            "select {1}, {2} from {0} where {3} = {4}",
                            transaction.EscapeName(this.checkParams.PatchesTable),
                            transaction.EscapeName("VERSION"),
                            transaction.EscapeName("NAME"),
                            transaction.EscapeName("STATUS"),
                            transaction.MarkParam("pstatus")
                            ),
                        new Dictionary <string, object> {
             { "pstatus", STATUS_INSTALLED },
         }
                        )
                    let patch = new PatchId(int.Parse(row["VERSION"]), row["NAME"])
                                orderby patch ascending
                                select patch
                    ).ToList());
     }
 }
コード例 #23
0
        public void TransactionFactoryCreateTest()
        {
            TransactionFactory tf    = TransactionFactory.Instance();
            Transaction        input = new Transaction();

            input.CurrencyCode      = _currency;
            input.Description       = _desc;
            input.Merchant          = _merchant;
            input.TransactionAmount = _amount;
            input.TransactionDate   = _tdate;

            ITransaction output = tf.Create(input);

            Assert.IsNotNull(output);
            Assert.AreEqual(1, output.TransactionId);
            Assert.IsTrue(output.CreatedDate >= _tdate && output.CreatedDate <= DateTime.Now,
                          String.Format("CreationDateTest {0} >= {1} <= {2}", output.ModifiedDate, _tdate, DateTime.Now));
            Assert.AreEqual(output.CreatedDate, output.ModifiedDate);
            Assert.AreEqual(_currency, output.CurrencyCode);
            Assert.AreEqual(_merchant, output.Merchant);
            Assert.AreEqual(_desc, output.Description);
            Assert.AreEqual(_amount, output.TransactionAmount);
        }
コード例 #24
0
        public void TransactionReadDataCommitTestMethod()
        {
            ITransactionWork transactionWork = null;

            using (transactionWork = TransactionFactory.Create())
            {
                transactionWork.ReadData(new DataTable("AdminDivision"));
                transactionWork.ReadData(new DataTable("Appp"));
                transactionWork.ReadData(new DataTable("Benefits"));
                transactionWork.ReadData(new DataTable("ChiperRecept"));
                transactionWork.ReadData(new DataTable("Gender"));
                transactionWork.ReadData(new DataTable("Land"));
                transactionWork.ReadData(new DataTable("DisabilityGroup"));
                transactionWork.ReadData(new DataTable("RegisterType"));
                transactionWork.ReadData(new DataTable("TypeStreet"));
                transactionWork.ReadData(new DataTable("WhyDeRegister"));

                transactionWork.ReadData(new DataTable("Customer"));
                transactionWork.ReadData(new DataTable("InvalidBenefits"));
                transactionWork.Commit();
                Assert.IsTrue(true);
            }
        }
コード例 #25
0
        public void FailedAndRollbackTransactionUpdateDataTestMethod()
        {
            ITransactionWork transactionWork = null;

            DataTable adminDivisionTable = new DataTable("AdminDivision");

            try
            {
                using (transactionWork = TransactionFactory.Create())
                {
                    transactionWork.ReadData(adminDivisionTable);
                    DataRow newRow = adminDivisionTable.NewRow();
                    newRow[1] = "aaa";
                    adminDivisionTable.Rows.Add(newRow);
                    throw new Exception();
                }
            }
            catch
            {
                transactionWork? .Rollback();
            }

            Assert.IsTrue(true);
        }
コード例 #26
0
    /// <inheritdoc />
    public async Task <Result> RespondAsync(IMessageCreate gatewayEvent, CancellationToken ct = default)
    {
        if (!gatewayEvent.GuildID.IsDefined(out var guildID))
        {
            return(Result.FromSuccess());
        }

        using var transaction = TransactionFactory.Create();

        var user = gatewayEvent.Author.ID;

        var getUserStatistics = await _statistics.GetOrCreateUserServerStatisticsAsync(guildID, user, ct);

        if (!getUserStatistics.IsSuccess)
        {
            return(Result.FromError(getUserStatistics));
        }

        var userStatistics = getUserStatistics.Entity;
        var setTotalCount  = await _statistics.SetTotalMessageCountAsync
                             (
            userStatistics,
            (userStatistics.TotalMessageCount ?? 0) + 1,
            ct
                             );

        if (!setTotalCount.IsSuccess)
        {
            return(setTotalCount);
        }

        var channel = gatewayEvent.ChannelID;
        var getChannelStatistics = await _statistics.GetOrCreateUserChannelStatisticsAsync
                                   (
            guildID,
            user,
            channel,
            ct
                                   );

        if (!getChannelStatistics.IsSuccess)
        {
            return(Result.FromError(getChannelStatistics));
        }

        var channelStatistics = getChannelStatistics.Entity;
        var setChannelCount   = await _statistics.SetChannelMessageCountAsync
                                (
            channelStatistics,
            (channelStatistics.MessageCount ?? 0) + 1,
            ct
                                );

        if (!setChannelCount.IsSuccess)
        {
            return(setChannelCount);
        }

        // Finally, update the relevant autoroles
        var autoroles = await _autoroles.GetAutorolesAsync
                        (
            guildID,
            q => q
            .Where(a => a.IsEnabled)
            .Where
            (
                a => a.Conditions.Any
                (
                    c =>
                    c.GetType() == typeof(MessageCountInGuildCondition) ||
                    c.GetType() == typeof(MessageCountInChannelCondition)
                )
            ),
            ct
                        );

        foreach (var autorole in autoroles)
        {
            var updateAutorole = await _autoroleUpdates.UpdateAutoroleForUserAsync(autorole, guildID, user, ct);

            if (!updateAutorole.IsSuccess)
            {
                return(Result.FromError(updateAutorole));
            }
        }

        transaction.Complete();
        return(Result.FromSuccess());
    }
コード例 #27
0
        public static void Main(string[] args)
        {
            string opzione = string.Empty;
            List <ITransazione> transazioni = new List <ITransazione>();
            ITransactionFactory factory     = new TransactionFactory();

            StampaMenu();

            do
            {
                Console.WriteLine();
                Console.Write("Inserire opzione desiderata: ");
                opzione = Console.ReadLine();
                switch (opzione)
                {
                case "m":
                case "menu":
                    StampaMenu();
                    break;

                case "a":
                case "aggiungi":
                    try
                    {
                        ITransazione nuovaTransazione = factory.Create();
                        Console.WriteLine();

                        Console.Write("Data transazione (MM/gg/aaaa): ");
                        string dtTransazione = Console.ReadLine();
                        nuovaTransazione.DataTransazione = DateTime.Parse(dtTransazione);
                        Console.Write("Tipo transazione (Spesa/Ricavo): ");
                        nuovaTransazione.Tipo = Console.ReadLine();
                        Console.Write("Categoria transazione: ");
                        nuovaTransazione.Categoria = Console.ReadLine();
                        Console.Write("Descrizione transazione: ");
                        nuovaTransazione.Descrizione = Console.ReadLine();
                        Console.Write("Importo transazione: ");
                        string impTransazione = Console.ReadLine();
                        nuovaTransazione.Importo = decimal.Parse(impTransazione);

                        transazioni.Add(nuovaTransazione);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Errore durante l'inserimento della transazione.");
                    }
                    break;

                case "c":
                case "cancella":
                    if (transazioni.Count == 0)
                    {
                        Console.WriteLine("Questa opzione non è disponibile. La lista è vuota.");
                    }
                    else if (transazioni.Count == 1)
                    {
                        Console.Write("Sei sicuro di voler procedere? (si/no): ");
                        opzione = Console.ReadLine();
                        if (opzione == "si")
                        {
                            transazioni.RemoveAt(0);
                            Console.WriteLine("Elemento cancellato.");
                        }
                        else if (opzione == "no")
                        {
                            Console.WriteLine("Operazione annullata.");
                        }
                        else
                        {
                            Console.WriteLine("Opzione non valida.");
                        }
                    }
                    else
                    {
                        Console.Write("Qual'è la posizione della transazione che vuoi cancellare? ");
                        opzione = Console.ReadLine();
                        try
                        {
                            int posizione = int.Parse(opzione);
                            if (posizione > 0 && posizione <= transazioni.Count)
                            {
                                Console.Write("Sei sicuro di voler procedere? (si/no): ");
                                opzione = Console.ReadLine();
                                if (opzione == "si")
                                {
                                    transazioni.RemoveAt(posizione - 1);
                                    Console.WriteLine("Elemento cancellato.");
                                }
                                else if (opzione == "no")
                                {
                                    Console.WriteLine("Operazione annullata.");
                                }
                                else
                                {
                                    Console.WriteLine("Opzione non valida.");
                                }
                            }
                            else
                            {
                                Console.WriteLine("Posizione non valida. Le posizioni valide sono da 1 a " + transazioni.Count + ".");
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Errore durante la cancellazione.");
                        }
                    }
                    break;

                case "s":
                case "stampa":
                    if (transazioni.Count == 0)
                    {
                        Console.WriteLine("Non ci sono transazioni.");
                    }
                    else
                    {
                        for (int i = 0; i < transazioni.Count; i++)
                        {
                            ITransazione transazione = transazioni[i];

                            Console.WriteLine((i + 1) + ":");
                            Console.WriteLine(transazione);
                            Console.WriteLine();
                        }
                    }
                    break;

                case "e":
                case "esci":
                    Console.Write("Sei sicuro di voler uscire? (si/no): ");
                    opzione = Console.ReadLine();
                    if (opzione == "si")
                    {
                        return;
                    }
                    if (opzione != "no")
                    {
                        Console.WriteLine("Opzione non riconosciuta.");
                    }
                    break;

                default:
                    Console.WriteLine("Opzione non riconosciuta. Riprovare.");
                    break;
                }
            } while (true);
        }
コード例 #28
0
    /// <inheritdoc />
    public async Task <Result> RespondAsync(IMessageReactionRemoveEmoji gatewayEvent, CancellationToken ct = default)
    {
        if (!gatewayEvent.GuildID.IsDefined(out var guildID))
        {
            return(Result.FromSuccess());
        }

        var autoroles = await _autoroles.GetAutorolesAsync
                        (
            guildID,
            q => q
            .Where(a => a.IsEnabled)
            .Where
            (
                a => a.Conditions.Any
                (
                    c =>
                    c is ReactionCondition &&
                    ((ReactionCondition)c).MessageID == gatewayEvent.MessageID &&
                    ((ReactionCondition)c).ChannelID == gatewayEvent.ChannelID &&
                    ((ReactionCondition)c).EmoteName == gatewayEvent.Emoji.Name
                )
            ),
            ct
                        );

        var users = new List <Snowflake>();
        Optional <Snowflake> after = default;

        while (true)
        {
            var listMembers = await _guildAPI.ListGuildMembersAsync(guildID, after : after, ct : ct);

            if (!listMembers.IsSuccess)
            {
                return(Result.FromError(listMembers));
            }

            var members = listMembers.Entity;
            if (members.Count == 0)
            {
                break;
            }

            users.AddRange(listMembers.Entity.Select(m => m.User.Value.ID));
            after = users.Last();
        }

        foreach (var autorole in autoroles)
        {
            foreach (var user in users)
            {
                using var transaction = TransactionFactory.Create();

                var updateAutorole = await _autoroleUpdates.UpdateAutoroleForUserAsync(autorole, guildID, user, ct);

                if (!updateAutorole.IsSuccess)
                {
                    return(Result.FromError(updateAutorole));
                }

                transaction.Complete();
            }
        }

        return(Result.FromSuccess());
    }
コード例 #29
0
    private async Task <Result> UpdateTimestampAndRelevantAutorolesAsync
    (
        Snowflake guild,
        Snowflake user,
        CancellationToken ct = default
    )
    {
        {
            using var timestampTransaction = TransactionFactory.Create(ReadCommitted);

            var getServerStatistics = await _statistics.GetOrCreateUserServerStatisticsAsync(guild, user, ct);

            if (!getServerStatistics.IsSuccess)
            {
                return(Result.FromError(getServerStatistics));
            }

            var serverStatistics = getServerStatistics.Entity;

            var updateTimestamp = await _statistics.UpdateTimestampAsync(serverStatistics, ct);

            if (!updateTimestamp.IsSuccess)
            {
                return(updateTimestamp);
            }

            timestampTransaction.Complete();
        }

        var autoroles = await _autoroles.GetAutorolesAsync
                        (
            guild,
            q => q
            .Where(a => a.IsEnabled)
            .Where
            (
                a => a.Conditions.Any
                (
                    c =>
                    c.GetType() == typeof(TimeSinceLastActivityCondition) ||
                    c.GetType() == typeof(TimeSinceJoinCondition)
                )
            ),
            ct
                        );

        foreach (var autorole in autoroles)
        {
            using var transaction = TransactionFactory.Create();

            var updateAutorole = await _autoroleUpdates.UpdateAutoroleForUserAsync(autorole, guild, user, ct);

            if (!updateAutorole.IsSuccess)
            {
                return(Result.FromError(updateAutorole));
            }

            transaction.Complete();
        }

        return(Result.FromSuccess());
    }
コード例 #30
0
        public static void ExportToExcel()
        {
            DataTable       table           = new DataTable();
            TransactionWork transactionWork = null;

            SqlParameter[] parameters = new SqlParameter[3];

            SqlParameter parameter = new SqlParameter();

            parameter.DbType        = DbType.String;
            parameter.Size          = 100;
            parameter.ParameterName = "@whereClasure";
            parameter.Value         = whereClasure;
            parameters[0]           = parameter;

            parameter               = new SqlParameter();
            parameter.DbType        = DbType.String;
            parameter.ParameterName = "@Param";
            parameter.Size          = 100;
            if (value == null)
            {
                parameter.Value = string.Empty;
            }
            else
            {
                parameter.Value = value;
            }
            parameter.IsNullable = true;
            parameters[1]        = parameter;

            parameter               = new SqlParameter();
            parameter.DbType        = DbType.String;
            parameter.Size          = 30;
            parameter.ParameterName = "@ParamType";
            parameter.Value         = dbType;
            parameter.IsNullable    = true;
            parameters[2]           = parameter;

            try
            {
                using (transactionWork = (TransactionWork)TransactionFactory.Create())
                {
                    transactionWork.Execute(table, "uspDynamicQuery", parameters);
                    transactionWork.Commit();
                }
            }
            catch (Exception)
            {
                transactionWork?.Rollback();
                throw;
            }

            FastExportingMethod.ExportToExcel(table,
                                              Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "List"));
            FastExportingMethod.GemExportToExcel(table,
                                                 Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "List2.xls"));
            table.Dispose();
            table = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }