private SqlCeResultSet DoExecuteResultSet(SqlCeCommand command, ResultSetOptions options)
        {
            DateTime       startTime = DateTime.Now;
            SqlCeResultSet reader    = command.ExecuteResultSet(options);

            return(reader);
        }
 /// <summary>
 ///        SQL Server CE provides a new type of data reader, the <see cref="SqlCeResultSet"/>, that provides
 ///        new abilities and better performance over a standard reader. This method provides access to
 ///        this reader.
 /// </summary>
 /// <remarks>
 ///        The <see cref="SqlCeResultSet"/> returned from this method will close the connection on dispose.
 /// </remarks>
 /// <param name="command">
 ///        The command that contains the SQL SELECT statement to execute.
 /// </param>
 /// <param name="options">Controls how the <see cref="SqlCeResultSet"/> behaves.</param>
 /// <param name="parameters">An option set of <see cref="DbParameter"/> parameters.</param>
 /// <returns>The reader in the form of a <see cref="SqlCeResultSet"/>.</returns>
 public virtual SqlCeResultSet ExecuteResultSet(DbCommand command, ResultSetOptions options, params DbParameter[] parameters)
 {
     using (DatabaseConnectionWrapper wrapper = GetOpenConnection())
     {
         AddParameters(command, parameters);
         PrepareCommand(command, wrapper.Connection);
         return(new SqlCeResultSetWrapper(wrapper, DoExecuteResultSet((SqlCeCommand)command, options)));
     }
 }
        /// <summary>
        /// Sends the command to the database and builds a <see cref="SqlCeResultSet"/>.
        /// </summary>
        /// <param name="command">The <see cref="DbCommand"/> to execute.</param>
        /// <param name="parameters">The parameter to pass to the command.</param>
        /// <param name="options">The <see cref="ResultSetOptions"/> to use when building the <see cref="SqlCeResultSet"/>.</param>
        /// <returns>A <see cref="SqlCeResultSet"/>.</returns>
        public override SqlCeResultSet ExecuteResultSet(DbCommand command, ResultSetOptions options,
                                                        params DbParameter[] parameters)
        {
            Guard.ArgumentNotNull(command, "command");

            SqlCeResultSet result = base.ExecuteResultSet(command, options, parameters);

            connection = command.Connection;
            return(result);
        }
        /// <summary>
        /// Sends the command to the database and builds a <see cref="SqlCeResultSet"/>.
        /// </summary>
        /// <param name="sqlCommand">The command to execute.</param>
        /// <param name="parameters">The parameter to pass to the command.</param>
        /// <param name="options">The <see cref="ResultSetOptions"/> to use when building the <see cref="SqlCeResultSet"/>.</param>
        /// <returns>A <see cref="SqlCeResultSet"/>.</returns>
        public SqlCeResultSet ExecuteResultSet(string sqlCommand, ResultSetOptions options, params DbParameter[] parameters)
        {
            Guard.ArgumentNotNullOrEmptyString(sqlCommand, "sqlCommand");

            using (SqlCeCommand command = (SqlCeCommand)DbProviderFactory.CreateCommand())
            {
                command.CommandText = sqlCommand;
                SqlCeResultSet result = ExecuteResultSet(command, options, parameters);
                connection = command.Connection;
                return(result);
            }
        }
        public SqlCeResultSet ExecuteResultSet(ResultSetOptions options, SqlCeResultSet resultSet)
        {
            var index = 0;

            Debug.Assert(CommandTexts.Length == 1 || CommandTexts.Length == 2);
            if (commandTexts.Length > 1)
            {
                command.CommandText = commandTexts[index++];

                // Not dispatching to interceptors here because that was already done before calling ExecuteReader.
                // This call is simply an implementation detail of how the SQL CE provider handles the command text.
                var cAffectedRecords = command.ExecuteNonQuery();

                // If first command doesn't affect any records, then second query should not return any rows
                //
                if (cAffectedRecords == 0)
                {
                    command.CommandText = "select * from (" + CommandTexts[index] + ") as temp where 1=2;";
                }
                else
                {
                    command.CommandText = commandTexts[index];
                }
            }
            else
            {
                command.CommandText = commandTexts[index];
            }
            try
            {
                return(command.ExecuteResultSet(options, resultSet));
            }
            catch (SqlCeException e)
            {
                // index == 1, means there are multiple commands in this SqlCeMultiCommand. Which indicates Server generated keys scenario.
                // This check will only work under the assumptions that:
                //      1. SqlCeMultiCommand is used only for Server generated keys scenarios.
                //      2. Server generated keys query generate exactly 2 commands.
                //
                if (index == 1)
                {
                    // Wrap in inner exception and let  user know that DML has succeeded.
                    throw new SystemException(EntityRes.GetString(EntityRes.ADP_CanNotRetrieveServerGeneratedKey), e);
                }
                else
                {
                    throw;
                }
            }
        }
