public static void CreditWriters() { //Credit var amount = "(SELECT [amount] FROM CTE WHERE CTE.userId = Users.UserId)"; var updateCommand = String.Format(@" UPDATE Users SET Users.Balance1 = Users.Balance1 + {0}, Users.TotalEarned = Users.TotalEarned + {0}, Users.StatsEarned = cast(({0}+CONVERT(decimal(19,8),(CAST(SUBSTRING(Users.StatsEarned,0, CHARINDEX('#', Users.StatsEarned)) AS varchar(30))))) as varchar(1000)) + SUBSTRING(Users.StatsEarned,CHARINDEX('#', Users.StatsEarned), 1000) WHERE Users.UserId IN (SELECT DISTINCT UserId FROM CTE);", amount); TableHelper.ExecuteRawCommandNonQuery(GetWritersCTE() + updateCommand); //Add Balance Logs var balanceLogsCommand = GetWritersCTE() + "SELECT * FROM CTE;"; BalanceLogManager.AddRange(balanceLogsCommand, "Article writing", BalanceType.MainBalance, BalanceLogType.ArticleWriting); //Add Money credited to articles table var creditArticlesQuery = @" WITH CTE AS ( SELECT av.ArticleId AS Article, FLOOR((COUNT(av.Id))/1000) AS Quantity, m.ArticleCreatorCPM AS PricePerQuantity FROM ArticleViews av INNER JOIN Articles a ON av.ArticleId = a.Id INNER JOIN Users u ON u.UserId = a.CreatorUserId INNER JOIN Memberships m ON m.MembershipId = u.UpgradeId WHERE av.CreatorCredited = 0 GROUP BY av.ArticleId, m.ArticleCreatorCPM HAVING FLOOR((COUNT(av.Id))/1000) > 0 ) UPDATE Articles SET CreatorMoneyEarned = CreatorMoneyEarned + (SELECT Quantity * PricePerQuantity FROM CTE WHERE Articles.Id = CTE.Article) WHERE Id IN (SELECT DISTINCT Article FROM CTE);"; TableHelper.ExecuteRawCommandNonQuery(creditArticlesQuery); //Mark views as credited var query = @"WITH CTE AS ( SELECT av.ArticleId AS Article, FLOOR((COUNT(av.Id))/1000) AS Quantity FROM ArticleViews av INNER JOIN Articles a ON av.ArticleId = a.Id WHERE av.CreatorCredited = 0 GROUP BY av.ArticleId HAVING FLOOR((COUNT(av.Id))/1000) > 0 ) UPDATE ArticleViews SET ArticleViews.CreatorCredited = 1 WHERE ArticleViews.ArticleId IN (SELECT DISTINCT Article FROM CTE) AND ArticleViews.Id IN ( SELECT TOP (SELECT Quantity*1000 FROM CTE WHERE ArticleViews.ArticleId = CTE.Article) av.Id FROM ArticleViews av WHERE av.ArticleId IN (SELECT Article FROM CTE WHERE Article = ArticleViews.ArticleId) ORDER BY av.ViewDate ASC ) "; TableHelper.ExecuteRawCommandNonQuery(query); }
public static void CRON() { try { if (!AppSettings.TitanFeatures.AdvertMarketplaceEnabled) { return; } AppSettings.Marketplace.Reload(); if (AppSettings.Marketplace.MarketplaceFundsExpireAfterDays == -1) { return; } var serverTime = AppSettings.ServerTime.ToDBString(); var balanceUpdateCommand = string.Format(@"UPDATE Users SET MarketplaceBalance = MarketplaceBalance - (SELECT SUM(Amount) FROM MarketplaceBalanceLogs mbl WHERE mbl.UserId = Users.UserId AND '{0}' > DateAdd(d, {1}, DateAdded))", serverTime, AppSettings.Marketplace.MarketplaceFundsExpireAfterDays); var balanceLogsCommand = string.Format(@"SELECT mbl.UserId AS userId, - SUM(mbl.Amount) AS amount, u.MarketplaceBalance AS state FROM MarketplaceBalanceLogs mbl JOIN Users u ON mbl.UserId = u.UserId WHERE '{0}' > DateAdd(d, 10, DateAdded) GROUP BY mbl.UserId, u.MarketplaceBalance", serverTime); var clearMBLCommand = string.Format(@"DELETE FROM MarketplaceBalanceLogs WHERE '{0}' > DateAdd(d, {1}, DateAdded);", serverTime, AppSettings.Marketplace.MarketplaceFundsExpireAfterDays); TableHelper.ExecuteRawCommandNonQuery(balanceLogsCommand); using (var bridge = ParserPool.Acquire(Database.Client)) { BalanceLogManager.AddRange(bridge.Instance, balanceLogsCommand, "Balance expiration", BalanceType.MarketplaceBalance, BalanceLogType.Other); } TableHelper.ExecuteRawCommandNonQuery(clearMBLCommand); } catch (Exception ex) { ErrorLogger.Log(ex); } }
private static void RewardMembers() { string idsToReward = GetUserIdsToReward(); if (string.IsNullOrWhiteSpace(idsToReward)) { return; } string amountQuery = @"(SELECT Reward FROM ReferralLeaderShipLevels WHERE Number = (CASE Users.LeadershipLevelId WHEN -1 THEN 1 ELSE (SELECT Number + 1 FROM ReferralLeadershipLevels WHERE Id = Users.LeadershipLevelId) END ))"; string rewardQuery = string.Format(@"UPDATE Users SET Users.Balance1 = Users.Balance1 + {0}, Users.TotalEarned = Users.TotalEarned + {0}, Users.StatsEarned = cast(({0}+CONVERT(decimal(10,4),(CAST(SUBSTRING(Users.StatsEarned,0, CHARINDEX('#', Users.StatsEarned)) AS varchar(10))))) as varchar(1000)) + SUBSTRING(Users.StatsEarned,CHARINDEX('#', Users.StatsEarned), 1000) WHERE Users.UserId IN ({1})", amountQuery, idsToReward); TableHelper.ExecuteRawCommandNonQuery(rewardQuery); string balanceLogHelperQuery = string.Format(@"SELECT Users.UserId AS userId, {0} as amount, Users.Balance1 AS state FROM Users WHERE Users.UserId IN ({1})", amountQuery, idsToReward); using (var bridge = ParserPool.Acquire(Database.Client)) { BalanceLogManager.AddRange(bridge.Instance, balanceLogHelperQuery, "Leadership Reward", BalanceType.MainBalance, BalanceLogType.LeadershipReward); } string updateLeadershipIdQuery = string.Format(@" UPDATE Users SET Users.LeadershipLevelId = (SELECT Id FROM ReferralLeaderShipLevels WHERE Number = CASE Users.LeadershipLevelId WHEN -1 THEN 1 ELSE (SELECT NextNumber FROM ReferralLeadershipLevels WHERE Id = Users.LeadershipLevelId) END), Users.LeadershipResetTime = GETDATE() WHERE UserId IN ({0})", idsToReward); TableHelper.ExecuteRawCommandNonQuery(updateLeadershipIdQuery); }
public static void CRON() { if (TitanFeatures.IsEpadilla) { //1. Send info about balances to S4DS var UsersToSend = TableHelper.GetListFromRawQuery <Member>("SELECT * FROM Users WHERE Balance1 > 0"); foreach (var userToSend in UsersToSend) { try { CreditS4DSPacks(userToSend); } catch (Exception ex) { ErrorLogger.Log(ex); } } try { //2. Reset all balances to 0 using (var parser = ParserPool.Acquire(Database.Client).Instance) { string dtCommand = String.Format(@" SELECT U.UserId AS userId, -1 * U.Balance1 AS amount, 0.00000000 AS state FROM Users U WHERE U.Balance1 > 0"); BalanceLogManager.AddRange(parser, dtCommand, "S4DS daily deduction", BalanceType.MainBalance, BalanceLogType.Other); } } catch (Exception ex) { ErrorLogger.Log(ex); } TableHelper.ExecuteRawCommandNonQuery("UPDATE Users SET Balance1 = 0 WHERE Balance1 > 0"); } }
public static void GlobalMemberAdjustHelper(Parser parser, string selectCommand, string updateCommand, string whereCommand, string note, Money amount, BalanceLogType balanceLogType) { //Add logs FAST var InactivityUsersDataTable = parser.ExecuteRawCommandToDataTable(selectCommand + whereCommand); var InactivityUsers = TableHelper.GetListFromDataTable <Member>(InactivityUsersDataTable, 100, true); var List = new List <KeyValuePair <int, Money> >(); var ListActuaiBalance = new List <KeyValuePair <int, Money> >(); foreach (var member in InactivityUsers) { List.Add(new KeyValuePair <int, Money>(member.Id, amount * -1)); ListActuaiBalance.Add(new KeyValuePair <int, Money>(member.Id, member.MainBalance - amount)); } BalanceLogManager.FastAddLogs(List, BalanceType.MainBalance, note, ListActuaiBalance, balanceLogType); //Update all parser.ExecuteRawCommandNonQuery(updateCommand + whereCommand); }
public static void CreditInfluencers() { //Credit var amount = "(SELECT [amount] FROM CTE WHERE CTE.userId = Users.UserId)"; var updateCommand = String.Format(@" UPDATE Users SET Users.Balance1 = Users.Balance1 + {0}, Users.TotalEarned = Users.TotalEarned + {0}, Users.StatsEarned = cast(({0}+CONVERT(decimal(19,8),(CAST(SUBSTRING(Users.StatsEarned,0, CHARINDEX('#', Users.StatsEarned)) AS varchar(30))))) as varchar(1000)) + SUBSTRING(Users.StatsEarned,CHARINDEX('#', Users.StatsEarned), 1000), Users.StatsArticlesTotalSharesMoney = cast(({0}+CONVERT(decimal(19,8),(CAST(SUBSTRING(Users.StatsArticlesTotalSharesMoney,0, CHARINDEX('#', Users.StatsArticlesTotalSharesMoney)) AS varchar(30))))) as varchar(1000)) + SUBSTRING(Users.StatsArticlesTotalSharesMoney,CHARINDEX('#', Users.StatsArticlesTotalSharesMoney), 1000) WHERE Users.UserId IN (SELECT DISTINCT UserId FROM CTE);", amount); TableHelper.ExecuteRawCommandNonQuery(GetInfluencersCTE() + updateCommand); //Add Balance Logs var balanceLogsCommand = GetInfluencersCTE() + "SELECT * FROM CTE;"; BalanceLogManager.AddRange(balanceLogsCommand, "Article sharing", BalanceType.MainBalance, BalanceLogType.ArticleSharing); //Mark views as credited var query = @"WITH CTE AS ( SELECT av.ArticleId AS Article, av.InfluencerUserId AS Influencer, FLOOR((COUNT(av.Id))/1000) AS Quantity FROM ArticleViews av WHERE av.InfluencerUserId > 0 AND av.InfluencerCredited = 0 GROUP BY av.ArticleId, av.InfluencerUserId HAVING FLOOR((COUNT(av.Id))/1000) > 0 ) UPDATE ArticleViews SET ArticleViews.InfluencerCredited = 1 WHERE ArticleViews.ArticleId IN (SELECT DISTINCT Article FROM CTE) AND ArticleViews.InfluencerUserId IN (SELECT DISTINCT Influencer FROM CTE) AND ArticleViews.Id IN ( SELECT TOP (SELECT Quantity*1000 FROM CTE WHERE ArticleViews.ArticleId = CTE.Article AND ArticleViews.InfluencerUserId = CTE.Influencer) av.Id FROM ArticleViews av WHERE av.ArticleId IN (SELECT Article FROM CTE WHERE Article = ArticleViews.ArticleId) AND av.InfluencerUserId IN (SELECT Influencer FROM CTE WHERE Influencer = ArticleViews.InfluencerUserId) ORDER BY av.ViewDate ASC ) "; TableHelper.ExecuteRawCommandNonQuery(query); }
public static void AddRange(Parser parser, string dataTableCommand, string note, BalanceType target, BalanceLogType balanceLogType) { //You need to provide DataTable with the following variables (User Ids must be unique): //userId => UserId //amount => money that will be added to the balance //state => current account state (AFTER the operation) var List = new List <KeyValuePair <int, Money> >(); var ListActualBalance = new List <KeyValuePair <int, Money> >(); var dt = parser.ExecuteRawCommandToDataTable(dataTableCommand); foreach (DataRow row in dt.Rows) { if (new Money((Decimal)row["amount"]) != Money.Zero) { List.Add(new KeyValuePair <int, Money>((int)row["userId"], new Money((Decimal)row["amount"]))); ListActualBalance.Add(new KeyValuePair <int, Money>((int)row["userId"], new Money((Decimal)row["state"]))); } } BalanceLogManager.FastAddLogs(List, target, note, ListActualBalance, balanceLogType); }
public static void CRON() { using (var bridge = ParserPool.Acquire(Database.Client)) { //0. RevenueShareAdsWatched yesterday string RevenueShareAdsWatchedCommand = @" UPDATE Users SET RevenueShareAdsWatchedYesterday = ( CASE WHEN Users.RSAAdsViewed = '-1' THEN -1 ELSE len(Users.RSAAdsViewed) - len(replace(Users.RSAAdsViewed, '#', '')) END ) + 1 "; bridge.Instance.ExecuteRawCommandNonQuery(RevenueShareAdsWatchedCommand); } using (var bridge = ParserPool.Acquire(Database.Client)) { //1. Credit new Referral Reward CreditForNewReferrals(); //2. Delete watched ads & TrafficGrid and other string resetDailyStatsCommand = "UPDATE Users SET " + Member.Columns.ViewedAds + " = '-1', " + Member.Columns.TrafficGridHitsToday + " = 0, PointsToday = 0, PointsCreditedForVideoToday = 0, PointsCreditedForSearchToday = 0, CPACompletedToday = 0, CompletedDailyCPAOffersToday = '-1', CompletedOffersFromOfferwallsToday = 0, MatrixBonusMoneyCyclesToday = 0, CompletedOffersMoreThan100pFromOfferwallsToday = 0, FbLikesToday = 0"; if (AppSettings.RevShare.DistributionTime != DistributionTimePolicy.EveryWeek || AppSettings.ServerTime.DayOfWeek == AppSettings.RevShare.DayOfWeekDistribution) { resetDailyStatsCommand += ", RSAAdsViewed = '-1'"; } bridge.Instance.ExecuteRawCommandNonQuery(resetDailyStatsCommand); } //3. Recalculate Statistics RecalculateStatistics(Member.Columns.StatsEarned, true); RecalculateStatistics(Member.Columns.StatsClicks, false); RecalculateStatistics(Member.Columns.UserClicksStats, false); RecalculateStatistics("RawDirectReferralsClicks", false); RecalculateStatistics("RawRentedReferralsClicks", false); RecalculateStatistics("StatsDirectReferralsEarned", true); RecalculateStatistics("StatsPointsEarned", false); RecalculateStatistics("StatsDirectReferralsPointsEarned", false); RecalculateStatistics("StatsDRAdPacksEarned", true); RecalculateStatistics("StatsCashLinksEarned", true); RecalculateStatistics("StatsDRCashLinksEarned", true); using (var bridge = ParserPool.Acquire(Database.Client)) { //4. Mark inactive ones string Command = string.Format(@"UPDATE Users SET {0} = {2}, AccountStatus = 'Expired' WHERE Username <> 'admin' AND {0} = {3} AND ( ( (LastLoginDate IS NOT NULL AND DATEADD (day, {1}, LastLoginDate) < GETDATE()) OR (LastLoginDate IS NULL AND DATEADD (day, {1}, RegisterDate) < GETDATE()) ) AND ( (VacationModeEnds IS NULL) OR (DATEADD (day, {1}, VacationModeEnds) < GETDATE()) ) )", "AccountStatusInt", AppSettings.Misc.DaysToInactivity, (int)MemberStatus.Expired, (int)MemberStatus.Active); bridge.Instance.ExecuteRawCommandNonQuery(Command); //5. Upgrade expiration var upgradeExpiredMembersQuery = "SELECT * FROM Users WHERE UpgradeExpires IS NOT NULL AND UpgradeExpires < GETDATE()"; var upgradeExpiredMembers = TableHelper.GetListFromRawQuery <Member>(upgradeExpiredMembersQuery); foreach (Member user in upgradeExpiredMembers) { DateTime membershipExpires = (DateTime)user.MembershipExpires; var dateWhenReferralsWillBeResolved = membershipExpires.AddDays(AppSettings.Referrals.ResolveReferralsAfterSpecifiedDays); if (dateWhenReferralsWillBeResolved <= DateTime.Now) { user.ResolveReferralsLimitDate = null; user.Downgrade(); } else { user.ResolveReferralsLimitDate = dateWhenReferralsWillBeResolved; user.Downgrade(false); } History.AddUpgradeExpiration(user.Name, user.MembershipName); } var usersWhoCouldHaveTooManyReferralsQuery = string.Format("SELECT * FROM {0} WHERE {1} IS NOT NULL AND {1} <= GETDATE()", Member.TableName, Member.Columns.ResolveReferralsLimitDate, AppSettings.Referrals.ResolveReferralsAfterSpecifiedDays); var usersWhoCouldHaveTooManyReferrals = TableHelper.GetListFromRawQuery <Member>(usersWhoCouldHaveTooManyReferralsQuery); foreach (var user in usersWhoCouldHaveTooManyReferrals) { user.ResolveReferralsLimitDate = null; user.SaveMembership(); user.ResolveReferralLimits(user.Membership); } DateTime DateNow = DateTime.Now; //6 Vacation mode expiration string VacationModeExpiredCommand = "UPDATE Users SET LastActivityTime = GETDATE(), AccountStatusInt = " + (int)MemberStatus.Active + ", AccountStatus = 'Active' WHERE VacationModeEnds IS NOT NULL AND VacationModeEnds < GETDATE() AND AccountStatusInt = " + (int)MemberStatus.VacationMode; bridge.Instance.ExecuteRawCommandNonQuery(VacationModeExpiredCommand); //7. RemovalReferrals Member.DeleteReferralsCRON(); //8. Inactivity fee: if (AppSettings.VacationAndInactivity.InactivityChargePerDay > Money.Zero) { try { string InactivityUpdateCommand = string.Format("UPDATE Users SET Balance1 = Balance1 - {0}", AppSettings.VacationAndInactivity.InactivityChargePerDay.ToClearString()); string InactivitySelectCommand = "SELECT * FROM Users"; string InactivityCondition = string.Format(" WHERE (LastActivityTime IS NOT NULL AND LastActivityTime < '{0}') AND AccountStatusInt = {1}", DateNow.AddDays(-AppSettings.VacationAndInactivity.DaysToInactivityCharge).ToDBString(), (int)MemberStatus.Active); BalanceLogManager.GlobalMemberAdjustHelper(bridge.Instance, InactivitySelectCommand, InactivityUpdateCommand, InactivityCondition, "Inactivity fee", AppSettings.VacationAndInactivity.InactivityChargePerDay, BalanceLogType.Other); } catch (Exception ex) { ErrorLogger.Log(ex); } } if (DateNow.Day == 1) { bridge.Instance.ExecuteRawCommandNonQuery("UPDATE Users SET PtcAutoSurfClicksThisMonth = 0;"); } DowngradeMembersLevels(); //Automatically reject all payout requests from banned members //We are doing it to properly calculate 'CheckMaxValueOfPendingRequestsPerDay' for payment processors var PayoutRequestsToReject = TableHelper.GetListFromRawQuery <PayoutRequest>(PayoutRequest.GetPayoutRequestsSQLQuery(true)); foreach (var request in PayoutRequestsToReject) { PayoutManager.RejectRequest(request); } } //9. Commissions Income Statistics //WEEKLY if (AppSettings.ServerTime.DayOfWeek == DayOfWeek.Sunday) { TableHelper.ExecuteRawCommandNonQuery("UPDATE Users SET StatsCommissionsLastWeekIncome = StatsCommissionsCurrentWeekIncome, StatsCommissionsCurrentWeekIncome = 0"); } //MONTHLY if (AppSettings.ServerTime.Day == DateTime.DaysInMonth(AppSettings.ServerTime.Year, AppSettings.ServerTime.Month)) { TableHelper.ExecuteRawCommandNonQuery("UPDATE Users SET StatsCommissionsLastMonthIncome = StatsCommissionsCurrentMonthIncome, StatsCommissionsCurrentMonthIncome = 0"); } }
public Money DistributeUsingPriority(Money amount, int AdPackTypeId) { //Updates all adpacks string AdPacksUpdateCommnad = String.Format(@" UPDATE AdPacks SET MoneyReturned = MoneyReturned + (FLOOR({0} * ({1} * DistributionPriority)) / {0}) WHERE DistributionPriority > 0 AND AdPackTypeId = {2}", MaxMultiplier, amount.ToClearString(), AdPackTypeId); //Update all member balances string MemberBalanceUpdateCommand = String.Format(@" WITH CTE AS ( SELECT P.UserId AS userId, SUM(FLOOR({0} * ({1} * DistributionPriority)) / {0}) AS amount FROM AdPacks P WHERE DistributionPriority > 0 AND AdPackTypeId = {4} GROUP BY P.UserId ) UPDATE Users SET Users.Balance3 = Users.Balance3 + {3}, Users.Balance1 = Users.Balance1 + ({2} - {3}) * (1 - {5}), Users.MarketplaceBalance = Users.MarketplaceBalance + ({2} - {3}) * {5}, Users.TotalEarned = Users.TotalEarned + ({2} - {3}) * (1 - {5}), Users.StatsEarned = cast(({2}+CONVERT(decimal(19,8),(CAST(SUBSTRING(Users.StatsEarned,0, CHARINDEX('#', Users.StatsEarned)) AS varchar(30))))) as varchar(1000)) + SUBSTRING(Users.StatsEarned,CHARINDEX('#', Users.StatsEarned), 1000), Users.StatsRevShareCurrentWeekIncome = Users.StatsRevShareCurrentWeekIncome + {2}, Users.StatsRevShareCurrentMonthIncome = Users.StatsRevShareCurrentMonthIncome + {2} WHERE Users.UserId IN (SELECT DISTINCT UserID from CTE)", MaxMultiplier, amount.ToClearString(), AmountToEarn, AmountToRepurchaseBalance(AdPackTypeId), AdPackTypeId, MarketplaceBalanceReturnPercentage(AdPackTypeId)); //BalanceLogs, add fast /MAIN BALANCE/ string dtCommand = String.Format(@" SELECT P.UserId AS userId, (" + AmountCalculated + @" - " + AmountCalculatedForRepurchase(AdPackTypeId) + @") * (1 - " + MarketplaceBalanceReturnPercentage(AdPackTypeId) + @") AS amount, U.Balance1 AS state FROM AdPacks P JOIN Users U ON P.UserID = U.UserID WHERE DistributionPriority > 0 AND AdPackTypeId = " + AdPackTypeId + @" GROUP BY P.UserId, U.Balance1, U.UpgradeId", amount.ToClearString()); //BalanceLogs, add fast /PURCHASE BALANCE/ string dtCommandAdBalance = String.Format(@" SELECT P.UserId AS userId, " + AmountCalculatedForRepurchase(AdPackTypeId) + @" AS amount, U.Balance3 AS state FROM AdPacks P JOIN Users U ON P.UserID = U.UserID WHERE DistributionPriority > 0 AND AdPackTypeId = " + AdPackTypeId + @" GROUP BY P.UserId, U.Balance3, U.UpgradeId", amount.ToClearString()); string dtCommandMarketplaceBalance = String.Format(@" SELECT P.UserId AS userId, (" + AmountCalculated + @" - " + AmountCalculatedForRepurchase(AdPackTypeId) + @") * " + MarketplaceBalanceReturnPercentage(AdPackTypeId) + @" AS amount, U.MarketplaceBalance AS state FROM AdPacks P JOIN Users U ON P.UserID = U.UserID WHERE DistributionPriority > 0 AND AdPackTypeId = " + AdPackTypeId + @" GROUP BY P.UserId, U.MarketplaceBalance, U.UpgradeId", amount.ToClearString()); parser.ExecuteRawCommandNonQuery(MemberBalanceUpdateCommand); BalanceLogManager.AddRange(parser, dtCommand, AppSettings.RevShare.AdPack.AdPackName + " revenue", BalanceType.MainBalance, BalanceLogType.AdPackROI); BalanceLogManager.AddRange(parser, dtCommandAdBalance, AppSettings.RevShare.AdPack.AdPackName + " revenue", BalanceType.PurchaseBalance, BalanceLogType.AdPackROI); if (AppSettings.Payments.MarketplaceBalanceEnabled) { BalanceLogManager.AddRange(parser, dtCommandMarketplaceBalance, AppSettings.RevShare.AdPack.AdPackName + " revenue", BalanceType.MarketplaceBalance, BalanceLogType.AdPackROI); } parser.ExecuteRawCommandNonQuery(AdPacksUpdateCommnad); //How much distributed string selectDistributionAmount = String.Format(@" SELECT SUM(FLOOR({0} * ({1} * DistributionPriority)) / {0}) FROM AdPacks WHERE DistributionPriority > 0 AND AdPackTypeId = {2}", MaxMultiplier, amount.ToClearString(), AdPackTypeId); object result = parser.ExecuteRawCommandScalar(selectDistributionAmount); if (result is DBNull) { return(Money.Zero); } return(Money.Parse(result.ToString())); }