Exemple #1
0
 public static List<IFundPosition> GetPositions(IDalSession session, int accountId, PositionsView view)
 {
     List<ICriterion> expressions = new List<ICriterion>();
     expressions.Add(Expression.Eq("Account.Key", accountId));
     addPositionsViewCriterion(expressions, view);
     return session.GetTypedList<FundPosition, IFundPosition>(expressions);
 }
Exemple #2
0
 public static IList<IAccountFamily> GetAccountFamilies(IDalSession session, IAssetManager assetManager)
 {
     List<ICriterion> expressions = new List<ICriterion>();
     if (!assetManager.IsStichting)
         expressions.Add(Expression.Eq("AssetManager.Key", assetManager.Key));
     return session.GetTypedList<AccountFamily,IAccountFamily>(expressions);
 }
Exemple #3
0
 /// <summary>
 /// This method retrieves a list of Position instances that belong to a specific account and meet the PositionsView criterium. 
 /// </summary>
 /// <param name="session">An instance of the Data Access Library <see cref="T:B4F.TotalGiro.DAL.NHSession">NHSession</see> class</param>
 /// <param name="account">The account the positions belong to</param>
 /// <param name="view">Determines which positions to show (zero side, non zero sized or all)</param>
 /// <returns>A list of position instances</returns>
 public static List<IFundPosition> GetPositions(IDalSession session, IAccountTypeInternal account, PositionsView view)
 {
     if (account != null)
         return GetPositions(session, account.Key, view);
     else
         return new List<IFundPosition>();
 }
        /// <summary>
        /// Discover at run time the appropriate set of Parameters for a stored procedure
        /// </summary>
		/// <param name="session">An IDalSession object</param>
		/// <param name="spName">Name of the stored procedure.</param>
        /// <param name="includeReturnValueParameter">if set to <c>true</c> [include return value parameter].</param>
        /// <returns>The stored procedure parameters.</returns>
		private IDataParameter[] InternalDiscoverSpParameterSet(IDalSession session, string spName, 
            bool includeReturnValueParameter)
		{
			using (IDbCommand cmd = session.CreateCommand(CommandType.StoredProcedure))
			{
				cmd.CommandText = spName;

			    // The session connection object is always created but the connection is not alwys open
			    // so we try to open it in case.
				session.OpenConnection();

				DeriveParameters(session.DataSource.DbProvider, cmd);

				if (cmd.Parameters.Count > 0) {
					IDataParameter firstParameter = (IDataParameter)cmd.Parameters[0];
					if (firstParameter.Direction == ParameterDirection.ReturnValue) {
						if (!includeReturnValueParameter) {
							cmd.Parameters.RemoveAt(0);
						}
					}	
				}


				IDataParameter[] discoveredParameters = new IDataParameter[cmd.Parameters.Count];
				cmd.Parameters.CopyTo(discoveredParameters, 0);
				return discoveredParameters;
			}
		}
Exemple #5
0
 public static IGLLookupRecords GetGLLookupRecords(IDalSession session, BookingComponentParentTypes bookingComponentParentType)
 {
     List<ICriterion> expressions = new List<ICriterion>();
     expressions.Add(Expression.Eq("BookingComponentParentType", bookingComponentParentType));
     IList<IGLLookupRecord> gLLookupRecords = session.GetTypedList<IGLLookupRecord>();
     return new GLLookupRecords(gLLookupRecords);
 }
Exemple #6
0
        /// <summary>
        /// Retrieves a list of all <b>FeeRule</b> objects in the system.
        /// </summary>
        /// <param name="session">An instance of the Data Access Library (see class <see cref="B4F.TotalGiro.DAL.NHSession">NHSession</see>).</param>
        /// <returns>A list of all <b>CommRule</b> objects in the system.</returns>
        public static IList<IFeeRule> GetFeeRules(IDalSession session,
            int feeCalcId, int modelId, int accountId, int startPeriod, int endPeriod,
            bool isDefault, bool hasEmployerRelation, bool executionOnly, bool sendByPost)
        {
            Hashtable parameters = new Hashtable();

            IManagementCompany company = LoginMapper.GetCurrentManagmentCompany(session);
            if (!company.IsStichting)
                parameters.Add("companyId", company.Key);
            if (feeCalcId != 0 && (int)feeCalcId != int.MinValue)
                parameters.Add("feeCalcId", feeCalcId);
            if (accountId != 0 && accountId != int.MinValue)
                parameters.Add("accountId", accountId);
            if (modelId != 0 && modelId != int.MinValue)
                parameters.Add("modelId", modelId);
            if (startPeriod != 0)
                parameters.Add("startPeriod", startPeriod);
            if (endPeriod != 0)
                parameters.Add("endPeriod", endPeriod);
            if (isDefault)
                parameters.Add("isDefault", isDefault);
            if (hasEmployerRelation)
                parameters.Add("hasEmployerRelation", hasEmployerRelation);
            if (executionOnly)
                parameters.Add("executionOnly", executionOnly);
            if (sendByPost)
                parameters.Add("sendByPost", sendByPost);

            return session.GetTypedListByNamedQuery<IFeeRule>(
                "B4F.TotalGiro.Fees.FeeRules.GetFeeRules",
                parameters);
        }
		/// <summary>
		/// Resolve at run time the appropriate set of Parameters for a stored procedure
		/// </summary>
		/// <param name="session">An IDalSession object</param>
		/// <param name="spName">the name of the stored procedure</param>
		/// <param name="includeReturnValueParameter">whether or not to include their return value parameter</param>
		/// <returns></returns>
		private IDataParameter[] DiscoverSpParameterSet(IDalSession session, string spName, bool includeReturnValueParameter)
		{
			return InternalDiscoverSpParameterSet(
                session,
                spName, 
                includeReturnValueParameter);	
		}