Beispiel #6
0
 private SqlCeResultSet DoExecuteResultSet(SqlCeCommand command, ResultSetOptions options)
 {
     try
     {
         DateTime       startTime = DateTime.Now;
         SqlCeResultSet reader    = command.ExecuteResultSet(options);
         instrumentationProvider.FireCommandExecutedEvent(startTime);
         return(reader);
     }
     catch (Exception e)
     {
         instrumentationProvider.FireCommandFailedEvent(command.CommandText, ConnectionStringNoCredentials, e);
         throw;
     }
 }
Beispiel #7
0
        /// <summary>
        ///		Sql Server CE provides a new type of data reader, the <see cref="SqlCeResultSet"/>, that provides
        ///		new abilities and better performance over a standard reader. This method provides access to
        ///		this reader.
        /// </summary>
        /// <remarks>
        ///		Unlike other Execute... methods that take a <see cref="DbCommand"/> instance, this method
        ///		does not set the command behavior to close the connection when you close the reader.
        ///		That means you'll need to close the connection yourself, by calling the
        ///		command.Connection.Close() method after you're finished using the reader.
        /// </remarks>
        /// <param name="command">
        ///		The command that contains the SQL to execute. It should be a SELECT statement.
        /// </param>
        /// <param name="options">Controls how the <see cref="SqlCeResultSet"/> behaves</param>
        /// <param name="parameters">An option set of <see cref="DbParameter"/> parameters</param>
        /// <returns>The reader in the form of a <see cref="SqlCeResultSet"/></returns>
        public virtual SqlCeResultSet ExecuteResultSet(DbCommand command, ResultSetOptions options, params DbParameter[] parameters)
        {
            ConnectionWrapper wrapper = GetOpenConnection(false);

            try
            {
                AddParameters(command, parameters);
                PrepareCommand(command, wrapper.Connection);
                return(DoExecuteResultSet((SqlCeCommand)command, options));
            }
            catch
            {
                wrapper.Connection.Close();                                     // Close the connection since we asked the wrapper not to, and we're done with it
                throw;
            }
        }