Exemple #8
0
        public static IList GetAverageHoldings(IDalSession session, IAccountTypeInternal account, DateTime startDate, DateTime endDate, ValuationTypesFilterOptions filterOption)
        {
            Hashtable parameters = new Hashtable(1);
            parameters.Add("account", account);
            parameters.Add("startDate", startDate);
            parameters.Add("endDate", endDate);
            string instrumentFilter = "";

            switch (filterOption)
            {
                case ValuationTypesFilterOptions.Security:
                    instrumentFilter = "and I.Key in (select S.Key from TradeableInstrument S) ";
                    break;
                case ValuationTypesFilterOptions.Monetary:
                    instrumentFilter = "and I.Key in (select C.Key from Currency C) ";
                    break;
            }

            string hql = string.Format(@"from AverageHolding A
                left join fetch A.Instrument I
                where A.Account = :account
                and (A.BeginDate between :startDate
                and :endDate ) {0}
                order by I.Key, A.BeginDate", instrumentFilter);
            return session.GetListByHQL(hql, parameters);
        }
Exemple #9
0
 /// <summary>
 /// Gets the Positions for the ExtCustodian for the specified date
 /// </summary>
 /// <param name="session">Data session object</param>
 /// <param name="custodian">The specified ExtCustodians</param>
 /// <param name="balanceDate">The specified date</param>
 /// <returns>A list ExtCustodian Positions</returns>
 public static IList GetExtCustodianPositions(IDalSession session, ExtCustodian custodian, DateTime balanceDate)
 {
     List<NHibernate.Criterion.ICriterion> expressions = new List<NHibernate.Criterion.ICriterion>();
     expressions.Add(NHibernate.Criterion.Expression.Eq("Custodian.Key", custodian.Key));
     expressions.Add(NHibernate.Criterion.Expression.Eq("BalanceDate", balanceDate));
     return session.GetList(typeof(ExtPosition), expressions);
 }
Exemple #10
0
        /// <summary>
        /// This method retrieves a list of counter account instances that meet the passed in arguments. 
        /// When an argument is ommitted it is not used to filter the counter accounts
        /// </summary>
        /// <param name="session">An instance of the Data Access Library <see cref="T:B4F.TotalGiro.DAL.NHSession">NHSession</see> class</param>
        /// <param name="assetManager">The asset manager the customer belongs to</param>
        /// <param name="counterAccountNumber">Number of the counter account</param>
        /// <param name="counterAccountName">Name of the counter account</param>
        /// <param name="contactName">The name of the contact</param>
        /// <param name="accountNumber">The account's number of the account</param>
        /// <param name="showActive">Show for active contacts</param>
        /// <param name="showInactive">Show for inactive contacts</param>
        /// <param name="isPublic">Show public contacts</param>
        /// <returns>A list of counter account instances</returns>
        public static IList<ICounterAccount> GetCounterAccounts(IDalSession session, IAssetManager assetManager,
            string counterAccountNumber, string counterAccountName, 
            string contactName, string accountNumber, bool showActive, 
            bool showInactive, bool isPublic)
        {
            Hashtable parameters = new Hashtable();

            if (assetManager != null)
                parameters.Add("managementCompanyId", assetManager.Key);
            if (counterAccountNumber != null && counterAccountNumber.Length > 0)
                parameters.Add("counterAccountNumber", Util.PrepareNamedParameterWithWildcard(counterAccountNumber, MatchModes.Anywhere));
            if (counterAccountName != null && counterAccountName.Length > 0)
                parameters.Add("counterAccountName", Util.PrepareNamedParameterWithWildcard(counterAccountName, MatchModes.Anywhere));
            if (contactName != null && contactName.Length > 0)
                parameters.Add("contactName", Util.PrepareNamedParameterWithWildcard(contactName, MatchModes.Anywhere));
            parameters.Add("isPublic", isPublic);
            if (showActive && !showInactive)
                parameters.Add("isActive", true);
            if (!showActive && showInactive)
                parameters.Add("isActive", false);

            if (accountNumber != null && accountNumber.Length > 0)
                parameters.Add("accountNumber", Util.PrepareNamedParameterWithWildcard(accountNumber, MatchModes.Anywhere));

            return session.GetTypedListByNamedQuery<ICounterAccount>(
                "B4F.TotalGiro.Accounts.CounterAccount.GetCounterAccounts",
                parameters);
        }
 /// <summary>
 /// Check whether the rate is within the range
 /// </summary>
 /// <param name="session"></param>
 /// <param name="checkRate"></param>
 /// <returns></returns>
 public static bool CheckHistoricalExRate(IDalSession session, IHistoricalExRate checkRate, out string errMessage)
 {
     bool success = true;
     errMessage = "";
     if (checkRate != null)
     {
         IList<IHistoricalExRate> previousRates = GetHistoricalExRates(session,
             checkRate.Currency, checkRate.RateDate.AddDays(-5),
             checkRate.RateDate.AddDays(-1));
         if (previousRates != null && previousRates.Count > 0)
         {
             decimal prevRate = previousRates.OrderByDescending(x => x.RateDate).FirstOrDefault().Rate;
             if (prevRate != 0M)
             {
                 decimal diff = Math.Abs((prevRate - checkRate.Rate) / prevRate);
                 if (diff > 0.05M)
                 {
                     errMessage = string.Format("The new Exchange Rate is {0}% different from the previous Exchange Rate.", (diff * 100).ToString("0.0"));
                     success = false;
                 }
             }
         }
     }
     return success;
 }
Exemple #12
0
        /// <summary>
        /// Check whether the price is within the range
        /// </summary>
        /// <param name="session"></param>
        /// <param name="checkPrice"></param>
        /// <returns></returns>
        public static bool CheckHistoricalPrice(IDalSession session, IHistoricalPrice checkPrice, out string errMessage)
        {
            bool success = true;
            errMessage = "";
            if (checkPrice != null)
            {
                IList<IHistoricalPrice> previousPrices = GetHistoricalPrices(session,
                    checkPrice.Instrument.Key, checkPrice.Date.AddDays(-5),
                    checkPrice.Date.AddDays(-1));
                if (previousPrices != null && previousPrices.Count > 0)
                {
                    Price prevPrice = previousPrices.OrderByDescending(x => x.Date).FirstOrDefault().Price;
                    if (prevPrice == null) prevPrice = checkPrice.Instrument.Get(e => e.CurrentPrice).Get(e => e.Price);

                    if (prevPrice != null)
                    {
                        decimal diff = Math.Abs((prevPrice.Quantity - checkPrice.Price.Quantity) / prevPrice.Quantity);
                        if (diff > 0.05M)
                        {
                            errMessage = string.Format("The new Price is {0}% different from the previous price.", (diff * 100).ToString("0.0"));
                            success = false;
                        }
                    }
                }
            }
            return success;
        }
Exemple #13
0
 public static IList<IGLAccount> GetClientBalanceGLAccounts(IDalSession session)
 {
     List<ICriterion> expressions = new List<ICriterion>();
     expressions.Add(Expression.Eq("IsClientOpenBalance", true));
     IList<IGLAccount> list = session.GetTypedList<GLAccount, IGLAccount>(expressions);
     return list;
 }
        public static void AdjustFixedAccountLine(IDalSession session, IJournalEntry journalEntry)
        {
            try
            {
                if (journalEntry.Status == JournalEntryStati.New && journalEntry.Journal.FixedGLAccount != null)
                {
                    IJournalEntryLine fixedAccountLine = journalEntry.Lines.FixedAccountLine;
                    Money balance = journalEntry.Balance;

                    if (balance.IsNotZero)
                    {
                        if (fixedAccountLine == null)
                        {
                            fixedAccountLine = new JournalEntryLine();
                            fixedAccountLine.GLAccount = journalEntry.Journal.FixedGLAccount;

                            journalEntry.Lines.AddJournalEntryLine(fixedAccountLine);
                            fixedAccountLine.LineNumber = 0;
                        }

                        fixedAccountLine.Balance = balance.Negate();

                        JournalEntryMapper.Update(session, journalEntry);
                    }
                    else if (fixedAccountLine != null)
                        deleteLine(session, fixedAccountLine);
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Could not adjust Fixed-Account Line.", ex);
            }
        }
Exemple #15
0
 public static List<ICashPosition> GetPositions(IDalSession session, IAccountTypeInternal account, PositionsView view)
 {
     List<ICriterion> expressions = new List<ICriterion>();
     expressions.Add(Expression.Eq("Account.Key", account.Key));
     addPositionsViewCriterion(expressions, view);
     return session.GetTypedList<CashPosition, ICashPosition>(expressions);
 }
Exemple #16
0
        //public static IList GetUnprintedNotas(IDalSession session)
        //{
        //    List<ICriterion> expressions = new List<ICriterion>();
        //    expressions.Add(Expression.Eq("PrintCount", 0));
        //    return session.GetList(typeof(Nota), expressions);
        //}
        //        public static List<IManagementCompany> GetMgmtCompaniesWithUnprintedNotas(IDalSession session,
        //                                                                                  NotaReturnClass returnClass, int[] managementCompanyIds)
        //        {
        //            string hql = string.Format(@"FROM ManagementCompany M WHERE M IN
        //                                            (SELECT A.AccountOwner FROM CustomerAccount A WHERE A IN
        //                                                (SELECT N.UnderlyingTx.AccountA FROM {0} N WHERE N.PrintCount = 0))",
        //                                       getType(returnClass).Name);
        //            if (managementCompanyIds != null && managementCompanyIds.Length > 0)
        //            {
        //                string idList = "";
        //                for (int i = 0; i < managementCompanyIds.Length; i++)
        //                    idList += (i > 0 ? ", " : "") + managementCompanyIds[i].ToString();
        //                hql += string.Format(" AND M IN ({0})", idList);
        //            }
        //            return NHSession.ToList<IManagementCompany>(session.GetListByHQL(hql, new Hashtable()));
        //        }
        public static int[] GetAccountsIdsWithUnprintedNotas(IDalSession session, int managementCompanyId, NotaReturnClass returnClass)
        {
            Hashtable parameters = new Hashtable();
            parameters.Add("ManagementCompanyId", managementCompanyId);
            string underlyingAccObj = "";
            switch (returnClass)
            {
                case NotaReturnClass.NotaTransaction:
                case NotaReturnClass.NotaTransfer:
                case NotaReturnClass.NotaInstrumentConversion:
                    underlyingAccObj = "UnderlyingTx.AccountA";
                    break;
                default:
                    underlyingAccObj = "UnderlyingBooking.Account";
                    break;
            }

            ArrayList accountIds = (ArrayList)session.GetListByHQL(
                string.Format(@"SELECT A.Key FROM CustomerAccount A
                                WHERE A.Key IN (SELECT N.{0}.Key FROM {1} N WHERE N.PrintCount = 0)
                                AND A.AccountOwner.Key = :ManagementCompanyId
                                ORDER BY A.Number",
                                underlyingAccObj,
                                getType(returnClass).Name),
                                parameters);
            return (int[])accountIds.ToArray(typeof(int));
        }
        public static IImportedBankBalance GetImportedBankBalance(IDalSession session, IJournal bankJournal, DateTime bookBalanceDate)
        {
            Hashtable parameters = new Hashtable();
            parameters.Add("BankJournalKey", bankJournal.Key);
            parameters.Add("BookBalanceDate", bookBalanceDate);

            string hql = @"from ImportedBankBalance I
                            where I.BankJournal.Key = :BankJournalKey
                            and I.BookBalanceDate = :BookBalanceDate";

            IList result = session.GetListByHQL(hql, parameters);
            if (result != null && result.Count == 1)
                return (ImportedBankBalance)result[0];
            else
                return null;

            //List<ICriterion> expressions = new List<ICriterion>();
            //expressions.Add(Expression.Eq("BankJournal.Key", bankJournal.Key));
            //expressions.Add(Expression.Eq("BookBalanceDate", bookBalanceDate));
            //IList result = session.GetList(typeof(ImportedBankBalance), expressions);
            //if (result != null && result.Count == 1)
            //    return (IImportedBankBalance)result[0];
            //else
            //    return null;
        }
 protected override void BeforeDataSetBuild(IDalSession session, INota[] notaGroup)
 {
     foreach (INotaDeposit nota in notaGroup)
         if (nota.IsWithdrawalPeriodic && (nota.TegenrekeningNumber == null || nota.TegenrekeningNumber == string.Empty))
             throw new ApplicationException(
                 "Periodic Withdrawal Nota cannot be printed because Tegenrekening Number is missing on the Cash Transfer.");
 }
        private static bool CreateManagementFeeBookingsforDate(IDalSession session, IList listofFees,
            IMemorialBooking feeBookings, IGLAccount clientTaxAccount, IGLAccount clientFeeAccount,
            IGLAccount clientFixedCostsAccount, IGLAccount taxAccount)
        {
            //foreach (IManagementFee imf in listofFees)
            //{
            //    foreach (MgtFeeBreakupLine line in imf.FeeDetails.BreakupLines)
            //    {
            //        if (line.Amount.IsNotZero)
            //        {
            //            IAccountTypeInternal account = line.Transaction.AccountA;
            //            IJournalEntryLine newLineClient = new JournalEntryLine();
            //            IJournalEntryLine newLineCP = new JournalEntryLine();
            //            IJournalEntryLine newLineClientTax = new JournalEntryLine();
            //            IJournalEntryLine newLineCPTax = new JournalEntryLine();

            //            switch (line.MgtFeeType.Key)
            //            {
            //                case FeeTypes.AdministrationCosts:
            //                case FeeTypes.FixedFee:
            //                    newLineClient.GLAccount = clientFixedCostsAccount;
            //                    newLineCP.GLAccount = account.AccountOwner.ManagementFeeFixedCostsAccount;
            //                    break;
            //                default:
            //                    newLineClient.GLAccount = clientFeeAccount;
            //                    newLineCP.GLAccount = account.AccountOwner.ManagementFeeIncomeAccount;
            //                    break;
            //            }

            //            newLineClientTax.GLAccount = clientTaxAccount;
            //            newLineCPTax.GLAccount = taxAccount;

            //            newLineClient.Balance = line.Amount;
            //            newLineCP.Balance = line.Amount.Negate();
            //            if ((line.Tax != null) && (line.Tax.IsNotZero))
            //            {
            //                newLineClientTax.Balance = line.Tax;
            //                newLineCPTax.Balance = line.Tax.Negate();
            //            }

            //            newLineClient.GiroAccount = account;
            //            newLineClientTax.GiroAccount = account;

            //            newLineClient.TotalGiroTrade = line.Transaction;
            //            newLineCP.TotalGiroTrade = line.Transaction;
            //            newLineClientTax.TotalGiroTrade = line.Transaction;
            //            newLineCPTax.TotalGiroTrade = line.Transaction;

            //            feeBookings.Lines.Add(newLineClient);
            //            feeBookings.Lines.Add(newLineCP);
            //            feeBookings.Lines.Add(newLineClientTax);
            //            feeBookings.Lines.Add(newLineCPTax);

            //        }
            //    }
            //}

            return true;
        }
Exemple #20
0
 public static IList<IJournal> GetJournals(IDalSession session, JournalTypes journalType)
 {
     List<ICriterion> expressions = new List<ICriterion>();
     List<Order> orderings = new List<Order>();
     expressions.Add(Expression.Eq("JournalType", journalType));
     orderings.Add(Order.Asc("JournalNumber"));
     return session.GetTypedList<Journal, IJournal>(expressions, orderings);
 }
Exemple #21
0
 public static List<IFundPosition> GetPositions(IDalSession session, IInstrument instrument, PositionsView view)
 {
     List<ICriterion> expressions = new List<ICriterion>();
     expressions.Add(Expression.Eq("Size.Underlying.Key", instrument.Key));
     addPositionsViewCriterion(expressions, view);
     LoginMapper.GetSecurityInfo(session, expressions, SecurityInfoOptions.NoFilter);
     return session.GetTypedList<FundPosition, IFundPosition>(expressions);
 }
Exemple #22
0
 /// <summary>
 /// Retrieves a list of all <b>FeeRule</b> objects in the system.
 /// </summary>
 /// <param name="session">An instance of the Data Access Library (see class <see cref="B4F.TotalGiro.DAL.NHSession">NHSession</see>).</param>
 /// <returns>A list of all <b>FeeRule</b> objects in the system.</returns>
 public static IList GetFeeRules(IDalSession session)
 {
     List<ICriterion> expressions = new List<ICriterion>();
     IManagementCompany company = LoginMapper.GetCurrentManagmentCompany(session);
     if (!company.IsStichting)
         expressions.Add(Expression.Eq("AssetManager.Key", company.Key));
     return session.GetList(typeof(FeeRule), expressions);
 }
 public static IPortfolioHistorical GetHistoricalPortfolio(IDalSession session, IAccountTypeInternal account,
     DateTime positionDate, IList<IHistoricalPrice> prices, IList<IHistoricalExRate> rates)
 {
     IList<IFundPositionTx> posTx = FundPositionMapper.GetPositionTransactionsByDate(session, account, positionDate);
     IList<IJournalEntryLine> lines = JournalEntryMapper.GetSettledBookingsForAccountUntilDate(session, positionDate, account.Key);
     IPortfolioHistorical portfolio = new PortfolioHistorical(account, positionDate, posTx, prices, rates, lines);
     return portfolio;
 }
Exemple #24
0
 public DataSet BuildTestDataSet(IDalSession session, int contactId)
 {
     IContact contact = ContactMapper.GetContact(session, contactId);
     if (contact != null)
         return buildDataSet(new CustomerLoginPerson(contact));
     else
         throw new ArgumentException(string.Format("{0} is not a valid ContactID.", contactId));
 }
 public static IEffectenGiro GetEffectenGiroCompany(IDalSession session)
 {
     IList list = session.GetList(typeof(EffectenGiro));
     if (list.Count == 1)
         return (IEffectenGiro)list[0];
     else
         throw new ApplicationException("There should be exactly one EffectenGiro company in the system.");
 }
Exemple #26
0
 /// <summary>
 /// Retrieves a list of all <b>CommRule</b> objects in the system.
 /// </summary>
 /// <param name="session">An instance of the Data Access Library (see class <see cref="B4F.TotalGiro.DAL.NHSession">NHSession</see>).</param>
 /// <param name="company">The company that owns these rules.</param>
 /// <returns>A list of all <b>CommRule</b> objects in the system.</returns>
 public static IList<ICommRule> GetCommissionRules(IDalSession session)
 {
     List<ICriterion> expressions = new List<ICriterion>();
     IManagementCompany company = LoginMapper.GetCurrentManagmentCompany(session);
     if (!company.IsStichting)
         expressions.Add(Expression.Eq("AssetManager.Key", company.Key));
     return session.GetTypedList<CommRule, ICommRule>(expressions);
 }
Exemple #27
0
 public static IInstrumentSymbol GetSymbol(IDalSession session, ITradeableInstrument Instrument, IExternalInterface externalInterface)
 {
     List<ICriterion> expressions = new List<ICriterion>();
     expressions.Add(Expression.Eq("Instrument.Key", Instrument.Key));
     expressions.Add(Expression.Eq("ExternalInterface", externalInterface));
     IList result = session.GetList(typeof(InstrumentSymbol), expressions);
     return (result.Count > 0) ? (IInstrumentSymbol)result[0] : null;
 }
Exemple #28
0
 public static IList GetAccountCategories(IDalSession session, IAssetManager am)
 {
     List<ICriterion> expressions = new List<ICriterion>();
     expressions.Add(Expression.Eq("AssetManager.Key", am.Key));
     List<Order> orderings = new List<Order>();
     orderings.Add(Order.Asc("CustomerType"));
     return session.GetList(typeof(AccountCategory), expressions, orderings, null, null);
 }
Exemple #29
0
 public static IList<IModelComponent> GetModelComponentsLatestVersion(IDalSession session, int modelID)
 {
     Hashtable parameters = new Hashtable();
     parameters.Add("modelID", modelID);
     return session.GetTypedListByNamedQuery<IModelComponent>(
         "B4F.TotalGiro.Instruments.ModelComponent.GetModelComponentsLatestVersion",
         parameters);
 }
Exemple #30
0
 public static IList GetAccountCommissionRules(IDalSession session, int accountID)
 {
     Hashtable parameters = new Hashtable(1);
     parameters.Add("accountID", accountID);
     return session.GetListByNamedQuery(
         "B4F.TotalGiro.Fees.CommRules.AccountCommissionRules",
         parameters);
 }
Exemple #31
0
        /// <summary>
        /// Store the specified session.
        /// </summary>
        /// <param name="session">The session to store</param>
        public override void Store(IDalSession session)
        {
            HttpContext currentContext = HttpContext.Current;

            if (currentContext == null)
            {
                CallContext.SetData(sessionName, session);
            }
            else
            {
                currentContext.Items[sessionName] = session;
            }
        }
Exemple #32
0
        public void Exportar(IDalSession session, EnAcao enAcao, string dataInicial, string dataFinal, int id = 0)
        {
            if (enAcao == EnAcao.EXPORTAR)
            {
                session.ServicoPedido.Exportar(dataInicial, dataFinal);
                session.ServicoPedidoItem.Exportar(dataInicial, dataFinal);
            }

            if (enAcao == EnAcao.EXCLUIR)
            {
                session.ServicoPedido.ExcluirNet(id);
            }
        }
Exemple #33
0
 public void Insert(Order order)
 {
     using (IDalSession session = Mapper.Instance().BeginTransaction())
     {
         Mapper.Instance().Insert("Order-Insert", order);
         foreach (OrderProduct orderProduct in order.OrderProducts)
         {
             orderProduct.OrderID = order.ID;
             Mapper.Instance().Insert("OrderProduct-Insert", orderProduct);
         }
         session.Complete();
     }
 }
Exemple #34
0
        private void Iniciar()
        {
            InitializeComponent();

            tabControl1.TabPages.Remove(tpEditar);
            tabControl1.TabPages.Remove(tpFiltro);
            _session = SessionFactory.Criar();

            Geral.Grade.Config(dgvDados);

            _model = new Contato();
            CarregarConsulta();
        }
Exemple #35
0
        private async Task <int> UpdateExistingArticle(Article entity, IDalSession dalSession)
        {
            var parameter = new DynamicParameters();

            parameter.Add("@ArticleId", entity.ArticleId);
            parameter.Add("@ArticleTitle", entity.Title);
            parameter.Add("@ArticleBody", entity.Body);
            parameter.Add("@IsPublished", entity.IsPublished);
            parameter.Add("@ArticleHeroImagePath", entity.HeroImagePath);
            parameter.Add("@ArticleBodyImagePath", entity.BodyImagePath);

            return(await dalSession.UnitOfWork.RepositoryConnection.Connection.ExecuteScalarAsync <int>("UpdateArticle", parameter, transaction : dalSession.UnitOfWork.Transaction, commandType : CommandType.StoredProcedure));
        }
Exemple #36
0
        /// <summary>
        /// Discover at run time the appropriate set of Parameters for a stored procedure
        /// </summary>
        /// <param name="session">An IDalSession object</param>
        /// <param name="spName">Name of the stored procedure.</param>
        /// <param name="includeReturnValueParameter">if set to <c>true</c> [include return value parameter].</param>
        /// <returns>The stored procedure parameters.</returns>
        private IDataParameter[] InternalDiscoverSpParameterSet(IDalSession session, string spName,
                                                                bool includeReturnValueParameter)
        {
            //#if !dotnet2
            // SqlCommandBuilder.DeriveParameters(<command>) does not support transactions.
            // If the command is within a transaction, you will get the following error:
            // SqlCommandBuilder Execute requires the command to have a transaction object
            // when the connection assigned to the command is in a pending local transaction?
            // even when the command object does in fact have a transaction object.
            using (IDbConnection connection = session.DataSource.DbProvider.CreateConnection())
            {
                connection.ConnectionString = session.DataSource.ConnectionString;
                connection.Open();
                using (IDbCommand cmd = connection.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    //#else
                    //				using (IDbCommand cmd = session.CreateCommand(CommandType.StoredProcedure))
                    //				{
                    //#endif
                    cmd.CommandText = spName;

                    // The session connection object is always created but the connection is not alwys open
                    // so we try to open it in case.
                    session.OpenConnection();

                    DeriveParameters(session.DataSource.DbProvider, cmd);

                    if (cmd.Parameters.Count > 0)
                    {
                        IDataParameter firstParameter = (IDataParameter)cmd.Parameters[0];
                        if (firstParameter.Direction == ParameterDirection.ReturnValue)
                        {
                            if (!includeReturnValueParameter)
                            {
                                cmd.Parameters.RemoveAt(0);
                            }
                        }
                    }


                    IDataParameter[] discoveredParameters = new IDataParameter[cmd.Parameters.Count];
                    cmd.Parameters.CopyTo(discoveredParameters, 0);
                    return(discoveredParameters);
                }
                //#if !dotnet2
            }
            //#endif
        }
Exemple #37
0
        /// <summary>
        /// 通用的以DataTable的方式得到Select的结果(xml文件中参数要使用$标记的占位参数,注:不支持#变量替换)
        /// </summary>
        /// <param name="statementName">语句ID</param>
        /// <param name="paramObject">语句所需要的参数</param>
        /// <param name="htOutPutParameter">Output参数值哈希表</param>
        /// <returns>得到的DataTable</returns>
        public static DataTable ExecuteQueryForDataTable(string statementName, object paramObject, out Hashtable htOutPutParameter)
        {
            ISqlMapper  sqlMap         = Mapper();
            DataSet     ds             = new DataSet();
            bool        isSessionLocal = false;
            IDalSession session        = sqlMap.LocalSession;

            if (session == null)
            {
                session = new SqlMapSession(sqlMap);
                session.OpenConnection();
                isSessionLocal = true;
            }

            IDbCommand cmd = GetCommand(statementName, paramObject);

            cmd.CommandTimeout = 0;

            try
            {
                cmd.Connection = session.Connection;
                IDbDataAdapter adapter = session.CreateDataAdapter(cmd);
                adapter.Fill(ds);
            }
            catch (Exception e)
            {
                throw new DataMapperException("Error executing query '" + statementName + "' for object.  Cause: " + e.Message, e);
            }
            finally
            {
                if (isSessionLocal)
                {
                    session.CloseConnection();
                }
            }

            htOutPutParameter = new Hashtable();
            foreach (IDataParameter parameter in cmd.Parameters)
            {
                if (parameter.Direction == ParameterDirection.Output)
                {
                    htOutPutParameter[parameter.ParameterName] = parameter.Value;
                }
            }


            return(ds.Tables[0]);
        }
Exemple #38
0
        public void Exportar(IDalSession session, EnAcao enAcao, int id = 0)
        {

            try
            {
                if (enAcao == EnAcao.EXPORTAR)
                    session.ServicoGrupo.ExportNetAsync();
                if (enAcao == EnAcao.EXCLUIR)
                    session.ServicoGrupo.ExcluirNet(id);
            }
            catch (System.Exception ex)
            {

                throw new System.Exception(ex.Message);
            }
        }
Exemple #39
0
        /// <summary>
        /// Open a connection, on the specified connection string.
        /// </summary>
        /// <param name="connectionString">The connection string</param>
        public IDalSession OpenConnection(string connectionString)
        {
            if (_daoSessionHandler == null)
            {
                throw new DataAccessException("DaoManager could not get DaoSession.  DaoSessionPool was null (possibly not configured).");
            }
            if (_sessionStore.LocalSession != null)
            {
                throw new DataAccessException("DaoManager could not invoke OpenConnection(). A connection is already started. Call CloseConnection first.");
            }
            IDalSession session = _daoSessionHandler.GetDaoSession(this);

            _sessionStore.Store(session);
            session.OpenConnection(connectionString);
            return(session);
        }
Exemple #40
0
        /// <summary>
        /// Begins a database transaction.
        /// </summary>
        /// <returns>A IDalSession</returns>
        public IDalSession BeginTransaction()
        {
            if (_daoSessionHandler == null)
            {
                throw new DataAccessException("DaoManager could not get DaoSession.  DaoSessionPool was null (possibly not configured).");
            }
            if (_sessionStore.LocalSession != null)
            {
                throw new DataAccessException("DaoManager could not invoke BeginTransaction(). A DaoSession is already started. Call CommitTransaction() or RollbackTransaction first.");
            }
            IDalSession session = _daoSessionHandler.GetDaoSession(this);

            _sessionStore.Store(session);
            session.BeginTransaction();
            return(session);
        }
Exemple #41
0
        public void TestUsingTransaction()
        {
            using (IDalSession session = sqlMap.BeginTransaction())
            {
                Account account = (Account)sqlMap.QueryForObject("GetAccountViaColumnName", 1);

                account.EmailAddress = "*****@*****.**";
                sqlMap.Update("UpdateAccountViaParameterMap", account);

                account = sqlMap.QueryForObject("GetAccountViaColumnName", 1) as Account;

                Assert.AreEqual("*****@*****.**", account.EmailAddress);

                session.Complete(); // Commit
            } // compiler will call Dispose on SqlMapSession
        }
Exemple #42
0
 /// <summary>
 /// Rolls back a transaction from a pending state.
 /// </summary>
 /// <remarks>
 /// Close the connection.
 /// </remarks>
 public void RollBackTransaction()
 {
     if (_sessionStore.LocalSession == null)
     {
         throw new DataAccessException("DaoManager could not invoke RollBackTransaction(). No Transaction was started. Call BeginTransaction() first.");
     }
     try
     {
         IDalSession session = _sessionStore.LocalSession;
         session.RollBackTransaction();
     }
     finally
     {
         _sessionStore.Dispose();
     }
 }
Exemple #43
0
        public void TestUsingTransaction()
        {
            IAccountDao accountDao = (IAccountDao)daoManager[typeof(IAccountDao)];

            using (IDalSession session = daoManager.BeginTransaction())
            {
                Account account  = NewAccount();
                Account account2 = accountDao.GetAccountById(1);
                account2.EmailAddress = "*****@*****.**";

                accountDao.Create(account);
                accountDao.Update(account2);

                session.Complete(); // Commit
            }                       // compiler will call Dispose on IDalSession
        }
Exemple #44
0
        /// <summary>
        /// Retrieves the set of IDataParameters appropriate for the stored procedure
        /// </summary>
        /// <remarks>
        /// This method will query the database for this information, and then store it in a cache for future requests.
        /// </remarks>
        /// <param name="session">a valid session</param>
        /// <param name="spName">the name of the stored procedure</param>
        /// <param name="includeReturnValueParameter">a bool value indicating whether the return value parameter should be included in the results</param>
        /// <returns>an array of IDataParameters</returns>
        public IDataParameter[] GetSpParameterSet(IDalSession session,
                                                  string spName, bool includeReturnValueParameter)
        {
            string hashKey = session.DataSource.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter":"");

            IDataParameter[] cachedParameters;

            cachedParameters = (IDataParameter[])_paramCache[hashKey];

            if (cachedParameters == null)
            {
                _paramCache[hashKey] = DiscoverSpParameterSet(session, spName, includeReturnValueParameter);
                cachedParameters     = (IDataParameter[])_paramCache[hashKey];
            }

            return(CloneParameters(cachedParameters));
        }
Exemple #45
0
        private void Iniciar(string texto)
        {
            tabControl1.TabPages.Remove(tpEditar);
            tabControl1.TabPages.Remove(tpFiltro);

            _session = SessionFactory.Criar();

            Geral.Grade.Config(dgvDados);

            _model = new Pessoa();
            PopularCampos();
            if (!string.IsNullOrWhiteSpace(texto))
            {
                CarregarConsulta();
            }
            txtId.Visible = false;
        }
        /// <summary>
        /// 执行事务,返回执行出错的错误信息
        /// </summary>
        /// <param name="SQLlist"></param>
        /// <param name="error">传入接受错误信息的字符串</param>
        /// <returns></returns>
        public bool ExecuteSqlTran(SortedList SQLlist, ref string error)
        {
            bool       b      = true;
            string     strsql = "";
            ISqlMapper mapper = baseDao.getMapper();

            try
            {
                //事务
                using (IDalSession session = mapper.BeginTransaction())
                {
                    //循环
                    foreach (DictionaryEntry myDE in SQLlist)
                    {
                        Hashtable ht = (Hashtable)myDE.Key;
                        if (ht["INSERT"] != null)
                        {
                            strsql = ht["INSERT"].ToString();
                            mapper.Insert(ht["INSERT"].ToString(), myDE.Value);
                        }
                        else if (ht["UPDATE"] != null)
                        {
                            strsql = ht["UPDATE"].ToString();
                            mapper.Update(ht["UPDATE"].ToString(), myDE.Value);
                        }
                        else if (ht["DELETE"] != null)
                        {
                            strsql = ht["DELETE"].ToString();
                            mapper.Delete(ht["DELETE"].ToString(), myDE.Value);
                        }
                    }
                    //提交事务
                    session.Complete();
                }
            }
            catch (Exception e)
            {
                error = e.Message + strsql;
                b     = false;
            }

            return(b);
        }
Exemple #47
0
        /// <summary>
        /// 用的以DataSet的方式得到Select的结果(xml文件中参数要使用$标记的占位参数. 注:不支持#变量替换)
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="paramObject"></param>
        /// <returns></returns>
        public static DataSet ExecuteQueryForDataSet(string statementName, object paramObject)
        {
            ISqlMapper sqlMap = Mapper();
            DataSet    ds     = new DataSet();


            bool        isSessionLocal = false;
            IDalSession session        = sqlMap.LocalSession;

            if (session == null)
            {
                session = new SqlMapSession(sqlMap);
                session.OpenConnection();
                isSessionLocal = true;
            }


            IDbCommand cmd = GetCommand(statementName, paramObject);

            cmd.CommandTimeout = 0;

            try
            {
                cmd.Connection = session.Connection;

                IDbDataAdapter adapter = session.CreateDataAdapter(cmd);
                adapter.Fill(ds);
            }
            catch (Exception e)
            {
                throw new DataMapperException("Error executing query '" + statementName + "' for object.  Cause: " + e.Message, e);
            }
            finally
            {
                if (isSessionLocal)
                {
                    session.CloseConnection();
                }
            }

            return(ds);
        }
Exemple #48
0
 /// <summary>
 /// Close a connection
 /// </summary>
 public void CloseConnection()
 {
     if (_sessionStore.LocalSession == null)
     {
         throw new DataAccessException("DaoManager could not invoke CloseConnection(). No connection was started. Call OpenConnection() first.");
     }
     try
     {
         IDalSession session = _sessionStore.LocalSession;
         session.CloseConnection();
     }
     catch (Exception ex)
     {
         throw new DataAccessException("DaoManager could not CloseConnection(). Cause :" + ex.Message, ex);
     }
     finally
     {
         _sessionStore.Dispose();
     }
 }
Exemple #49
0
        public object runTrans(transFunc func)
        {
            ISqlMapper mapper = baseDao.getMapper();

            object result = null;

            try
            {
                using (IDalSession session = mapper.BeginTransaction())
                {
                    result = func(mapper);
                    session.Complete();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("出错:" + ex.ToString());
            }
            return(result);
        }
Exemple #50
0
 private IDataParameter[] InternalDiscoverSpParameterSet(IDalSession session, string spName, bool includeReturnValueParameter)
 {
     using (IDbCommand command = session.CreateCommand(CommandType.StoredProcedure))
     {
         command.CommandText = spName;
         session.OpenConnection();
         this.DeriveParameters(session.DataSource.DbProvider, command);
         if (command.Parameters.Count > 0)
         {
             IDataParameter parameter = (IDataParameter)command.Parameters[0];
             if ((parameter.Direction == ParameterDirection.ReturnValue) && !includeReturnValueParameter)
             {
                 command.Parameters.RemoveAt(0);
             }
         }
         IDataParameter[] array = new IDataParameter[command.Parameters.Count];
         command.Parameters.CopyTo(array, 0);
         return(array);
     }
 }
Exemple #51
0
        private void Iniciar()
        {
            InitializeComponent();

            tabControl1.TabPages.Remove(tpEditar);
            tabControl1.TabPages.Remove(tpFiltro);

            _session = SessionFactory.Criar();

            Geral.Grade.Config(dgvDados);

            txtNumEncontro.Text = _session.ServiceEncontro.ObterEncontroAtual();
            CarregarConsulta();

            _model = new Encontro();

            if (txtTexto.Text == "ABCDE")
            {
                txtTexto.Text = "";
            }
        }
Exemple #52
0
        public void TestTransaction2()
        {
            ISqlMapper    sqlMapper     = new DomSqlMapBuilder().Configure("IBatisNet.config");
            TestObjectDao testObjectDao = new TestObjectDao(sqlMapper);
            TestObject    object1       = TestObject.NewRandom();

            try
            {
                //using... syntax
                using (IDalSession session = sqlMapper.BeginTransaction())
                {
                    testObjectDao.Insert(object1);
                    testObjectDao.Insert(object1);
                    session.Complete();
                }
            }
            catch { }

            TestObject object2 = testObjectDao.SelectById(object1.Id);

            Assert.IsNull(object2);
        }
Exemple #53
0
        /// <summary>
        /// 用于分页控件使用
        /// </summary>
        /// <param name="tag">语句ID</param>
        /// <param name="paramObject">语句所需要的参数</param>
        /// <param name="PageSize">每页显示数目</param>
        /// <param name="curPage">当前页</param>
        /// <param name="recCount">记录总数</param>
        /// <returns>得到的DataTable</returns>
        public static DataTable QueryForDataTable(string tag, object paramObject, int PageSize, int curPage, out int recCount)
        {
            IDataReader dr             = null;
            bool        isSessionLocal = false;
            string      sql            = QueryForSql(tag, paramObject);
            string      strCount       = "select count(*) " + sql.Substring(sql.ToLower().IndexOf("from"));

            IDalSession session = SqlMap.LocalSession;
            DataTable   dt      = new DataTable();

            if (session == null)
            {
                session = new SqlMapSession(SqlMap);
                session.OpenConnection();
                isSessionLocal = true;
            }
            try
            {
                IDbCommand cmdCount = GetDbCommand(tag, paramObject);
                cmdCount.Connection  = session.Connection;
                cmdCount.CommandText = strCount;
                object count = cmdCount.ExecuteScalar();
                recCount = Convert.ToInt32(count);

                IDbCommand cmd = GetDbCommand(tag, paramObject);
                cmd.Connection = session.Connection;
                dr             = cmd.ExecuteReader();

                dt = QueryForPaging(dr, PageSize, curPage);
            }
            finally
            {
                if (isSessionLocal)
                {
                    session.CloseConnection();
                }
            }
            return(dt);
        }
Exemple #54
0
        public void Usage()
        {
            IWindsorContainer container = CreateConfiguredContainer();

            container.AddFacility("IBatisNet", new IBatisNetFacility());

            SqlMapper sqlMap = container[AbstractIBatisNetTestCase.DATA_MAPPER] as SqlMapper;

            using (IDalSession session = sqlMap.OpenConnection())
            {
                Account account = new Account();
                account.Id           = 99;
                account.EmailAddress = "*****@*****.**";
                account.FirstName    = "Gilles";
                account.LastName     = "Bayon";

                sqlMap.Insert("InsertAccount", account);
                account = null;
                account = sqlMap.QueryForObject("GetAccount", 99) as Account;

                Assert.AreEqual(99, account.Id, "account.Id");
            }
        }
        public void Intercept(IInvocation invocation)
        {
            //if (_logger.IsDebugEnabled)
            //    _logger.Debug("Intercept :" + invocation.Method.Name);

            MethodInfo info = invocation.MethodInvocationTarget;

            if (!info.IsDefined(typeof(TransactionAttribute), true))
            {
                invocation.Proceed();
                return;
            }

            String     key    = ObtainSqlMapKeyFor(info);
            ISqlMapper sqlMap = ObtainSqlMapperFor(key);

            //for nested transaction.
            if (sqlMap.IsSessionStarted)
            {
                invocation.Proceed();
                return;
            }
            //=================================================================

            //if (_logger.IsDebugEnabled)
            //    _logger.Debug("Automatic transaction :" + invocation.Method.Name);

            //=================================================================
            //Use this code will catch exception, application not except this.
            //try
            //{
            //    if (_logger.IsDebugEnabled)
            //        _logger.Debug("BeginTransaction :" + invocation.Method.Name);

            //    sqlMap.BeginTransaction();

            //    invocation.Proceed();

            //    if (_logger.IsDebugEnabled)
            //        _logger.Debug("CommitTransaction :" + invocation.Method.Name);

            //    sqlMap.CommitTransaction();
            //}
            //catch
            //{
            //    if (_logger.IsDebugEnabled)
            //        _logger.Debug("RollBackTransaction :" + invocation.Method.Name);

            //    sqlMap.RollBackTransaction();
            //}
            //finally
            //{
            //    if (_logger.IsDebugEnabled)
            //        _logger.Debug("Close connection on method :" + invocation.Method.Name);

            //    sqlMap.CloseConnection();
            //}
            //=================================================================

            //=================================================================
            //Can't use commented code below, test faild.
            //sqlMap.OpenConnection();
            //try
            //{
            using (IDalSession session = sqlMap.BeginTransaction())
            {
                invocation.Proceed();
                session.Complete();
            }
            //}
            //finally
            //{
            //    if (_logger.IsDebugEnabled)
            //        _logger.Debug("Close connection on method :" + invocation.Method.Name);

            //    sqlMap.CloseConnection();
            //}
            //=================================================================
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="session"></param>
        /// <param name="command"></param>
        /// <param name="request"></param>
        /// <param name="statement"></param>
        /// <param name="parameterObject"></param>
        protected override void ApplyParameterMap
            (IDalSession session, IDbCommand command,
            RequestScope request, IStatement statement, object parameterObject)
        {
            ArrayList properties     = request.PreparedStatement.DbParametersName;
            ArrayList parameters     = request.PreparedStatement.DbParameters;
            object    parameterValue = null;

            int count = properties.Count;

            for (int i = 0; i < count; ++i)
            {
                IDataParameter sqlParameter = (IDataParameter)parameters[i];
                string         propertyName = (string)properties[i];

                if (command.CommandType == CommandType.Text)
                {
                    if (propertyName != "value")                     // Inline Parameters && Parameters via ParameterMap
                    {
//						ParameterProperty property = request.ParameterMap.GetProperty(i);

//						parameterValue = request.ParameterMap.GetValueOfProperty(parameterObject,
//							property.PropertyName);
                    }
                    else                     // 'value' parameter
                    {
                        parameterValue = parameterObject;
                    }
                }
                else                 // CommandType.StoredProcedure
                {
                    // A store procedure must always use a ParameterMap
                    // to indicate the mapping order of the properties to the columns
                    if (request.ParameterMap == null)                     // Inline Parameters
                    {
                        throw new DataMapperException("A procedure statement tag must alway have a parameterMap attribute, which is not the case for the procedure '" + statement.Id + "'.");
                    }
                    else                     // Parameters via ParameterMap
                    {
                        ParameterProperty property = request.ParameterMap.GetProperty(i);

                        if (property.DirectionAttribute.Length == 0)
                        {
                            property.Direction = sqlParameter.Direction;
                        }

                        //						IDbDataParameter dataParameter = (IDbDataParameter)parameters[i];
                        //						property.Precision = dataParameter.Precision;
                        //						property.Scale = dataParameter.Scale;
                        //						property.Size = dataParameter.Size;

                        sqlParameter.Direction = property.Direction;
//						parameterValue = request.ParameterMap.GetValueOfProperty(parameterObject, property.PropertyName);
                    }
                }

                IDataParameter parameterCopy = command.CreateParameter();
                // Fix JIRA 20
                sqlParameter.Value  = parameterValue;
                parameterCopy.Value = parameterValue;

                parameterCopy.Direction = sqlParameter.Direction;

                // With a ParameterMap, we could specify the ParameterDbTypeProperty
                if (statement.ParameterMap != null)
                {
                    if (request.ParameterMap.GetProperty(i).DbType != null &&
                        request.ParameterMap.GetProperty(i).DbType.Length > 0)
                    {
                        string dbTypePropertyName = session.DataSource.DbProvider.ParameterDbTypeProperty;

                        ObjectProbe.SetPropertyValue(parameterCopy, dbTypePropertyName, ObjectProbe.GetPropertyValue(sqlParameter, dbTypePropertyName));
                    }
                    else
                    {
                        //parameterCopy.DbType = sqlParameter.DbType;
                    }
                }
                else
                {
                    //parameterCopy.DbType = sqlParameter.DbType;
                }

                // JIRA-49 Fixes (size, precision, and scale)
                if (session.DataSource.DbProvider.SetDbParameterSize)
                {
                    if (((IDbDataParameter)sqlParameter).Size > 0)
                    {
                        ((IDbDataParameter)parameterCopy).Size = ((IDbDataParameter)sqlParameter).Size;
                    }
                }

                if (session.DataSource.DbProvider.SetDbParameterPrecision)
                {
                    ((IDbDataParameter)parameterCopy).Precision = ((IDbDataParameter)sqlParameter).Precision;
                }

                if (session.DataSource.DbProvider.SetDbParameterScale)
                {
                    ((IDbDataParameter)parameterCopy).Scale = ((IDbDataParameter)sqlParameter).Scale;
                }

                parameterCopy.ParameterName = sqlParameter.ParameterName;

                command.Parameters.Add(parameterCopy);


                // NOTE:
                // Code from Oleksa Borodie to embed parameter values
                // into command text/sql statement.
                // NEED TO MERGE WITH ABOVE AFTER INITIAL TESTING
                // TO REMOVE REDUNDANT LOOPING!

                // replace parameter names with parameter values
                // only for parameters with names, parameterMaps will be ignored
                IDataParameter p;
                for (int iCnt = command.Parameters.Count - 1; iCnt >= 0; iCnt--)
                {
                    p = (IDataParameter)command.Parameters[iCnt];
                    if (p.Direction == ParameterDirection.Input &&
                        command.CommandText.IndexOf(p.ParameterName) > 0)
                    {
                        switch (p.DbType)
                        {
                        case DbType.String:
                        case DbType.AnsiString:
                        case
                            DbType.AnsiStringFixedLength:
                        case DbType.StringFixedLength:
                            command.CommandText =
                                command.CommandText.Replace(p.ParameterName,
                                                            "\'" + p.Value.ToString().Replace("\'", "\'\'") + "\'");
                            break;

                        case DbType.Date:
                        case DbType.DateTime:
                            DateTime v =
                                Convert.ToDateTime(p.Value);
                            command.CommandText =
                                command.CommandText.Replace(p.ParameterName,
                                                            String.Format("\'{0}.{1}.{2} {3}:{4}:{5}.{6}\'", v.Year, v.Month,
                                                                          v.Day, v.Hour, v.Minute, v.Second, v.Millisecond));
                            //                                                      command.CommandText =
                            command.CommandText.Replace(p.ParameterName,
                                                        "\'" + p.Value.ToString() + "\'");
                            break;

                        case DbType.Double:
                        case DbType.Decimal:
                        case DbType.Currency:
                        case DbType.Single:
                            command.CommandText =
                                command.CommandText.Replace(p.ParameterName,
                                                            p.Value.ToString().Replace(',', '.'));
                            break;

                        default:
                            command.CommandText =
                                command.CommandText.Replace(p.ParameterName, p.Value.ToString());
                            break;
                        }
                        command.Parameters.RemoveAt(iCnt);
                    }
                }
            }
        }
Exemple #57
0
 /// <summary>
 /// Retrieves the set of IDataParameters appropriate for the stored procedure
 /// </summary>
 /// <remarks>
 /// This method will query the database for this information, and then store it in a cache for future requests.
 /// </remarks>
 /// <param name="session">a valid session</param>
 /// <param name="spName">the name of the stored procedure</param>
 /// <returns>an array of IDataParameters</returns>
 public IDataParameter[] GetSpParameterSet(IDalSession session, string spName)
 {
     return(GetSpParameterSet(session, spName, false));
 }
Exemple #58
0
 public ArticleRepository(IDalSession dalSession)
 {
     _dalSession = dalSession;
 }
Exemple #59
0
 /// <summary>
 /// Store the local session.
 /// Ensure that the session is unique for each thread.
 /// </summary>
 /// <param name="session">The session to store</param>
 public void Store(IDalSession session)
 {
     CallContext.SetData(_sessionName, session);
 }
Exemple #60
0
        /// <summary>
        /// Store the specified session.
        /// </summary>
        /// <param name="session">The session to store</param>

        public override void Store(IDalSession session)
        {
            CallContext.SetData(sessionName, session);
        }