Beispiel #8
0
        public object ExecuteSql(string sql, bool updatable)
        {
            if (Connection == null)
            {
                return(null);
            }

            if (Connection.State == ConnectionState.Closed)
            {
                Connection.Open();
            }

            LastError = string.Empty;

            object           command  = assembly.CreateInstance("System.Data.SqlServerCe.SqlCeCommand", false, BindingFlags.CreateInstance, null, new object[] { null, Connection }, null, null);
            var              enumType = assembly.GetType("System.Data.SqlServerCe.ResultSetOptions");
            ResultSetOptions options  = updatable ? ResultSetOptions.Scrollable | ResultSetOptions.Updatable : ResultSetOptions.Scrollable;

            object result = null;

            QueryCount = 0;

            for (Match m = regexSemicolon.Match(sql); m.Success; m = m.NextMatch())
            {
                if (!string.IsNullOrWhiteSpace(m.Value))
                {
                    QueryCount++;
                    try
                    {
                        command.GetType().InvokeMember("CommandText", BindingFlags.SetProperty, null, command, new object[] { m.Value.Trim() });
                        object resultset  = command.GetType().GetMethod("ExecuteResultSet", new Type[] { enumType }, null).Invoke(command, new object[] { options });
                        bool   scrollable = (bool)resultset.GetType().InvokeMember("Scrollable", BindingFlags.GetProperty, null, resultset, null);
                        if (scrollable)
                        {
                            result = resultset;
                        }
                    }
                    catch (Exception e)
                    {
                        LastError = $"{GlobalText.GetValue("Query")} {QueryCount}: {(e.InnerException == null ? e.Message : e.InnerException.Message)}";
                        return(null);
                    }
                }
            }

            return(result);
        }
Beispiel #9
0
        /// <summary>
        /// Text Changed event handler for the tbCommand TextBox
        /// - In this handler the data displayed in the grid is filtered
        /// - on the Ship Name column according to what is typed in the TextBox
        /// </summary>
        private void tbCommand_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (false == this.menuItemUseDataSet.Checked)
                {
                    if (null == this.resultSet)
                    {
                        MessageBox.Show("Command hasn't been executed. Press execute button first");
                        return;
                    }
                    ResultSetOptions options = ResultSetOptions.Scrollable | ResultSetOptions.Sensitive;
                    if (this.menuItemUpdatable.Checked)
                    {
                        options |= ResultSetOptions.Updatable;
                    }

                    // Query the database again using the WHERE clause to filter according
                    // to the input in the text box
                    string query = String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                 "SELECT * FROM Orders WHERE [Ship Name] LIKE '{0}%' ", tbCommand.Text);

                    this.command.CommandText = query;

                    this.resultSet = this.command.ExecuteResultSet(options);
                    this.BindData();
                }
                else
                {
                    if (null == this.table)
                    {
                        MessageBox.Show("Command hasn't been executed. Press execute button first");
                        return;
                    }
                    //Row filters are used to filter the table since the entire table
                    // is already loaded in memory
                    string filterExpression = String.Format(System.Globalization.CultureInfo.InvariantCulture, "[Ship Name] LIKE '{0}%' ", tbCommand.Text);
                    table.DefaultView.RowFilter = filterExpression;
                    this.BindData();
                }
            }
            catch (SqlCeException ex)
            {
                ShowErrors(ex);
            }
        }
Beispiel #10
0
        public static SqlCeResultSet ExecuteScalar(String sqlstring, ResultSetOptions rsopts)
        {
            SqlCeCommand command = Connection.CreateCommand();

            command.CommandText = sqlstring;
            command.CommandType = System.Data.CommandType.Text;
            try
            {
                if (Connection.State != ConnectionState.Open)
                {
                    Connection.Open();
                }
                SqlCeResultSet result = command.ExecuteResultSet(rsopts);
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Connection.Close();
            }
        }
Beispiel #11
0
        /// <summary>
        /// Click Event handler for the Query and Bind button
        /// </summary>
        private void btnExecute_Click(object sender, EventArgs e)
        {
            //Clear the text in the filter textbox above the datagrid
            tbCommand.Text = String.Empty;
            // Disable the button till we are done quering and binding
            btnExecute.Enabled = false;
            try
            {
                // Dispose previous views bound to the currently active RS
                if (null != view1)
                {
                    ((IDisposable)view1).Dispose();
                }
                if (null != view2)
                {
                    ((IDisposable)view2).Dispose();
                }

                // Dispose previous SqlCeCommand and previous SqlCeResultSet
                if (null != this.command)
                {
                    this.command.Dispose();
                }
                if (null != this.resultSet)
                {
                    this.resultSet.Dispose();
                }

                //Creates a Command with the associated connection
                this.command = this.connection.CreateCommand();

                // Use the SqlCeResultSet if the "Use DataSet" menu item is not
                // checked
                if (false == this.menuItemUseDataSet.Checked)
                {
                    // Queury the Orders table in the Northwind database
                    this.command.CommandText = "SELECT * FROM Orders";
                    ResultSetOptions options = ResultSetOptions.Scrollable | ResultSetOptions.Sensitive;

                    if (this.menuItemUpdatable.Checked)
                    {
                        options |= ResultSetOptions.Updatable;
                    }

                    this.resultSet = this.command.ExecuteResultSet(options);

                    this.dataGrid.DataSource = null;
                    // Bind the result set to the controls
                    this.BindData();
                }
                else
                {
                    //Retrieve the columns we are interested in from the Orders table
                    //Note that we do not specify this in the SqlCeResultSet queury above
                    // because we demonstrate the use of the Ordinals property in the
                    // ResultSetView.
                    string query = @"SELECT [Customer ID], [Ship Name],[Ship City]
                                    ,[Ship Country] FROM Orders";
                    this.command.CommandText = query;
                    table        = new DataTable("Orders");
                    table.Locale = System.Globalization.CultureInfo.InvariantCulture;
                    SqlCeDataAdapter adapter = new SqlCeDataAdapter(this.command);

                    adapter.FillSchema(table, SchemaType.Source);
                    adapter.Fill(table);

                    this.dataGrid.DataSource = null;
                    this.BindData();
                }
                btnExecute.Enabled = true;
            }
            catch (InvalidOperationException ex)
            {
                btnExecute.Enabled = true;
                MessageBox.Show(String.Format(System.Globalization.CultureInfo.CurrentCulture,
                                              "Exception while Performing Query/Bind: \n {0}", ex.ToString()));
            }
            catch (SqlCeException ex)
            {
                btnExecute.Enabled = true;
                ShowErrors(ex);
            }
        }
 private SqlCeResultSet DoExecuteResultSet(SqlCeCommand command, ResultSetOptions options)
 {
     DateTime startTime = DateTime.Now;
     SqlCeResultSet reader = command.ExecuteResultSet(options);
     return reader;
 }
        public SqlCeResultSet ExecuteResultSet(ResultSetOptions options, SqlCeResultSet resultSet)
        {
            var index = 0;
            Debug.Assert(CommandTexts.Length == 1 || CommandTexts.Length == 2);
            if (commandTexts.Length > 1)
            {
                command.CommandText = commandTexts[index++];

                // Not dispatching to interceptors here because that was already done before calling ExecuteReader.
                // This call is simply an implementation detail of how the SQL CE provider handles the command text.
                var cAffectedRecords = command.ExecuteNonQuery();

                // If first command doesn't affect any records, then second query should not return any rows
                //
                if (cAffectedRecords == 0)
                {
                    command.CommandText = "select * from (" + CommandTexts[index] + ") as temp where 1=2;";
                }
                else
                {
                    command.CommandText = commandTexts[index];
                }
            }
            else
            {
                command.CommandText = commandTexts[index];
            }
            try
            {
                return command.ExecuteResultSet(options, resultSet);
            }
            catch (SqlCeException e)
            {
                // index == 1, means there are multiple commands in this SqlCeMultiCommand. Which indicates Server generated keys scenario.
                // This check will only work under the assumptions that:
                //      1. SqlCeMultiCommand is used only for Server generated keys scenarios.
                //      2. Server generated keys query generate exactly 2 commands.
                //
                if (index == 1)
                {
                    // Wrap in inner exception and let  user know that DML has succeeded.
                    throw new SystemException(EntityRes.GetString(EntityRes.ADP_CanNotRetrieveServerGeneratedKey), e);
                }
                else
                {
                    throw;
                }
            }
        }
 public SqlCeResultSet ExecuteResultSet(ResultSetOptions options)
 {
     return ExecuteResultSet(options, null /* resultSetType */);
 }
		/// <summary>
		///		Sql Server CE provides a new type of data reader, the <see cref="SqlCeResultSet"/>, that provides
		///		new abilities and better performance over a standard reader. This method provides access to
		///		this reader.
		/// </summary>
		/// <remarks>
		///		The <see cref="SqlCeResultSet"/> returned from this method will close the connection on dispose.
		/// </remarks>
		/// <param name="command">
		///		The command that contains the SQL to execute. It should be a SELECT statement.
		/// </param>
		/// <param name="options">Controls how the <see cref="SqlCeResultSet"/> behaves</param>
		/// <param name="parameters">An option set of <see cref="DbParameter"/> parameters</param>
		/// <returns>The reader in the form of a <see cref="SqlCeResultSet"/></returns>
		public virtual SqlCeResultSet ExecuteResultSet(DbCommand command, ResultSetOptions options, params DbParameter[] parameters)
		{
			using(DatabaseConnectionWrapper wrapper = GetOpenConnection())
			{
				AddParameters(command, parameters);
				PrepareCommand(command, wrapper.Connection);
				return new SqlCeResultSetWrapper(wrapper, DoExecuteResultSet((SqlCeCommand)command, options));
			}
		}
Beispiel #16
0
		/// <summary>
		///		Sql Server CE provides a new type of data reader, the <see cref="SqlCeResultSet"/>, that provides
		///		new abilities and better performance over a standard reader. This method provides access to
		///		this reader.
		/// </summary>
		/// <remarks>
		///		Unlike other Execute... methods that take a <see cref="DbCommand"/> instance, this method
		///		does not set the command behavior to close the connection when you close the reader.
		///		That means you'll need to close the connection yourself, by calling the
		///		command.Connection.Close() method after you're finished using the reader.
		/// </remarks>
		/// <param name="command">
		///		The command that contains the SQL to execute. It should be a SELECT statement.
		/// </param>
		/// <param name="options">Controls how the <see cref="SqlCeResultSet"/> behaves</param>
		/// <param name="parameters">An option set of <see cref="DbParameter"/> parameters</param>
		/// <returns>The reader in the form of a <see cref="SqlCeResultSet"/></returns>
		public virtual SqlCeResultSet ExecuteResultSet(DbCommand command, ResultSetOptions options, params DbParameter[] parameters)
		{
			ConnectionWrapper wrapper = GetOpenConnection(false);

			try
			{
				AddParameters(command, parameters);
				PrepareCommand(command, wrapper.Connection);
				return DoExecuteResultSet((SqlCeCommand)command, options);
			}
			catch
			{
				wrapper.Connection.Close();			// Close the connection since we asked the wrapper not to, and we're done with it
				throw;
			}
		}
Beispiel #17
0
        public SQLCECursor ExecuteResultSet(string tableName, string indexName, DbRangeOptions rangeOptions, object[] startValues, object[] endValues, ResultSetOptions resultSetOptions)
        {
            Command.CommandType = System.Data.CommandType.TableDirect;
            Command.CommandText = tableName;
            Command.IndexName   = indexName;
            Command.SetRange(rangeOptions, startValues, endValues);
                        #if SQLSTORETIMING
            long startTicks = TimingUtility.CurrentTicks;
            try
            {
                        #endif

            return(new SQLCECursor(this, Command.ExecuteResultSet(resultSetOptions)));

                        #if SQLSTORETIMING
        }

        finally
        {
            Store.Counters.Add(new SQLStoreCounter("ExecuteResultSet", ATableName, AIndexName, AStartValues != null && AEndValues == null, AStartValues != null && AEndValues != null, (ResultSetOptions.Updatable & AResultSetOptions) != 0, TimingUtility.TimeSpanFromTicks(startTicks)));
        }
                        #endif
        }
Beispiel #18
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="command"></param>
		/// <param name="transaction"></param>
		/// <param name="options"></param>
		/// <param name="parameters"></param>
		/// <returns></returns>
		public virtual SqlCeResultSet ExecuteResultSet(DbCommand command, DbTransaction transaction, ResultSetOptions options, params DbParameter[] parameters)
		{
			AddParameters(command, parameters);
			PrepareCommand(command, transaction);
			return DoExecuteResultSet((SqlCeCommand)command, options);
		}
Beispiel #19
0
		private SqlCeResultSet DoExecuteResultSet(SqlCeCommand command, ResultSetOptions options)
		{
			try
			{
				DateTime startTime = DateTime.Now;
				SqlCeResultSet reader = command.ExecuteResultSet(options);
				instrumentationProvider.FireCommandExecutedEvent(startTime);
				return reader;
			}
			catch (Exception e)
			{
				instrumentationProvider.FireCommandFailedEvent(command.CommandText, ConnectionStringNoCredentials, e);
				throw;
			}
		}
Beispiel #20
0
        internal SqlCeResultSet ExecuteResultSet(string ATableName, string AIndexName, DbRangeOptions ARangeOptions, object[] AStartValues, object[] AEndValues, ResultSetOptions AResultSetOptions)
        {
            ExecuteCommand.CommandType = CommandType.TableDirect;
            ExecuteCommand.CommandText = ATableName;
            ExecuteCommand.IndexName   = AIndexName;
            ExecuteCommand.SetRange(ARangeOptions, AStartValues, AEndValues);

                        #if SQLSTORETIMING
            long LStartTicks = TimingUtility.CurrentTicks;
            try
            {
                        #endif

            return(ExecuteCommand.ExecuteResultSet(AResultSetOptions));

                        #if SQLSTORETIMING
        }
        finally
        {
            Store.Counters.Add(new SQLStoreCounter("ExecuteResultSet", ATableName, AIndexName, AStartValues != null && AEndValues == null, AStartValues != null && AEndValues != null, (ResultSetOptions.Updatable & AResultSetOptions) != 0, TimingUtility.TimeSpanFromTicks(LStartTicks)));
        }
                        #endif
        }
Beispiel #21
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="command"></param>
 /// <param name="transaction"></param>
 /// <param name="options"></param>
 /// <param name="parameters"></param>
 /// <returns></returns>
 public virtual SqlCeResultSet ExecuteResultSet(DbCommand command, DbTransaction transaction, ResultSetOptions options, params DbParameter[] parameters)
 {
     AddParameters(command, parameters);
     PrepareCommand(command, transaction);
     return(DoExecuteResultSet((SqlCeCommand)command, options));
 }
 public SqlCeResultSet ExecuteResultSet(ResultSetOptions options)
 {
     return(ExecuteResultSet(options, null /* resultSetType */));
 }
        protected override object[] Select(string entityName, IEnumerable <FilterCondition> filters, int fetchCount, int firstRowOffset, bool fillReferences, bool filterReferences, IDbConnection connection)
        {
            if (!m_entities.HasEntity(entityName))
            {
                throw new EntityNotFoundException(entityName);
            }

            UpdateIndexCacheForType(entityName);

            //var genType = typeof(List<>).MakeGenericType(objectType);
            //var items = (System.Collections.IList)Activator.CreateInstance(genType);

            var  items = new List <object>();
            bool tableDirect;

            SqlEntityInfo entity          = m_entities[entityName];
            var           isDynamicEntity = entity is DynamicEntityInfo;

            if (connection == null)
            {
                connection = GetConnection(false);
            }
            SqlCeCommand command = null;

            if (UseCommandCache)
            {
                Monitor.Enter(CommandCache);
            }

            try
            {
                CheckPrimaryKeyIndex(entityName);

                OnBeforeSelect(entity, filters, fillReferences);
                var start = DateTime.Now;

                command            = GetSelectCommand <SqlCeCommand, SqlCeParameter>(entityName, filters, firstRowOffset, fetchCount, out tableDirect);
                command.Connection = connection as SqlCeConnection;

                int searchOrdinal        = -1;
                ResultSetOptions options = ResultSetOptions.Scrollable;

                object matchValue       = null;
                string matchField       = null;
                bool   primarykeyfilter = false;

                if (tableDirect) // use index
                {
                    if ((filters != null) && (filters.Count() > 0))
                    {
                        var filter = filters.First();

                        matchValue = filter.Value ?? DBNull.Value;
                        matchField = filter.FieldName;

                        var sqlfilter = filter as SqlFilterCondition;
                        if ((sqlfilter != null) && (sqlfilter.PrimaryKey))
                        {
                            primarykeyfilter = true;
                        }
                    }

                    // we need to ensure that the search value does not exceed the length of the indexed
                    // field, else we'll get an exception on the Seek call below
                    var indexInfo = GetIndexInfo(command.IndexName);
                    if (indexInfo != null)
                    {
                        if (indexInfo.MaxCharLength > 0)
                        {
                            var value = (string)matchValue;
                            if (value.Length > indexInfo.MaxCharLength)
                            {
                                matchValue = value.Substring(0, indexInfo.MaxCharLength);
                            }
                        }
                    }
                }
                using (var results = command.ExecuteResultSet(options))
                {
                    if (results.HasRows)
                    {
                        var ordinals = GetOrdinals(entityName, results);

                        ReferenceAttribute[] referenceFields = null;

                        int currentOffset = 0;

                        if (matchValue != null)
                        {
                            // convert enums to an int, else the .Equals later check will fail
                            // this feels a bit kludgey, but for now it's all I can think of
                            if (matchValue.GetType().IsEnum)
                            {
                                matchValue = (int)matchValue;
                            }

                            if (primarykeyfilter)
                            {
                                searchOrdinal = ordinals[m_entities[entityName].Fields.KeyField.FieldName];
                            }
                            else if (searchOrdinal < 0)
                            {
                                searchOrdinal = ordinals[matchField];
                            }

                            if (tableDirect)
                            {
                                results.Seek(DbSeekOptions.FirstEqual, new object[] { matchValue });
                            }
                        }

                        // autofill references if desired
                        if (referenceFields == null)
                        {
                            referenceFields = entity.References.ToArray();
                        }

                        while (results.Read())
                        {
                            if (currentOffset < firstRowOffset)
                            {
                                currentOffset++;
                                continue;
                            }

                            if (tableDirect && (matchValue != null))
                            {
                                // if we have a match value, we'll have seeked to the first match above
                                // then at this point the first non-match means we have no more matches, so
                                // we can exit out once we hit the first non-match.

                                // For string we want a case-insensitive search, so it's special-cased here
                                if (matchValue is string)
                                {
                                    if (string.Compare((string)results[searchOrdinal], (string)matchValue, true) != 0)
                                    {
                                        break;
                                    }
                                }
                                else
                                {
                                    if (!results[searchOrdinal].Equals(matchValue))
                                    {
                                        break;
                                    }
                                }
                            }

                            object item  = null;
                            object rowPK = null;

                            if (isDynamicEntity)
                            {
                                var dynamic = new DynamicEntity(entity as DynamicEntityInfo);
                                foreach (var pair in ordinals)
                                {
                                    if (entity.Fields[pair.Key].DataType == DbType.Object)
                                    {
                                        if (entity.Deserializer == null)
                                        {
                                            throw new MissingMethodException(
                                                      string.Format("The field '{0}' requires a custom serializer/deserializer method pair in the '{1}' Entity",
                                                                    pair.Key, entityName));
                                        }
                                        dynamic[pair.Key] = entity.Deserializer(dynamic, pair.Key, results[pair.Value]);
                                    }
                                    else
                                    {
                                        dynamic[pair.Key] = results[pair.Value];
                                    }
                                }
                                item = dynamic;
                            }
                            else if (entity.CreateProxy == null)
                            {
                                if (entity.DefaultConstructor == null)
                                {
                                    item = Activator.CreateInstance(entity.EntityType);
                                }
                                else
                                {
                                    item = entity.DefaultConstructor.Invoke(null);
                                }

                                foreach (var field in entity.Fields)
                                {
                                    var value = results[ordinals[field.FieldName]];
                                    if (value != DBNull.Value)
                                    {
                                        if (field.DataType == DbType.Object)
                                        {
                                            if (entity.Deserializer == null)
                                            {
                                                throw new MissingMethodException(
                                                          string.Format("The field '{0}' requires a custom serializer/deserializer method pair in the '{1}' Entity",
                                                                        field.FieldName, entityName));
                                            }

                                            var @object = entity.Deserializer.Invoke(item, field.FieldName, value);
                                            field.PropertyInfo.SetValue(item, @object, null);
                                        }
                                        else if (field.IsRowVersion)
                                        {
                                            // sql stores this an 8-byte array
                                            field.PropertyInfo.SetValue(item, BitConverter.ToInt64((byte[])value, 0), null);
                                        }
                                        else if (field.PropertyInfo.PropertyType.UnderlyingTypeIs <TimeSpan>())
                                        {
                                            // SQL Compact doesn't support Time, so we're convert to ticks in both directions
                                            var valueAsTimeSpan = new TimeSpan((long)value);
                                            field.PropertyInfo.SetValue(item, valueAsTimeSpan, null);
                                        }
                                        else
                                        {
                                            field.PropertyInfo.SetValue(item, value, null);
                                        }
                                    }
                                    //Check if it is reference key to set, not primary.
                                    ReferenceAttribute attr = referenceFields.Where(
                                        x => x.ReferenceField == field.FieldName).FirstOrDefault();

                                    if (attr != null)
                                    {
                                        rowPK = value;
                                    }
                                    if (field.IsPrimaryKey)
                                    {
                                        rowPK = value;
                                    }
                                }
                            }
                            else
                            {
                                item = entity.CreateProxy.Invoke(results, ordinals);
                            }

                            if ((fillReferences) && (referenceFields.Length > 0))
                            {
                                if (entity.Fields.KeyFields.Count == 1)
                                {
                                    rowPK = entity.Fields.KeyField.PropertyInfo.GetValue(item, null);
                                    //FillReferences(item, rowPK, referenceFields, true);
                                    FillReferences(item, rowPK, referenceFields, false, fillReferences, connection);
                                }
                            }

                            items.Add(item);
                            if ((fetchCount > 0) && (items.Count >= fetchCount))
                            {
                                break;
                            }
                        }
                    }
                }
                OnAfterSelect(entity, filters, fillReferences, DateTime.Now.Subtract(start), command.CommandText);
            }
            finally
            {
                if ((!UseCommandCache) && (command != null))
                {
                    command.Dispose();
                }

                if (UseCommandCache)
                {
                    Monitor.Exit(CommandCache);
                }

                FlushReferenceTableCache();
                DoneWithConnection(connection, false);
            }

            return(items.ToArray());
        }
Beispiel #24
0
 public static SqlCeResultSet ExecuteScalar(String sqlstring,ResultSetOptions rsopts)
 {
     SqlCeCommand command = Connection.CreateCommand();
     command.CommandText = sqlstring;
     command.CommandType = System.Data.CommandType.Text;
     try
     {
         if (Connection.State != ConnectionState.Open)
             Connection.Open();
         SqlCeResultSet result = command.ExecuteResultSet(rsopts);
         return result;
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         Connection.Close();
     }
 }