text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Reflection.Emit;

using BLToolkit.Common;
using BLToolkit.Data;
using BLToolkit.Mapping;
using BLToolkit.Properties;
using BLToolkit.Reflection;
using BLToolkit.Reflection.Emit;
using BLToolkit.TypeBuilder;
using BLToolkit.TypeBuilder.Builders;

namespace BLToolkit.DataAccess
{
	public class DataAccessorBuilder : AbstractTypeBuilderBase
	{
		private struct MapOutputParametersValue
		{
			public readonly string        ReturnValueMember;
			public readonly ParameterInfo ParameterInfo;

			public MapOutputParametersValue(string returnValueMember, ParameterInfo parameterInfo)
			{
				ReturnValueMember = returnValueMember;
				ParameterInfo     = parameterInfo;
			}
		}

		public override int GetPriority(BuildContext context)
		{
			return TypeBuilderConsts.Priority.DataAccessor;
		}

		public override bool IsApplied(BuildContext context, AbstractTypeBuilderList builders)
		{
			if (context.IsBuildStep)
			{
				if (context.IsAbstractMethod)
				{
					// Give up if there is any builder that builds the method body.
					//
					if (builders.Count > 1)
						foreach (IAbstractTypeBuilder builder in builders)
							if (builder != this && builder.IsApplied(context, builders))
								return false;

					return true;
				}

				// Treat an abstract getter/setter as a regular method
				// when the property has [NoInstance] attribute
				//
				if (context.IsAbstractGetter || context.IsAbstractSetter)
					return context.CurrentProperty.IsDefined(typeof(NoInstanceAttribute), true);
			}

			return false;
		}

		private Dictionary<Type, Type> _actualTypes;
		private Dictionary<Type, Type>  ActualTypes
		{
			get
			{
				if (_actualTypes == null)
				{
					_actualTypes = new Dictionary<Type,Type>();

					object[] attrs = Context.Type.GetAttributes(typeof(ActualTypeAttribute));

					foreach (ActualTypeAttribute attr in attrs)
						if (!_actualTypes.ContainsKey(attr.BaseType))
							_actualTypes.Add(attr.BaseType, attr.ActualType);
				}

				return _actualTypes;
			}
		}

		enum ReturnType
		{
			DataReader,
			DataSet,
			DataTable,
			List,
			Dictionary,
			Enumerable,
			Void,
			Scalar,
			Object
		}

		private static ReturnType GetReturnType(Type returnType)
		{
			if (returnType == typeof(IDataReader))
				return ReturnType.DataReader;

			if (returnType == typeof(DataSet) || returnType.IsSubclassOf(typeof(DataSet)))
				return ReturnType.DataSet;

			if (returnType == typeof(DataTable) || returnType.IsSubclassOf(typeof(DataTable)))
				return ReturnType.DataTable;

			if (!returnType.IsArray &&
				(IsInterfaceOf(returnType, typeof(IList)) ||
					returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(IList<>)))
				return ReturnType.List;

			if (IsInterfaceOf(returnType, typeof(IDictionary)) ||
				returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(IDictionary<,>))
				return ReturnType.Dictionary;

			if (returnType == typeof(IEnumerable) ||
				returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
				return ReturnType.Enumerable;

			if (returnType == typeof(void))
				return ReturnType.Void;

			if (TypeHelper.IsScalar(returnType.IsByRef? returnType.GetElementType(): returnType))
				return ReturnType.Scalar;

			return ReturnType.Object;
		}

		void ThrowTypeBuilderException(string message)
		{
			throw new TypeBuilderException(
				string.Format(message, Context.CurrentMethod.DeclaringType.Name, Context.CurrentMethod.Name));
		}

		const BindingFlags _bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		readonly Type     _baseType = typeof(DataAccessor);
		Type              _objectType;
		bool              _explicitObjectType;
		ParameterInfo[]   _parameters;
		ArrayList         _paramList;
		ArrayList         _refParamList;
		bool              _createManager;
		LocalBuilder      _locManager;
		LocalBuilder      _locObjType;
		ArrayList         _outputParameters;
		SqlQueryAttribute _sqlQueryAttribute;
		ArrayList         _formatParamList;
		ParameterInfo     _destination;
		ArrayList         _mapOutputParameters;

		protected override void BuildAbstractMethod()
		{
			// Any class variable must be initialized before use
			// as the same instance of the class is utilized to build abstract methods.
			//
			_paramList           = new ArrayList();
			_refParamList        = new ArrayList();
			_formatParamList     = new ArrayList();
			_mapOutputParameters = new ArrayList();
			_destination         = null;
			_createManager       = true;
			_objectType          = null;
			_explicitObjectType  = false;
			_parameters          = Context.CurrentMethod.GetParameters();
			_locManager          = Context.MethodBuilder.Emitter.DeclareLocal(typeof(DbManager));
			_locObjType          = Context.MethodBuilder.Emitter.DeclareLocal(typeof(Type));
			_outputParameters    = null;
			_sqlQueryAttribute   = null;

			GetSqlQueryAttribute();
			ProcessParameters();

			Type returnType = MethodReturnType;
			ReturnType rt   = GetReturnType(returnType);

			CreateDbManager(rt != ReturnType.Enumerable);
			SetObjectType();

			// Define execution method type.
			//
			switch (rt)
			{
				case ReturnType.DataReader : ExecuteReader();            break;
				case ReturnType.DataSet    : ExecuteDataSet(returnType); break;
				case ReturnType.DataTable  : ExecuteDataTable();         break;
				case ReturnType.Void       : ExecuteNonQuery();          break;
				case ReturnType.Scalar     : ExecuteScalar();            break;
				case ReturnType.Enumerable : ExecuteEnumerable();        break;

				case ReturnType.List       :

					if (!_explicitObjectType)
					{
						Type elementType = TypeHelper.GetListItemType(returnType);

						if (elementType == typeof(object) && _destination != null)
							elementType = TypeHelper.GetListItemType(Context.CurrentMethod.ReturnType);

						if (elementType != typeof(object))
							_objectType = elementType;

						if (ActualTypes.ContainsKey(_objectType))
							_objectType = ActualTypes[_objectType];
					}

					if (_objectType == null || _objectType == typeof(object))
						ThrowTypeBuilderException(Resources.DataAccessorBuilder_BadListItemType);

					if (TypeHelper.IsScalar(_objectType))
						ExecuteScalarList();
					else
						ExecuteList();

					break;

				case ReturnType.Dictionary:
					{
						Type   elementType = null;
						Type   keyType     = typeof(object);
						Type[] gTypes      = TypeHelper.GetGenericArguments(returnType, typeof(IDictionary));

						if ((gTypes == null || gTypes.Length != 2) && _destination != null)
							gTypes = TypeHelper.GetGenericArguments(_destination.ParameterType, typeof(IDictionary));

						if (gTypes != null && gTypes.Length == 2)
						{
							keyType     = gTypes[0];
							elementType = gTypes[1];
						}

						if (elementType == null || _explicitObjectType)
							elementType = _objectType;

						if (elementType == null || elementType == typeof(object))
							ThrowTypeBuilderException(Resources.DataAccessorBuilder_BadListItemType);

						bool isIndex = TypeHelper.IsSameOrParent(typeof(CompoundValue), keyType);

						if (keyType != typeof(object) && !isIndex && !TypeHelper.IsScalar(keyType))
							ThrowTypeBuilderException(
								Resources.DataAccessorBuilder_BadKeyType);

						MethodInfo mi = Context.CurrentMethod;

						object[]               attrs  = mi.GetCustomAttributes(typeof(IndexAttribute), true);
						NameOrIndexParameter[] fields = new NameOrIndexParameter[0];

						if (attrs.Length != 0)
							fields = ((IndexAttribute)attrs[0]).Fields;

						if (fields.Length > 1 && keyType != typeof(object) && !isIndex)
							ThrowTypeBuilderException(
								Resources.DataAccessor_InvalidKeyType);

						if (TypeHelper.IsScalar(elementType))
						{
							attrs = mi.GetCustomAttributes(typeof(ScalarFieldNameAttribute), true);

							if (attrs.Length == 0)
								ThrowTypeBuilderException(Resources.DataAccessorBuilder_ScalarFieldNameMissing);

							NameOrIndexParameter scalarField = ((ScalarFieldNameAttribute)attrs[0]).NameOrIndex;

							if (fields.Length == 0)
								ExecuteScalarDictionaryWithPK(keyType, scalarField, elementType);
							else if (isIndex || fields.Length > 1)
								ExecuteScalarDictionaryWithMapIndex(fields, scalarField, elementType);
							else
								ExecuteScalarDictionaryWithScalarKey(fields[0], keyType, scalarField, elementType);
						}
						else
						{
							if (!_explicitObjectType && ActualTypes.ContainsKey(elementType))
								elementType = ActualTypes[elementType];

							if (fields.Length == 0)
								ExecuteDictionaryWithPK(keyType, elementType);
							else if (isIndex || fields.Length > 1)
								ExecuteDictionaryWithMapIndex(fields, elementType);
							else
								ExecuteDictionaryWithScalarKey(fields[0], elementType);
						}
					}

					break;

				default:

					if (_objectType == null)
						_objectType = returnType;

					if (!_explicitObjectType && ActualTypes.ContainsKey(_objectType))
						_objectType = ActualTypes[_objectType];

					ExecuteObject();

					break;
			}

			GetOutRefParameters();

			if (rt != ReturnType.Enumerable)
				Finally();
		}

		protected override void BuildAbstractGetter()
		{
			BuildAbstractMethod();
		}

		protected override void BuildAbstractSetter()
		{
			BuildAbstractMethod();
		}

		private void GetSqlQueryAttribute()
		{
			object[] attrs = Context.CurrentMethod.GetCustomAttributes(typeof(SqlQueryAttribute), true);

			if (attrs.Length != 0)
				_sqlQueryAttribute = (SqlQueryAttribute)attrs[0];
		}

		private void AddParameter(ParameterInfo pi)
		{
			Type pType = pi.ParameterType;

			if (pType.IsByRef)
				pType = pType.GetElementType();

			if (TypeHelper.IsScalar(pType))
				_paramList.Add(pi);
			else if (pType == typeof(DbManager) || pType.IsSubclassOf(typeof(DbManager)))
				_createManager = false;
			else
				_refParamList.Add(pi);
		}

		private void ProcessParameters()
		{
			for (int i = 0; i < _parameters.Length; i++)
			{
				ParameterInfo       pi = _parameters[i];
				NoMapAttribute[] attrs = (NoMapAttribute[])pi.GetCustomAttributes(typeof(NoMapAttribute), true);

				if (attrs.Length == 0)
					AddParameter(pi);
				else
				{
					for (int j = 0; j < attrs.Length; ++j)
					{
						if (!attrs[j].NoMap)
							AddParameter(pi);

						if (attrs[j] is FormatAttribute)
						{
							int index = ((FormatAttribute)attrs[j]).Index;

							if (index < 0)
								index = 0;
							else if (index > _formatParamList.Count)
								index = _formatParamList.Count;

							_formatParamList.Insert(index, pi);
						}
						else if (attrs[j] is DestinationAttribute)
						{
							if (_destination != null)
								throw new TypeBuilderException(Resources.DataAccessorBuilderTooManyDestinations);

							_destination = pi;
						}
					}
				}
			}
		}

		private void CreateDbManager(bool beginException)
		{
			EmitHelper emit = Context.MethodBuilder.Emitter;

			if (_createManager)
			{
				emit
					.ldarg_0
					.callvirt (_baseType, "GetDbManager")
					.stloc    (_locManager);

				if (beginException)
					emit.BeginExceptionBlock();
			}
			else
			{
				for (int i = 0; i < _parameters.Length; i++)
				{
					Type pType = _parameters[i].ParameterType;

					if (pType == typeof(DbManager) || pType.IsSubclassOf(typeof(DbManager)))
					{
						emit
							.ldarg   (_parameters[i])
							.stloc   (_locManager)
							;

						break;
					}
				}
			}
		}

		private void SetObjectType()
		{
			MethodInfo mi = Context.CurrentMethod;

			object[] attrs = mi.GetCustomAttributes(typeof(ObjectTypeAttribute), true);

			if (attrs.Length == 0)
				attrs = mi.DeclaringType.GetCustomAttributes(typeof(ObjectTypeAttribute), true);
			else
				_explicitObjectType = true;

			if (attrs.Length != 0)
				_objectType = ((ObjectTypeAttribute)attrs[0]).ObjectType;

			if (_objectType == null)
			{
				Type[] types = TypeHelper.GetGenericArguments(mi.DeclaringType, typeof(DataAccessor));

				if (types != null)
					_objectType = types[0];
			}
		}

		#region ExecuteReader

		private void ExecuteReader()
		{
			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();

			object[] attrs = Context.CurrentMethod.GetCustomAttributes(typeof(CommandBehaviorAttribute), true);

			if (attrs.Length == 0)
			{
				Context.MethodBuilder.Emitter
					.callvirt (typeof(DbManager).GetMethod("ExecuteReader", Type.EmptyTypes))
					.stloc    (Context.ReturnValue)
					;
			}
			else
			{
				Context.MethodBuilder.Emitter
					.ldc_i4_  ((int)((CommandBehaviorAttribute)attrs[0]).CommandBehavior)
					.callvirt (typeof(DbManager), "ExecuteReader", typeof(CommandBehavior))
					.stloc    (Context.ReturnValue)
					;
			}
		}

		#endregion

		#region ExecuteDataSet

		private void ExecuteDataSet(Type returnType)
		{
			CreateReturnTypeInstance();
			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();

			EmitHelper emit = Context.MethodBuilder.Emitter;

			if (returnType == typeof(DataSet))
			{
				LoadDestinationOrReturnValue();

				object[] attrs = Context.CurrentMethod.GetCustomAttributes(typeof(DataSetTableAttribute), true);

				if (attrs.Length == 0)
				{
					emit
						.callvirt (typeof(DbManager), "ExecuteDataSet", typeof(DataSet))
						.pop
						.end()
						;
				}
				else
				{
					emit
						.ldNameOrIndex(((DataSetTableAttribute)attrs[0]).NameOrIndex)
						.callvirt (typeof(DbManager), "ExecuteDataSet", typeof(DataSet), typeof(NameOrIndexParameter))
						.pop
						.end()
						;
				}
			}
			else
			{
				emit
					.pop
					.end()
					;

				LoadDestinationOrReturnValue();

				Label l1 = emit.DefineLabel();
				Label l2 = emit.DefineLabel();

				emit
					.callvirt  (typeof(DataSet).GetProperty("Tables").GetGetMethod())
					.callvirt  (typeof(InternalDataCollectionBase).GetProperty("Count").GetGetMethod())
					.ldc_i4_0
					.ble_s(l1)
					.ldloc     (_locManager);

				LoadDestinationOrReturnValue();

				object[] attrs = Context.CurrentMethod.GetCustomAttributes(typeof(DataSetTableAttribute), true);

				if (attrs.Length == 0)
				{
					LoadDestinationOrReturnValue();

					emit
						.callvirt (typeof(DataSet).GetProperty("Tables").GetGetMethod())
						.ldc_i4_0
						.callvirt (typeof(DataTableCollection), "get_Item", typeof(int))
						.callvirt (typeof(DataTable).GetProperty("TableName").GetGetMethod())
						.call     (typeof(NameOrIndexParameter), "op_Implicit", typeof(string))
						;
				}
				else
				{
					emit
						.ldNameOrIndex(((DataSetTableAttribute)attrs[0]).NameOrIndex)
						;
				}

				emit
					.callvirt  (typeof(DbManager), "ExecuteDataSet", typeof(DataSet), typeof(NameOrIndexParameter))
					.pop
					.br_s      (l2)
					.MarkLabel (l1)
					.ldloc     (_locManager);

				LoadDestinationOrReturnValue();

				emit
					.callvirt  (typeof(DbManager), "ExecuteDataSet", typeof(DataSet))
					.pop
					.MarkLabel (l2)
					;
			}
		}

		#endregion

		#region ExecuteDataTable

		private void ExecuteDataTable()
		{
			CreateReturnTypeInstance();
			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();
			LoadDestinationOrReturnValue();

			EmitHelper emit = Context.MethodBuilder.Emitter;

			emit
				.callvirt (typeof(DbManager), "ExecuteDataTable", typeof(DataTable))
				.pop
				.end()
				;

			// When DataSetTableAttribute is present, simply set table name to the name specified.
			//
			object[] attrs = Context.CurrentMethod.GetCustomAttributes(typeof(DataSetTableAttribute), true);

			if (attrs.Length != 0)
			{
				DataSetTableAttribute attr = (DataSetTableAttribute)attrs[0];

				if (!attr.NameOrIndex.ByName)
					throw new TypeBuilderException(string.Format(
						Resources.DataAccessorBuilder_DataSetTableMustBeByName,
						Context.CurrentMethod.DeclaringType.Name, Context.CurrentMethod.Name));

				LoadDestinationOrReturnValue();

				emit
					.ldstr(attr.NameOrIndex.Name)
					.callvirt (typeof(DataTable), "set_TableName", typeof(string))
					;
			}
		}

		#endregion

		#region ExecuteScalarList

		private void ExecuteScalarList()
		{
			CreateReturnTypeInstance();
			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();
			LoadDestinationOrReturnValue();

			object[] attrs = Context.CurrentMethod.GetCustomAttributes(typeof(ScalarFieldNameAttribute), true);

			if (attrs.Length == 0)
			{
				Context.MethodBuilder.Emitter
					.ldloc(_locObjType)
					.callvirt(typeof(DbManager), "ExecuteScalarList", typeof(IList), typeof(Type))
					.pop
					.end()
					;
			}
			else
			{
				Context.MethodBuilder.Emitter
					.ldloc(_locObjType)
					.ldNameOrIndex(((ScalarFieldNameAttribute)attrs[0]).NameOrIndex)
					.callvirt(typeof(DbManager), "ExecuteScalarList", typeof(IList), typeof(Type), typeof(NameOrIndexParameter))
					.pop
					.end()
					;
			}
		}

		private void ExecuteList()
		{
			CreateReturnTypeInstance();
			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();
			LoadDestinationOrReturnValue();

			Context.MethodBuilder.Emitter
				.CastIfNecessary (typeof(IList), MethodReturnType)
				.ldloc           (_locObjType)
				.callvirt        (typeof(DbManager), "ExecuteList", typeof(IList), typeof(Type))
				.pop
				.end()
				;
		}

		#endregion

		#region ExecuteDictionary

		public FieldBuilder GetIndexField(NameOrIndexParameter[] namesOrIndexes)
		{
			string id = "index$" + string.Join("%",
				Array.ConvertAll<NameOrIndexParameter, string>(namesOrIndexes,
					delegate(NameOrIndexParameter nameOrIndex)
					{
						return nameOrIndex.ToString();
					}));

			FieldBuilder fieldBuilder = Context.GetField(id);

			if (fieldBuilder == null)
			{
				fieldBuilder = Context.CreatePrivateStaticField(id, typeof(MapIndex));

				EmitHelper emit = Context.TypeBuilder.TypeInitializer.Emitter;

				emit
					.ldc_i4_ (namesOrIndexes.Length)
					.newarr  (typeof(NameOrIndexParameter))
					;

				for (int i = 0; i < namesOrIndexes.Length; i++)
				{
					emit
						.dup
						.ldc_i4_(i)
						.ldelema(typeof(NameOrIndexParameter));

					if (namesOrIndexes[i].ByName)
					{
						emit
							.ldstr(namesOrIndexes[i].Name)
							.call(typeof(NameOrIndexParameter), "op_Implicit", typeof(string));
					}
					else
					{
						emit
							.ldc_i4_(namesOrIndexes[i].Index)
							.call(typeof(NameOrIndexParameter), "op_Implicit", typeof(int));
					}

					emit
						.stobj(typeof(NameOrIndexParameter))
						.end()
						;
				}

				emit
					.newobj (typeof(MapIndex), typeof(NameOrIndexParameter[]))
					.stsfld (fieldBuilder)
					;
			}

			return fieldBuilder;
		}

		/// <summary>
		/// Maps primary keys(s) to a scalar field.
		/// </summary>
		private void ExecuteScalarDictionaryWithPK(
			Type                 keyType,
			NameOrIndexParameter scalarField,
			Type                 elementType)
		{
			CreateReturnTypeInstance();
			InitObjectType();

			Context.MethodBuilder.Emitter
				.ldarg_0
				.end()
				;

			GetSprocNameOrSqlQueryTest();
			CallSetCommand();
			LoadDestinationOrReturnValue();

			Context.MethodBuilder.Emitter
				.ldloc         (_locObjType)
				.LoadType      (keyType)
				.ldstr         (Context.CurrentMethod.Name)
				.ldNameOrIndex (scalarField)
				.LoadType      (elementType)
				.callvirt      (_baseType, "ExecuteScalarDictionary", _bindingFlags,
					            typeof(DbManager), typeof(IDictionary), typeof(Type),
					            typeof(Type), typeof(string), typeof(NameOrIndexParameter), typeof(Type))
				;
		}

		/// <summary>
		/// Maps a complex index to a scalar field.
		/// </summary>
		private void ExecuteScalarDictionaryWithMapIndex(
			NameOrIndexParameter[] index,
			NameOrIndexParameter   scalarField,
			Type                   elementType)
		{
			_objectType = elementType;

			CreateReturnTypeInstance();
			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();
			LoadDestinationOrReturnValue();

			Context.MethodBuilder.Emitter
				.ldsfld        (GetIndexField(index))
				.ldNameOrIndex (scalarField)
				.ldloc         (_locObjType)
				.callvirt      (typeof(DbManager), "ExecuteScalarDictionary",
				                typeof(IDictionary), typeof(MapIndex),
				                typeof(NameOrIndexParameter), typeof(Type))
				.pop
				.end()
				;
		}

		/// <summary>
		/// Maps any single field to any (other) single field.
		/// </summary>
		private void ExecuteScalarDictionaryWithScalarKey(
			NameOrIndexParameter keyField,    Type keyType,
			NameOrIndexParameter scalarField, Type elementType)
		{
			_objectType = elementType;

			CreateReturnTypeInstance();
			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();
			LoadDestinationOrReturnValue();

			Context.MethodBuilder.Emitter
				.ldNameOrIndex (keyField)
				.LoadType      (keyType)
				.ldNameOrIndex (scalarField)
				.ldloc         (_locObjType)
				.callvirt      (typeof(DbManager), "ExecuteScalarDictionary",
					            typeof(IDictionary), typeof(NameOrIndexParameter), typeof(Type),
					            typeof(NameOrIndexParameter), typeof(Type))
				.pop
				.end()
				;
		}

		/// <summary>
		/// Maps primary keys(s) to an object of the specified type.
		/// </summary>
		private void ExecuteDictionaryWithPK(
			Type keyType,
			Type elementType)
		{
			EmitHelper emit = Context.MethodBuilder.Emitter;

			_objectType = elementType;

			CreateReturnTypeInstance();
			InitObjectType();

			emit
				.ldarg_0
				.end()
				;

			GetSprocNameOrSqlQueryTest();
			CallSetCommand();
			LoadDestinationOrReturnValue();

			if (IsGenericDestinationOrReturnValue())
			{
				Type[]     genericArgs = Context.ReturnValue.LocalType.GetGenericArguments();
				Type[]     types       = new Type[]
					{
						typeof(DbManager),
						typeof(IDictionary<,>).MakeGenericType(genericArgs),
						typeof(Type),
						typeof(string),
					};
				MethodInfo method = _baseType.GetMethod("ExecuteDictionary",
					_bindingFlags, GenericBinder.Generic, types, null);

				if (TypeHelper.IsSameOrParent(typeof(CompoundValue), genericArgs[0]))
					method = method.MakeGenericMethod(genericArgs[1]);
				else
					method = method.MakeGenericMethod(genericArgs);

				emit
					.ldloc    (_locObjType)
					.ldstr    (Context.CurrentMethod.Name)
					.callvirt (method)
					;
			}
			else

				emit
					.ldloc    (_locObjType)
					.LoadType (keyType)
					.ldstr    (Context.CurrentMethod.Name)
					.callvirt (_baseType, "ExecuteDictionary", _bindingFlags,
							   typeof(DbManager), typeof(IDictionary), typeof(Type),
							   typeof(Type), typeof(string))
					;
		}

		/// <summary>
		/// Maps a complex index to an object of the specified type.
		/// </summary>
		private void ExecuteDictionaryWithMapIndex(
			NameOrIndexParameter[] index,
			Type                   elementType)
		{
			_objectType = elementType;

			CreateReturnTypeInstance();
			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();
			LoadDestinationOrReturnValue();

			Context.MethodBuilder.Emitter
				.ldsfld   (GetIndexField(index))
				.ldloc    (_locObjType)
				.ldnull
				.callvirt (typeof(DbManager), "ExecuteDictionary",
					       typeof(IDictionary), typeof(MapIndex), typeof(Type), typeof(object[]))
				.pop
				.end()
				;
		}

		/// <summary>
		/// Maps any single field to object type.
		/// </summary>
		private void ExecuteDictionaryWithScalarKey(
			NameOrIndexParameter keyField,
			Type                 elementType)
		{
			EmitHelper emit = Context.MethodBuilder.Emitter;

			_objectType = elementType;

			CreateReturnTypeInstance();
			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();
			LoadDestinationOrReturnValue();

			if (IsGenericDestinationOrReturnValue())
			{
				Type[]     genericArgs = Context.ReturnValue.LocalType.GetGenericArguments();
				Type[]     types       = new Type[]
					{
						typeof(IDictionary<,>).MakeGenericType(genericArgs),
						typeof(NameOrIndexParameter),
						typeof(Type),
						typeof(object[]),
					};
				MethodInfo method = typeof(DbManager).GetMethod("ExecuteDictionary", _bindingFlags, GenericBinder.Generic, types, null)
					.MakeGenericMethod(genericArgs);

				emit
					.ldNameOrIndex(keyField)
					.ldloc        (_locObjType)
					.ldnull
					.callvirt     (method)
					.pop
					.end()
					;
			}
			else
			{
				emit
					.ldNameOrIndex(keyField)
					.ldloc        (_locObjType)
					.ldnull
					.callvirt     (typeof(DbManager), "ExecuteDictionary", typeof(IDictionary), typeof(NameOrIndexParameter), typeof(Type), typeof(object[]))
					.pop
					.end()
					;
			}
		}

		#endregion

		#region ExecuteEnumerable

		public void ExecuteEnumerable()
		{
			EmitHelper emit         = Context.MethodBuilder.Emitter;
			Type       returnType   = Context.CurrentMethod.ReturnType;

			if (_objectType == null && returnType.IsGenericType)
				_objectType = returnType.GetGenericArguments()[0];

			if (_objectType == null || _objectType == typeof(object))
				ThrowTypeBuilderException(Resources.DataAccessorBuilder_BadListItemType);

			Type returnObjectType = returnType.IsGenericType ? returnType.GetGenericArguments()[0] : _objectType;

			InitObjectType();

			Context.MethodBuilder.Emitter
				.ldarg_0
				.end()
				;

			GetSprocNameOrSqlQueryTest();
			CallSetCommand();

			Type[]     genericArgs = new Type[] { returnObjectType };
			Type[]     types       = new Type[] { typeof(DbManager), typeof(Type), typeof(bool), };
			MethodInfo method      = _baseType
				.GetMethod("ExecuteEnumerable", _bindingFlags, GenericBinder.Generic, types, null)
				.MakeGenericMethod(genericArgs);

			emit
				.LoadType (_objectType)
				.ldc_i4_1
				.callvirt (method)
				.stloc    (Context.ReturnValue)
				;
		}

		#endregion

		#region ExecuteNonQuery

		public void ExecuteNonQuery()
		{
			if (_destination != null)
				throw new TypeBuilderException(Resources.DataAccessorBuilder_CantExecuteNonQueryToDestination);

			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();

			MethodInfo   mi      = typeof(DbManager).GetMethod("ExecuteNonQuery", Type.EmptyTypes);
			LocalBuilder locExec = Context.MethodBuilder.Emitter.DeclareLocal(mi.ReturnType);

			Context.MethodBuilder.Emitter
				.callvirt (mi)
				.stloc    (locExec)
				;

			if (Context.ReturnValue != null)
			{
				Context.MethodBuilder.Emitter
					.ldloc (locExec)
					.stloc (Context.ReturnValue)
					;
			}
		}

		#endregion

		#region ExecuteScalar

		public void ExecuteScalar()
		{
			EmitHelper emit       = Context.MethodBuilder.Emitter;
			Type       returnType = Context.CurrentMethod.ReturnType;
			Type       scalarType;

			if (_destination != null)
			{
				if (_destination.ParameterType.IsByRef)
					scalarType = _destination.ParameterType.GetElementType();
				else
					throw new TypeBuilderException(Resources.DataAccessorBuilder_ScalarDestinationIsNotByRef);

				if (returnType != typeof(void) && !TypeHelper.IsSameOrParent(returnType, scalarType))
				{
					// object Foo(out int num) is valid,
					// IConvertible Foo(ref int num) is also ok,
					// but string Bar(out DateTime dt) is not
					//
					throw new TypeBuilderException(string.Format(
						Resources.DataAccessorBuilder_IncompatibleDestinationType,
						returnType.FullName, Context.CurrentMethod.Name, scalarType.FullName));
				}
			}
			else
				scalarType = returnType;

			if (_destination != null)
				emit
					.ldarg (_destination)
					;

			emit
				.ldarg_0
				.ldloc     (_locManager)
				;

			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();

			object[] attrs  = Context.CurrentMethod.GetCustomAttributes(typeof(ScalarSourceAttribute), true);

			if (attrs.Length == 0)
			{
				emit
					.callvirtNoGenerics   (typeof(DbManager), "ExecuteScalar")
					;
			}
			else
			{
				ScalarSourceAttribute attr = (ScalarSourceAttribute)attrs[0];

				emit
					.ldc_i4_            ((int)attr.ScalarType)
					.ldNameOrIndex      (attr.NameOrIndex)
					.callvirtNoGenerics (typeof(DbManager), "ExecuteScalar", typeof(ScalarSourceType), typeof(NameOrIndexParameter));
			}

			MethodInfo converter = GetConverterMethod(scalarType);

			if (converter == null)
			{
				emit
					.LoadType           (scalarType)
					.ldnull
					.callvirt           (_baseType, "ConvertChangeType", _bindingFlags, typeof (DbManager), typeof (object), typeof (Type), typeof (object))
					.unboxIfValueType   (scalarType)
					;

			}
			else
			{
				emit
					.ldnull
					.callvirt           (converter)
					;
			}

			if (_destination != null)
			{
				emit
					.stind              (scalarType)
					;

				// The return value and a destination both are present
				//
				if (Context.ReturnValue != null)
				{
					emit
						.ldargEx        (_destination, false)
						;

					if (scalarType != returnType)
						emit
							.boxIfValueType (scalarType)
							.CastFromObject (returnType)
							;

					emit.stloc          (Context.ReturnValue)
					;
				}
			}
			else
				emit
					.stloc              (Context.ReturnValue)
					;
		}

		#endregion

		#region ExecuteObject

		public void ExecuteObject()
		{
			InitObjectType();
			GetSprocNameOrSqlQueryTest();
			CallSetCommand();

			EmitHelper emit = Context.MethodBuilder.Emitter;

			if (_destination != null)
			{
				emit
					.ldarg(_destination)
					.callvirt(typeof(DbManager), "ExecuteObject", typeof(Object))
					;
			}
			else
			{
				emit
					.ldloc(_locObjType)
					.callvirt(typeof(DbManager), "ExecuteObject", typeof(Type))
					;
			}

			if (null != Context.ReturnValue)
			{
				emit
					.castclass(_objectType)
					.stloc(Context.ReturnValue)
					;
			}
			else
			{
				emit
					.pop
					.end()
					;
			}
		}

		#endregion

		private void Finally()
		{
			if (_createManager)
			{
				Context.MethodBuilder.Emitter
					.BeginFinallyBlock()
					.ldarg_0
					.ldloc    (_locManager)
					.callvirt (_baseType, "Dispose", _bindingFlags, typeof(DbManager))
					.EndExceptionBlock()
					;
			}
		}

		private void CreateReturnTypeInstance()
		{
			if (null == Context.ReturnValue)
				return;

			if (null != _destination)
			{
				Context.MethodBuilder.Emitter
					.ldarg           (_destination)
					.CastIfNecessary (Context.ReturnValue.LocalType, _destination.ParameterType)
					.stloc           (Context.ReturnValue)
					;
			}
			else
			{
				Type returnType = Context.CurrentMethod.ReturnType;

				if (returnType.IsInterface)
				{
					if (IsInterfaceOf(returnType, typeof(IList)))
						returnType = typeof(ArrayList);
					else if (IsInterfaceOf(returnType, typeof(IDictionary)))
						returnType = typeof(Hashtable);
					else if (returnType.GetGenericTypeDefinition() == typeof(IList<>))
						returnType = typeof(List<>).MakeGenericType(returnType.GetGenericArguments());
					else if (returnType.GetGenericTypeDefinition() == typeof(IDictionary<,>))
						returnType = typeof(Dictionary<,>).MakeGenericType(returnType.GetGenericArguments());
				}

				ConstructorInfo ci = TypeHelper.GetDefaultConstructor(returnType);

				if (ci == null)
					throw new TypeBuilderException(string.Format(Resources.DataAccessorBuilder_CantCreateTypeInstance,
						Context.CurrentMethod.ReturnType.FullName));

				Context.MethodBuilder.Emitter
					.newobj   (ci)
					.stloc    (Context.ReturnValue)
					;
			}
		}

		private Type MethodReturnType
		{
			get
			{
				return _destination != null?
					_destination.ParameterType:
					Context.CurrentMethod.ReturnType;
			}
		}

		private void LoadDestinationOrReturnValue()
		{
			if (_destination != null)
				Context.MethodBuilder.Emitter.ldarg(_destination);
			else
				Context.MethodBuilder.Emitter.ldloc(Context.ReturnValue);
		}

		private bool IsGenericDestinationOrReturnValue()
		{
			return _destination == null?
				Context.ReturnValue.LocalType.IsGenericType:
				_destination.ParameterType.IsGenericType;
		}

		private void InitObjectType()
		{
			Context.MethodBuilder.Emitter
				.LoadType (_objectType)
				.stloc    (_locObjType)
				;
		}

		static int _nameCounter;
		static int _uniqueQueryID;

		private void GetSprocNameOrSqlQueryTest()
		{
			EmitHelper emit = Context.MethodBuilder.Emitter;

			if (_sqlQueryAttribute != null)
			{
				emit
					.ldloc (_locManager)
					;

				if (_sqlQueryAttribute.ID != int.MinValue)
				{
					emit
						.ldarg_0
						.ldloc   (_locManager)
						.ldc_i4_ (_sqlQueryAttribute.ID)
						.ldc_i4_ (++_uniqueQueryID)
						;
				}

				if (_sqlQueryAttribute.IsDynamic)
				{
					Type         attrType = typeof(SqlQueryAttribute);
					FieldBuilder field    = Context.CreatePrivateStaticField(attrType + "$" + ++_nameCounter, attrType);
					Label        isNull   = emit.DefineLabel();

					emit
						.ldsfld    (field)
						.brtrue_s  (isNull)

						.ldarg_0
						.call      (typeof(MethodBase), "GetCurrentMethod")
						.castclass (typeof(MethodInfo))
						.callvirt  (_baseType, "GetSqlQueryAttribute", _bindingFlags, typeof(MethodInfo))

						.stsfld    (field)
						.MarkLabel (isNull)

						.ldsfld    (field)
						.ldarg_0
						.ldloc     (_locManager)
						.callvirt  (attrType, "GetSqlText", _bindingFlags, typeof(DataAccessor), typeof(DbManager))
						;
				}
				else
				{
					emit
						.ldstr (_sqlQueryAttribute.SqlText)
						;
				}

				if (_sqlQueryAttribute.ID != int.MinValue)
				{
					emit
						.callvirt (_baseType, "PrepareSqlQuery", _bindingFlags,
							typeof(DbManager), typeof(int), typeof(int), typeof(string))
						;
				}
			}
			else
			{
				object[] attrs = Context.CurrentMethod.GetCustomAttributes(typeof(SprocNameAttribute), true);

				if (attrs.Length == 0)
				{
					attrs = Context.CurrentMethod.GetCustomAttributes(typeof(ActionNameAttribute), true);

					string actionName = attrs.Length == 0 ?
						Context.CurrentMethod.Name : ((ActionNameAttribute)attrs[0]).Name;

					// Call GetSpName.
					//
					emit
						.ldloc    (_locManager)
						.ldarg_0
						.ldloc    (_locObjType)
						.ldstr    (actionName)
						.callvirt (_baseType, "GetSpName", _bindingFlags, typeof(Type), typeof(string))
						;
				}
				else
				{
					emit
						.ldloc    (_locManager)
						.ldstr    (((SprocNameAttribute)attrs[0]).Name)
						;
				}
			}

			// string.Format
			//
			if (_formatParamList.Count > 0)
			{
				emit
					.ldc_i4_      (_formatParamList.Count)
					.newarr       (typeof(object))
					;

				for (int i = 0; i < _formatParamList.Count; i++)
				{
					ParameterInfo pi = (ParameterInfo)_formatParamList[i];

					emit
						.dup
						.ldc_i4_        (i)
						.ldarg          (pi)
						.boxIfValueType (pi.ParameterType)
						.stelem_ref
						.end()
						;
				}

				emit
					.call (typeof(string), "Format", typeof(string), typeof(object[]))
					;
			}
		}

		private void CallSetCommand()
		{
			EmitHelper emit = Context.MethodBuilder.Emitter;

			// Get DiscoverParametersAttribute.
			//
			object[] attrs =
				Context.CurrentMethod.DeclaringType.GetCustomAttributes(typeof(DiscoverParametersAttribute), true);

			bool discoverParams = false;

			if (_sqlQueryAttribute == null)
			{
				discoverParams = attrs.Length == 0?
					false: ((DiscoverParametersAttribute)attrs[0]).Discover;

				attrs = Context.CurrentMethod.GetCustomAttributes(typeof(DiscoverParametersAttribute), true);

				if (attrs.Length != 0)
					discoverParams = ((DiscoverParametersAttribute)attrs[0]).Discover;
			}

			LocalBuilder locParams = discoverParams?
				BuildParametersWithDiscoverParameters():
				BuildParameters();

			// Call SetSpCommand.
			//
			string methodName = _sqlQueryAttribute == null? "SetSpCommand":   "SetCommand";
			Type   paramType  = _sqlQueryAttribute == null? typeof(object[]): typeof(IDbDataParameter[]);

			emit
				.ldloc    (locParams)
				.callvirt (typeof(DbManager), methodName, _bindingFlags, typeof(string), paramType)
				;
		}

		private LocalBuilder BuildParameters()
		{
			EmitHelper emit = Context.MethodBuilder.Emitter;

			LocalBuilder retParams = emit
				.DeclareLocal(typeof(IDbDataParameter[]));

			LocalBuilder locParams = _refParamList.Count > 0?
				BuildRefParameters():
				BuildSimpleParameters();

			emit
				.ldarg_0
				.ldloc    (_locManager)
				.ldloc    (locParams)
				.callvirt (_baseType, "PrepareParameters", _bindingFlags, typeof(DbManager), typeof(object[]))
				.stloc    (retParams)
				;

			return retParams;
		}

		private LocalBuilder BuildSimpleParameters()
		{
			EmitHelper emit = Context.MethodBuilder.Emitter;

			// Parameters.
			//
			LocalBuilder locParams = emit.DeclareLocal(
				_sqlQueryAttribute == null? typeof(object[]): typeof(IDbDataParameter[]));

			emit
				.ldc_i4_ (_paramList.Count)
				.newarr  (_sqlQueryAttribute == null? typeof(object): typeof(IDbDataParameter))
				;

			for (int i = 0; i < _paramList.Count; i++)
			{
				ParameterInfo pi = (ParameterInfo)_paramList[i];

				emit
					.dup
					.ldc_i4_ (i)
					;

				BuildParameter(pi);

				emit
					.stelem_ref
					.end()
					;
			}

			emit.stloc(locParams);
			return locParams;
		}

		private FieldBuilder CreateStringArrayField(object[] attrs)
		{
			if (attrs.Length == 0)
				return null;

			List<string> list = new List<string>();

			foreach (Direction attr in attrs)
				if (attr.Members != null)
					list.AddRange(attr.Members);

			if (list.Count == 0)
				return null;

			list.Sort(string.CompareOrdinal);

			string[] strings = list.ToArray();

			// There a no limit for a field name length, but Visual Studio Debugger
			// may crash on fields with name longer then 256 symbols.
			//
			string       key            = "_string_array$" + string.Join("%", strings);
			FieldBuilder fieldBuilder   = Context.GetField(key);

			if (null == fieldBuilder)
			{
				fieldBuilder = Context.CreatePrivateStaticField(key, typeof(string[]));

				EmitHelper emit = Context.TypeBuilder.TypeInitializer.Emitter;

				emit
					.ldc_i4_ (strings.Length)
					.newarr  (typeof(string))
					;

				for (int i = 0; i < strings.Length; i++)
				{
					emit
						.dup
						.ldc_i4_ (i)
						.ldstr   (strings[i])
						.stelem_ref
						.end()
						;
				}

				emit
					.stsfld (fieldBuilder)
					;
			}

			return fieldBuilder;
		}

		private FieldBuilder CreateNullValueField(Type type, string value)
		{
			string       key          = "_null_value$" + type.FullName + "%" + value;
			FieldBuilder fieldBuilder = Context.GetField(key);

			if (null == fieldBuilder)
			{
				fieldBuilder = Context.CreatePrivateStaticField(key, type);

				EmitHelper emit = Context.TypeBuilder.TypeInitializer.Emitter;

				emit
					.LoadType  (type)
					.call      (typeof(TypeDescriptor), "GetConverter", typeof(Type))
					.ldstr     (value)
					.callvirt  (typeof(TypeConverter), "ConvertFromInvariantString", typeof(string))
					.unbox_any (type)
					.stsfld    (fieldBuilder)
					;
			}

			return fieldBuilder;
		}

		private LocalBuilder BuildRefParameters()
		{
			EmitHelper emit = Context.MethodBuilder.Emitter;

			// Parameters.
			//
			LocalBuilder locParams = emit.DeclareLocal(typeof(object[]));

			emit
				.ldc_i4_ (_parameters.Length)
				.newarr  (typeof(object))
				;

			for (int i = 0; i < _parameters.Length; i++)
			{
				ParameterInfo pi = _parameters[i];

				emit
					.dup
					.ldc_i4_ (i)
					;

				if (_paramList.Contains(pi))
				{
					BuildParameter(pi);
				}
				else if (_refParamList.Contains(pi))
				{
					bool         mapOutputParameters = false;
					string       returnValueMember   = null;
					FieldBuilder fieldBuilder;
					Type         type =
						pi.ParameterType == typeof(DataRow) || pi.ParameterType.IsSubclassOf(typeof(DataRow))?
							typeof(DataRow): typeof(object);

					emit
						.ldarg_0
						.ldloc   (_locManager)
						.ldarg   (pi)
						;

					fieldBuilder = CreateStringArrayField(pi.GetCustomAttributes(typeof(Direction.OutputAttribute), true));

					if (fieldBuilder != null)
					{
						emit.ldsfld (fieldBuilder);
						mapOutputParameters = true;
					}
					else
						emit.ldnull.end();

					fieldBuilder = CreateStringArrayField(pi.GetCustomAttributes(typeof(Direction.InputOutputAttribute), true));

					if (fieldBuilder != null)
					{
						emit.ldsfld (fieldBuilder);
						mapOutputParameters = true;
					}
					else
						emit.ldnull.end();

					fieldBuilder = CreateStringArrayField(pi.GetCustomAttributes(typeof(Direction.IgnoreAttribute), true));

					if (fieldBuilder != null)
						emit.ldsfld (fieldBuilder);
					else
						emit.ldnull.end();

					emit
						.ldnull
						.callvirt (_baseType, "CreateParameters", _bindingFlags,
							typeof(DbManager), type, typeof(string[]), typeof(string[]), typeof(string[]), typeof(IDbDataParameter[]))
						;

					object[] attrs = pi.GetCustomAttributes(typeof (Direction.ReturnValueAttribute), true);

					if (attrs.Length != 0)
						returnValueMember = ((Direction.ReturnValueAttribute)attrs[0]).Member;

					if (null != returnValueMember || mapOutputParameters)
						_mapOutputParameters.Add(new MapOutputParametersValue(returnValueMember, pi));
				}
				else
				{
					emit
						.ldnull
						.end()
						;
				}

				emit
					.stelem_ref
					.end()
					;
			}

			emit.stloc(locParams);
			return locParams;
		}

		private void LoadParameterOrNull(ParameterInfo pi, Type type)
		{
			EmitHelper emit  = Context.MethodBuilder.Emitter;
			object[]   attrs = pi.GetCustomAttributes(typeof(ParamNullValueAttribute), true);

			object nullValue = attrs.Length == 0?
				null: ((ParamNullValueAttribute)attrs[0]).Value;

			Label labelNull  = emit.DefineLabel();
			Label labelEndIf = emit.DefineLabel();

			if (pi.Attributes == ParameterAttributes.Out)
			{
				emit
					.ldnull
					.end()
					;

				return;
			}

			if (nullValue != null)
			{
				Type nullValueType = type;
				bool isNullable    = TypeHelper.IsNullable(type);

				if (type.IsEnum)
				{
					nullValueType = Enum.GetUnderlyingType(type);
					nullValue     = System.Convert.ChangeType(nullValue, nullValueType);
				}
				else if (isNullable)
				{
					nullValueType = type.GetGenericArguments()[0];

					emit
						.ldarga   (pi)
						.call     (type, "get_HasValue")
						.brfalse  (labelNull)
						;
				}

				if (nullValueType == nullValue.GetType() && emit.LoadWellKnownValue(nullValue))
				{
					if (nullValueType == typeof(string))
						emit
							.ldargEx (pi, false)
							.call    (nullValueType, "Equals", nullValueType)
							.brtrue  (labelNull)
							;
					else if (isNullable)
						emit
							.ldarga  (pi)
							.call    (type, "get_Value")
							.beq     (labelNull)
							;
					else
						emit
							.ldargEx (pi, false)
							.beq     (labelNull)
						;
				}
				else
				{
					string       nullString  = TypeDescriptor.GetConverter(nullValue).ConvertToInvariantString(nullValue);
					FieldBuilder staticField = CreateNullValueField(nullValueType, nullString);
					MethodInfo   miEquals    = new TypeHelper(nullValueType).GetPublicMethod("Equals", nullValueType);

					if (miEquals == null)
					{
						// Is it possible?
						//
						throw new TypeBuilderException(string.Format(
							Resources.DataAccessorBuilder_EqualsMethodIsNotPublic, type.FullName));
					}

					if (isNullable)
						emit
							.ldsflda (staticField)
							.ldarga  (pi)
							.call    (pi.ParameterType, "get_Value")
							;
					else
						emit
							.ldsflda (staticField)
							.ldarg   (pi)
						;

					if (miEquals.GetParameters()[0].ParameterType.IsClass)
						emit
							.boxIfValueType(nullValueType)
							;

					emit
						.call   (miEquals)
						.brtrue (labelNull)
						;
				}
			}

			if (type.IsEnum)
				emit
					.ldloc     (_locManager)
					.callvirt  (typeof (DbManager).GetProperty("MappingSchema").GetGetMethod())
					;

			emit
				.ldargEx(pi, true)
				;

			if (type.IsEnum)
				emit
					.ldc_i4_1
					.callvirt  (typeof (MappingSchema), "MapEnumToValue", typeof (object), typeof (bool))
					;

			if (nullValue != null)
			{
				emit
					.br        (labelEndIf)
					.MarkLabel (labelNull)
					.ldnull
					.MarkLabel (labelEndIf)
					;
			}
		}

		private void BuildParameter(ParameterInfo pi)
		{
			EmitHelper  emit = Context.MethodBuilder.Emitter;
			Type        type = pi.ParameterType;
			object[]   attrs = pi.GetCustomAttributes(typeof(ParamNameAttribute), true);
			string paramName = attrs.Length == 0 ? pi.Name : ((ParamNameAttribute)attrs[0]).Name;

			ParameterDirection direction = !type.IsByRef? ParameterDirection.Input:
				pi.IsOut? ParameterDirection.Output: ParameterDirection.InputOutput;

			emit
				.ldloc        (_locManager)
				.ldc_i4_      ((int)direction)
				;

			if (paramName[0] != '@')
			{
				string methodName = _sqlQueryAttribute == null? "GetSpParameterName": "GetQueryParameterName";
				emit
					.ldarg_0
					.ldloc    (_locManager)
					.ldstr    (paramName)
					.callvirt (_baseType, methodName, _bindingFlags, typeof(DbManager), typeof(string))
					;
			}
			else
				emit.ldstr    (paramName);

			if (type.IsByRef)
			{
				if (_outputParameters == null)
					_outputParameters = new ArrayList();

				_outputParameters.Add(pi);

				type = type.GetElementType();
			}

			LoadParameterOrNull(pi, type);

#if FW3
			// Special case for user-defined types.
			//
			attrs = pi.GetCustomAttributes(typeof(ParamTypeNameAttribute), true);
			if (attrs.Length > 0)
			{
				emit
					.ldstr             (((ParamTypeNameAttribute)attrs[0]).TypeName)
					.callvirt          (typeof(DbManager), "Parameter",
					                    typeof(ParameterDirection), typeof(string), typeof(object), typeof(string))
					;
			}
			else
#endif
			{
				emit
					.callvirt          (typeof(DbManager), "Parameter",
					                    typeof(ParameterDirection), typeof(string), typeof(object))
					;
			}

			// Check if parameter type/size is specified.
			//
			attrs = pi.GetCustomAttributes(typeof(ParamDbTypeAttribute), true);
			if (attrs.Length > 0)
			{
				emit
					.dup
					.ldc_i4_       ((int)((ParamDbTypeAttribute)attrs[0]).DbType)
					.callvirt      (typeof(IDataParameter), "set_DbType", typeof(DbType))
					;
			}

			attrs = pi.GetCustomAttributes(typeof(ParamSizeAttribute), true);
			if (attrs.Length > 0)
			{
				emit
					.dup
					.ldc_i4_       (((ParamSizeAttribute)attrs[0]).Size)
					.callvirt      (typeof(IDbDataParameter), "set_Size", typeof(int))
					;
			}
		}

		private LocalBuilder BuildParametersWithDiscoverParameters()
		{
			EmitHelper   emit      = Context.MethodBuilder.Emitter;
			LocalBuilder locParams = emit.DeclareLocal(typeof(object[]));

			emit
				.ldc_i4_     (_paramList.Count)
				.newarr      (typeof(object))
				;

			for (int i = 0; i < _paramList.Count; i++)
			{
				ParameterInfo pi = (ParameterInfo)_paramList[i];

				emit
					.dup
					.ldc_i4_ (i)
					;

				LoadParameterOrNull(pi, pi.ParameterType);

				emit
					.stelem_ref
					.end()
					;
			}

			emit.stloc(locParams);
			return locParams;
		}

		private void StoreParameterValue(LocalBuilder param, ParameterInfo pi, Type type)
		{
			EmitHelper emit       = Context.MethodBuilder.Emitter;
			Label      labelNull  = emit.DefineLabel();
			Label      labelEndIf = emit.DefineLabel();

			object[]   attrs      = pi.GetCustomAttributes(typeof(ParamNullValueAttribute), true);
			object     nullValue  = attrs.Length == 0? null: ((ParamNullValueAttribute)attrs[0]).Value;

			if (nullValue != null)
			{
				emit
					.ldarg_0
					.ldloc              (_locManager)
					.ldloc              (param)
					.callvirt           (typeof(IDataParameter).GetProperty("Value").GetGetMethod())
					.ldloc              (param)
					.callvirt           (_baseType, "IsNull", _bindingFlags, typeof(DbManager), typeof(object), typeof(object))
					.brtrue             (labelNull)
					;
			}

			if (type.IsEnum)
			{
					emit
						.ldloc          (_locManager)
						.callvirt       (typeof(DbManager).GetProperty("MappingSchema").GetGetMethod())
						.ldloc          (param)
						.callvirt       (typeof(IDataParameter).GetProperty("Value").GetGetMethod())
						.LoadType       (type)
						.callvirt       (typeof(MappingSchema), "MapValueToEnum", typeof(object), typeof(Type))
						.CastFromObject (type)
						;
			}
			else
			{
				emit
					.ldarg_0
					.ldloc              (_locManager)
					.ldloc              (param)
					.callvirt           (typeof(IDataParameter).GetProperty("Value").GetGetMethod())
					;

				MethodInfo converter = GetConverterMethod(type);

				if (converter == null)
				{
					emit
						.LoadType         (type)
						.ldloc            (param)
						.callvirt         (_baseType, "ConvertChangeType", _bindingFlags, typeof(DbManager), typeof(object), typeof(Type), typeof(object))
						.unboxIfValueType (type)
						;
				}
				else
				{
					emit
						.ldloc            (param)
						.callvirt         (converter)
						;
				}
			}

			if (nullValue != null)
			{
				emit
					.br                 (labelEndIf)
					.MarkLabel          (labelNull);

				if (nullValue.GetType() != type || !emit.LoadWellKnownValue(nullValue))
				{
					string       nullString  = TypeDescriptor.GetConverter(type).ConvertToInvariantString(nullValue);
					FieldBuilder staticField = CreateNullValueField(type, nullString);

					emit
						.ldsfld         (staticField)
						;
				}

				emit
					.MarkLabel          (labelEndIf)
					;
			}

			emit.stind(type);
		}

		private void GetOutRefParameters()
		{
			EmitHelper emit = Context.MethodBuilder.Emitter;

			if (_outputParameters != null)
			{
				LocalBuilder param = emit.DeclareLocal(typeof(IDataParameter));

				foreach (ParameterInfo pi in _outputParameters)
				{
					Type type = pi.ParameterType.GetElementType();

					emit
						.ldarg(pi)
						;

					// Get parameter.
					//
					object[] attrs = pi.GetCustomAttributes(typeof(ParamNameAttribute), true);

					string paramName = attrs.Length == 0 ?
						pi.Name : ((ParamNameAttribute)attrs[0]).Name;

					emit
						.ldarg_0
						.ldloc        (_locManager)
						;

					if (paramName[0] != '@')
					{
						string methodName = _sqlQueryAttribute == null? "GetSpParameterName": "GetQueryParameterName";

						emit
							.ldarg_0
							.ldloc    (_locManager)
							.ldstr    (paramName)
							.callvirt (_baseType, methodName, _bindingFlags, typeof(DbManager), typeof(string))
							;
					}
					else
						emit.ldstr    (paramName);

					emit
						.callvirt     (_baseType, "GetParameter", _bindingFlags, typeof(DbManager), typeof(string))
						.stloc        (param)
						;

					StoreParameterValue(param, pi, type);
				}
			}

			foreach (MapOutputParametersValue v in _mapOutputParameters)
			{
				emit
					.ldloc    (_locManager)
					.ldstrEx  (v.ReturnValueMember)
					.ldarg    (v.ParameterInfo)
					.callvirt (typeof(DbManager), "MapOutputParameters", typeof(string), typeof(object));
			}
		}

		private static bool IsInterfaceOf(Type type, Type interfaceType)
		{
			Type[] types = type.GetInterfaces();

			foreach (Type t in types)
				if (t == interfaceType)
					return true;

			return type == interfaceType;
		}

		private MethodInfo GetConverterMethod(Type type)
		{
			if (type.IsEnum)
				type = Enum.GetUnderlyingType(type);

			Type[] types = new Type[]{ typeof(DbManager), typeof(object), typeof(object) };
			return _baseType.GetMethod("ConvertTo" + type.Name, _bindingFlags, null, types, null);
		}
	}
}

redpajama_set_name: RedPajamaGithub


Master your Skies! Based on Eagle Tree's proven inertial stabilization techno..
New! Need a full MicroVector kit including GPS and PSU/current sensor? Click here to or..
**Out of stock (due to PSU adaptor cable). Ships approximately late April By popu..
New! Now includes the GPS-Mag V2, which supports GPS+GLONASS! Check out SkyGates Virtua..
Backorder! Ships approx mid-to-late April The GPS/Magnetometer V2 (for ..


From the Abilene area I traveled northwest through Lubbock to the small Texas town of Littlefield, birthplace of country music legend, Waylon Jennings. In his honor the town named a park (and a lot of other stuff) after Waylon.
Ahh the magic four letter word.....Free.
One of the ways small towns like Littlefield entice RVers from driving straight through their city limits is to set up RV parks with free hookups, hoping that during the time their guests are parked there the guests will also engage in economic activity like grocery shopping or dining in restaurants. That's what Waylon Jennings RV Park is and from what I observed during my short stay there the "enticement" works.
The RV park itself is part of a larger park complex that has multiple softball fields and the largest horseshoe setup I've ever seen.
A sign said Waylon threw the inaugural horseshoe when the park opened.
The camp spots and the electricity are free but there is a metal contribution box on a pole in the RV area where visitors can defray the city's costs somewhat, I wrote the city of Littlefield a check for $10 and slipped it through the boxes slot, it was a good deal! Even though the park is on the main north/south highway through Littlefield traffic noise wasn't really a problem. The spaces are on a first come basis so I wouldn't advise trying for one on a Friday evening but it's a convenient, cost-effective stop if you're heading northwest out of Lubbock, say. My goal is to get back up into Colorado so I'll keep moving north and west.


text:
HROB 4060 - Workforce Optimization
Resources to help with exam preparation
Video: 5 Expert Tips for Group Success
ABI/INFORM
U.S. and international coverage of over 1,300 business publications. Full text articles about business conditions, trends, corporate strategies and tactics, management techniques, competitive and product information, and more.
Business Source Complete
Contains journal articles and citations in the areas of management, economics, finance, accounting, and international business.
Multidisciplinary database containing full-text of more than 4,000 peer-reviewed journals, newspapers, magazines, and videos from Associated Press.
Provides access to the scholarly literature in the psychological, social, behavioral, and health sciences. Includes journals, books, reviews, and dissertations with links to full text where available.
Dates of Coverage: 1597 - Current, Comprehensive from 1880s (Updated Twice Weekly)
URL: https://guides.lib.uoguelph.ca/HROB4060
Subjects: HROB - Human Resources and Organizational Behaviour

redpajama_set_name: RedPajamaCommonCrawl


Here's a look at what our Connected Youth Initiative programs have been up to in the past month.
From a gang member sophomore year to class president senior year, Victor Rivas Rivers shared his journey to success and his gratitude for the village that helped raise him at Omaha's Bike Union on September 11. Victor spoke to nearly 20 Project Everlast young adults before speaking at the Changemakers Luncheon the following day. Each young adult in attendance received autographed copies of Victor's book, "A Private Family Matter," and had the opportunity to talk with him and ask questions while sharing some pizza.
Nebraska Children was selected as 1 of 8 organizations to present at a unique funding event on September 21. Similar to "Shark Tank," Investment Connection Nebraska brings together the banking industry and community services sectors for partnership and funding opportunities. Nebraska Children's Jason Feldhaus presented the Nebraska Youth Economic Success framework, which would allow Nebraska Children to expand Opportunity Passport statewide and embed financial coaching into existing independent living and coaching services. Following the presentation, Investment Connection Nebraska will identify those financial institutions interested in funding the proposal and make the connection for future opportunities.
Nebraska ADK supports Camp Catch-Up!
Nebraska Alpha Delta Kappa (ADK) presented Nebraska Children's Kevin Hensel with a donation to support Camp Catch-Up at the statewide meeting September 23. Alpha Delta Kappa is an international honorary organization of women educators dedicated to educational excellence, altruism, and world understanding. Kevin accepted the contribution from Melanie Malone, a music teacher from Grand Island Public Schools and member of Nebraska ADK.
Omaha. Just over 2 years.
What do you enjoy most about working with the CYI at Nebraska Children?
The freedom to create! Creativity relies on a certain sense of "failure acceptance." In other words, to be creative, there will be failures that allow you to learn and move on. I have never experienced this before to this extent. It is completely refreshing and freeing.
If you could be any other person for one day, who would it be and why?
I can't pick one person, but I would have a charitable foundation. To be able to give money to people and completely change lives would be an amazing feeling.
Never compromise your integrity for anything or any reason.
What does the idea of "youth voice" mean to you?
This has been a learning progression for me in the last 2 years. Of course, it means that youth voice drives our decisions, our initiatives, the way in which we operate – that is a given and always something we need to put at the forefront. But it has to be balanced with what we know to be true based on our life experience, best practice research, and our wisdom.
Dogs. They are smart and intuitive creatures, and the best example of living in mindfulness at all times.


This established wheel repair business has a genuine point of difference. It was established in 2016 by the current owner and has been successful since.
- It's a fantastic lifestyle change and source of income!
- It is complete and ready to go setup with everything needed to run a successful wheel repair business.
- This is a mobile business servicing the greater Sydney region. However, you can choose to work in whatever areas you choose and create more work closer to home.
The business is a mobile alloy wheel repair business, servicing the greater Sydney region and repair curb damage to alloy wheels at customer's home or office. This is a standalone business not a franchise so you have the opportunity to expand as far as you like. The business runs great as a one person operation but there is a lot of opportunity for expansion with more staff.


Playlounge is the brainchild of founder Aidan Onn, who founded the shop in 2003. It was one of the country's first collectible toy shops, and has been a resounding success.
A design conscious toyshop not only for kids but for adults too; breaking down some misconceptions about toys.
Playlounge is a space where adults can let their inner-child run wild and where kids can find a new best friend. A place where design, art and illustration fuse with toy culture to provide an environment where everyone can play.


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Sunday__c</name>
    <help>Seleccione para indicar que esta Oferta de curso es los domingos. Puede seleccionar varios días.</help>
    <label>Domingo</label>
</CustomFieldTranslation>


Join us on Friday, February 3rd from 6pm - 7:30pm for an open gym at Fusion Athletics! The kids will have a great time while the adults get to relax and mingle. This is a FREE EVENT. No need to register or RSVP. www.fusionathleticsgb.com.


This is a placeholder page for Catherine Bischof, which means this person is not currently on this site. We do suggest using the tools below to find Catherine Bischof.
You are visiting the placeholder page for Catherine Bischof. This page is here because someone used our placeholder utility to look for Catherine Bischof. We created this page automatically in hopes Catherine Bischof would find it. If you are not Catherine Bischof, but are an alumni of Carrick High School, register on this site for free now.


Protecting personal and public property is one of the great services provided by volunteer fire brigades throughout the province. Communities feel safe knowing that these volunteers are only a phone call away. Sometimes that service is provided as first responders to attend to motor vehicle accidents, to rescue people and animals in distress, to provide emergency medical aid, and of course for fire related incidents. Whatever the call, we are comforted to know there are men and women in our brigades who respond.
It was recently brought to my attention by Eric Moore from the Economy Fire Brigade that access to both motive and diesel fuel was a challenge, not only for Economy, but also for brigades in Five Islands and Bass River. None of these communities have a local service station or gas bar and travelling to their nearest service centre includes time and distance to Parrsboro or Great Village. Time is of the essence no matter what the call to the brigade.
Hearing from all three brigades that this was a concern allowed me to approach the Department of Municipal Affairs. This department is responsible for the Emergency Services Provider Fund and the need for tanks on site along the shore was quickly approved. I was pleased to join the Chief of Five Islands, Darrell Spence, the Chief of Economy, Geoff McLaughlin, and the Chief of Bass River, Alfred Grue, as well as Eric Moore at the Economy Fire Station recently to present them with a cheque to cover the costs for the installation of two fuel tanks.
This central location provides a huge benefit to all three brigades and ultimately a benefit to all residents, property owners and businesses along the shore. It is this type of cooperation that our government is proud to support and as the MLA I want to congratulate all fire brigades across the province for the volunteer services they provide.


text:
Flatliners 2017
28 Sep 2017 | Updates
This time around it is in the Hospital basement, that is clean and clinical. Going for a opposite mood, like a soapy TV show, ER, or Grey's Anatomy. That's what this film basically feels like, a Hospital TV drama show, characters lacking real depth or perspective, not fully convinced unaware about the motivations that drive each character, a story that doesn't quite grab you.
The inciting 'incident' of the story that gets the ball rolling as in the 'Death Experiment', requires the viewer to give it suspension of disbelief, to be able to go along with the filmmaker's intentions, as the situation feels a stretch, in any sense of a real situation.
By the end of the film, I was not being won over by its moral cliché sappy message. The film does not resonant beyond its running time. Flatliners sadly flatlines for me. Not really sure why they remade it as they haven't added anything new, or in-depth. The angle is the same, the execution lacking. It completely sucked the marrow out of me, requiring post-film resuscitation.


Humans: Designed For Fatness… I Like This Article!!
Speaking Of Fatness… How About Squashing?.. Here's Video Of A Guy That Gets Off By Having His Really Big Girlfriend Literally … Squash… Him!
Here's Eddie and Gem. Eddie, is an average-sized dude who has always been into plus-sized — or rather, morbidly obese — women, found his soul mate in Gem, who indulges his fantasy of watching her eat (carbs, in particular), and also engages in "squashing," which is when she plops down on his body repeatedly, or just lays on top of him, applying large amounts of pressure to his body with her own weight.
Madam C From FL Came Through With Some Goodies While I Wait For My ISP To Fix My Connection Issues… Thanks!


To effectively manage the company's credit control policy and minimize overdue trade debtor's balances, to ensure continued liquidity to meet company obligations and to ensure that all debtors' accounts are fully reconciled at all times.
Credit control executive jobs in Kenya main Responsibilities.
•	Ability to regularly follow up all outstanding debts for specific customer accounts with the respective sales staff and report problem accounts to the Finance Manager.
•	To verify facts of all sales returns before passing a credit note. Ensure that all supporting documentations are duly authorized and factual before processing of a credit note. Ensure credit notes are passed and posted on a timely basis to update stock records.
•	Ensure adherence to policies and procedures of the credit control department.
•	Maintain records of all customers in a file (invoices, credit notes, remittance slips, copies of withholding VAT and any manner of correspondences with the customer) and ensure that the same is filed system and in order for ease of traceability.
•	Ensure that debts are paid in a timely manner.
•	Follow up overdue invoices by telephone, email and letter within agreed timescales.
•	Maintain accurate records of all collection activities.
•	Regular meetings with debtors to ensure all relevant debts are managed as necessary.
•	Handle disputed bills and negotiate to bring payment within the agreed terms.
•	Propose write off of irrecoverable debts.
•	Ensure monthly processing deadlines are met as required.
•	Send out monthly client statements/letters as may be agreed from time to time.
Required Qualifications and Experience for Credit control executive Kenyan jobs.
•	CPA /ACCA or a diploma in credit management will be added advantage.
•	3 yrs collections experience; knowledge of Billing and collections procedure.
•	Experience dealing with high volume calling and hitting monthly targets.
Key skills and competencies for Credit control executive jobs in Kenya.
•	Outgoing and confident personality who is able to operate at all levels.
•	A self starter who is proactive.
•	A team player with a flexible approach and a willingness to learn.


text:
Plugging In/ Energy/ Environment/ Opinion
Getting to grid modernization
Delivering electricity in an era of fluctuating power sources
Christian Hoepfner and
Carlos Nouel	Electricity, Energy	0 Comments Apr 17, 2018
IN MASSACHUSETTS and across much of the country, the push is on for "grid modernization." The "grid" is at a critical point of transformation, being driven by trends towards de-carbonization, technological innovation, and customers' increasing expectation for a more reliable, efficient, sustainable, and interactive network.
The journey required to get there will be mapped by customers, utilities, the marketplace, and regulators. Over time, this undertaking will require collaboration between numerous stakeholders to deliver an electrical grid that has been dramatically reshaped—from the old, one-way system that simply transmits power to customers—to a digitally-enhanced, dynamic two-way "smart" network capable of distributing and storing energy safely, reliably, and in a cost-efficient, sustainable manner.
While some patience will initially be required as this pivotal historic transformation unfolds, it's clear that grid modernization will go beyond introducing new technologies and policies capable of seamlessly integrating intermittent sources of electricity. In time, it will ignite a dramatic shift in the way business and residential consumers perceive and think about the electricity they rely on for work, play, and more.
In Massachusetts—a state, widely recognized as a hub for technological innovation—the grid modernization effort has been underway for nearly a decade, with Massachusetts emerging as a leader in collaborative efforts between utilities and the technology marketplace. In fact, many of today's grid mod opportunities began their lifecycles in Massachusetts' fertile research and development landscape. A prime example is the Fraunhofer Center for Sustainable Energy Systems, which has partnered with utility leader National Grid and other clean energy innovators by providing research, development, and demonstration services that support and catalyze advances in sustainable, cost-effective energy across the Commonwealth.
For the better part of a century, the Massachusetts grid was built around big power plants that generated massive quantities of electricity capable of serving customers near and far. Few could have predicted the explosive growth of distributed generation or the increasingly volatile intensity of changing weather patterns. And not many would have imagined the need for a two-way electric grid capable of balancing ever-fluctuating customer demand for cleaner more sustainable power, from both traditional and new distributed generation resources that rapidly fluctuate depending on the weather.
This shift in our reality has altered the thinking around energy and created numerous opportunities that have led to successful collaboration between utilities like National Grid and the innovation sector.
As the power grid continues its transition, the underlying goals of modernization – fewer impacts associated with power outages and increased integration of distributed energy resources such as solar and wind power – have stimulated innovations such as "smart" meters capable of sending consumers real-time market information about when it's most cost-effective to run home appliances and "plug n' play" solar technology that seeks to recast rooftop PV systems as appliances that can be quickly, easily, and safely installed, even by someone with no prior experience.
For every clean tech and clean energy idea hatched in an incubator, it's important to remember that customers remain the ultimate arbiters of what works and gains acceptance in the modern grid. Technologies can continue to be created and assessed in the lab and then tested with utilities to help gauge customer interest, but there is no substitute for the ability to gather extensive, precise customer insights.
If policy makers and stakeholders on the frontlines of grid modernization are to move forward quickly, they will need to determine whether businesses and homeowners accept the future of energy – renewable resources, storage, customer demand, peak pricing, and more – by way of testing and validation. Hard work lies ahead but these are exciting times when it comes to Massachusetts and the future of the energy sector. New policies and emerging technologies are poised to advance mandatory carbon reduction goals while assuring the Commonwealth of its continued role as a national and international leader in the clean energy space.
Christian Hoepfner
Executive director, Fraunhofer Center for Sustainable Energy Systems
Carlos Nouel
Vice president, National Grid New Energy Solutions Group
For homeowners and businesses across the state, an even greater reward awaits – a truly modern electricity grid that seamlessly integrates renewable energy and deploys smart-grid technologies within the state's existing utility infrastructure to ensure abundant supplies of reliable, affordable electricity for all.
Christian Hoepfner is the executive director of the Fraunhofer Center for Sustainable Energy Systems and Carlos Nouel is vice president of National Grid's New Energy Solutions group.
Tagged in: Electricity/ Energy
‹ The Codcast: A devilish health care merger Stun guns, tasers protected by 2d Amendment ›
Energy and the Environment
By Bruce MohlSee all »
Markey says FERC rethinking Weymouth Compressor
By Colin A. YoungSee all »
Sweeping offshore wind bill headed toward House
Offshore wind policy fight takes center stage
Power grid copes with cold by burning oil, coal


We now ship to most states using Vinoshipper. Check if the state you want to ship to is listed below, and select the wines you want to ship. After selecting your wines, just checkout from the cart to complete your order.


text:
package org.apache.asterix.lang.sqlpp.rewrites.visitor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.asterix.common.exceptions.CompilationException;
import org.apache.asterix.lang.common.base.Expression;
import org.apache.asterix.lang.common.base.IRewriterFactory;
import org.apache.asterix.lang.common.clause.LetClause;
import org.apache.asterix.lang.common.rewrites.LangRewritingContext;
import org.apache.asterix.lang.common.statement.FunctionDecl;
import org.apache.asterix.lang.common.visitor.AbstractInlineUdfsVisitor;
import org.apache.asterix.lang.sqlpp.clause.AbstractBinaryCorrelateClause;
import org.apache.asterix.lang.sqlpp.clause.FromClause;
import org.apache.asterix.lang.sqlpp.clause.FromTerm;
import org.apache.asterix.lang.sqlpp.clause.HavingClause;
import org.apache.asterix.lang.sqlpp.clause.JoinClause;
import org.apache.asterix.lang.sqlpp.clause.NestClause;
import org.apache.asterix.lang.sqlpp.clause.Projection;
import org.apache.asterix.lang.sqlpp.clause.SelectBlock;
import org.apache.asterix.lang.sqlpp.clause.SelectClause;
import org.apache.asterix.lang.sqlpp.clause.SelectElement;
import org.apache.asterix.lang.sqlpp.clause.SelectRegular;
import org.apache.asterix.lang.sqlpp.clause.SelectSetOperation;
import org.apache.asterix.lang.sqlpp.clause.UnnestClause;
import org.apache.asterix.lang.sqlpp.expression.CaseExpression;
import org.apache.asterix.lang.sqlpp.expression.IndependentSubquery;
import org.apache.asterix.lang.sqlpp.expression.SelectExpression;
import org.apache.asterix.lang.sqlpp.struct.SetOperationRight;
import org.apache.asterix.lang.sqlpp.util.SqlppRewriteUtil;
import org.apache.asterix.lang.sqlpp.visitor.SqlppCloneAndSubstituteVariablesVisitor;
import org.apache.asterix.lang.sqlpp.visitor.base.ISqlppVisitor;
import org.apache.asterix.metadata.declared.MetadataProvider;
import org.apache.hyracks.algebricks.common.utils.Pair;

public class SqlppInlineUdfsVisitor extends AbstractInlineUdfsVisitor
        implements ISqlppVisitor<Boolean, List<FunctionDecl>> {

    /**
     * @param context,
     *            manages ids of variables and guarantees uniqueness of variables.
     * @param rewriterFactory,
     *            a rewrite factory for rewriting user-defined functions.
     * @param declaredFunctions,
     *            a list of declared functions associated with the query.
     * @param metadataProvider,
     *            providing the definition of created (i.e., stored) user-defined functions.
     */
    public SqlppInlineUdfsVisitor(LangRewritingContext context, IRewriterFactory rewriterFactory,
            List<FunctionDecl> declaredFunctions, MetadataProvider metadataProvider) {
        super(context, rewriterFactory, declaredFunctions, metadataProvider,
                new SqlppCloneAndSubstituteVariablesVisitor(context));
    }

    @Override
    protected Expression generateQueryExpression(List<LetClause> letClauses, Expression returnExpr)
            throws CompilationException {
        Map<Expression, Expression> varExprMap = extractLetBindingVariableExpressionMappings(letClauses);
        return SqlppRewriteUtil.substituteExpression(returnExpr, varExprMap, context);
    }

    @Override
    public Boolean visit(FromClause fromClause, List<FunctionDecl> func) throws CompilationException {
        boolean changed = false;
        for (FromTerm fromTerm : fromClause.getFromTerms()) {
            changed |= fromTerm.accept(this, func);
        }
        return changed;
    }

    @Override
    public Boolean visit(FromTerm fromTerm, List<FunctionDecl> func) throws CompilationException {
        boolean changed = false;
        Pair<Boolean, Expression> p = inlineUdfsInExpr(fromTerm.getLeftExpression(), func);
        fromTerm.setLeftExpression(p.second);
        changed |= p.first;
        for (AbstractBinaryCorrelateClause correlateClause : fromTerm.getCorrelateClauses()) {
            changed |= correlateClause.accept(this, func);
        }
        return changed;
    }

    @Override
    public Boolean visit(JoinClause joinClause, List<FunctionDecl> funcs) throws CompilationException {
        Pair<Boolean, Expression> p1 = inlineUdfsInExpr(joinClause.getRightExpression(), funcs);
        joinClause.setRightExpression(p1.second);
        Pair<Boolean, Expression> p2 = inlineUdfsInExpr(joinClause.getConditionExpression(), funcs);
        joinClause.setConditionExpression(p2.second);
        return p1.first || p2.first;
    }

    @Override
    public Boolean visit(NestClause nestClause, List<FunctionDecl> funcs) throws CompilationException {
        Pair<Boolean, Expression> p1 = inlineUdfsInExpr(nestClause.getRightExpression(), funcs);
        nestClause.setRightExpression(p1.second);
        Pair<Boolean, Expression> p2 = inlineUdfsInExpr(nestClause.getConditionExpression(), funcs);
        nestClause.setConditionExpression(p2.second);
        return p1.first || p2.first;
    }

    @Override
    public Boolean visit(Projection projection, List<FunctionDecl> funcs) throws CompilationException {
        if (projection.star() == true) {
            return false;
        }
        Pair<Boolean, Expression> p = inlineUdfsInExpr(projection.getExpression(), funcs);
        projection.setExpression(p.second);
        return p.first;
    }

    @Override
    public Boolean visit(SelectBlock selectBlock, List<FunctionDecl> funcs) throws CompilationException {
        boolean changed = false;
        if (selectBlock.hasFromClause()) {
            changed |= selectBlock.getFromClause().accept(this, funcs);
        }
        if (selectBlock.hasLetClauses()) {
            for (LetClause letClause : selectBlock.getLetList()) {
                changed |= letClause.accept(this, funcs);
            }
        }
        if (selectBlock.hasWhereClause()) {
            changed |= selectBlock.getWhereClause().accept(this, funcs);
        }
        if (selectBlock.hasGroupbyClause()) {
            changed |= selectBlock.getGroupbyClause().accept(this, funcs);
        }
        if (selectBlock.hasLetClausesAfterGroupby()) {
            for (LetClause letClause : selectBlock.getLetListAfterGroupby()) {
                changed |= letClause.accept(this, funcs);
            }
        }
        if (selectBlock.hasHavingClause()) {
            changed |= selectBlock.getHavingClause().accept(this, funcs);
        }
        changed |= selectBlock.getSelectClause().accept(this, funcs);
        return changed;
    }

    @Override
    public Boolean visit(SelectClause selectClause, List<FunctionDecl> funcs) throws CompilationException {
        boolean changed = false;
        if (selectClause.selectElement()) {
            changed |= selectClause.getSelectElement().accept(this, funcs);
        } else {
            changed |= selectClause.getSelectRegular().accept(this, funcs);
        }
        return changed;
    }

    @Override
    public Boolean visit(SelectElement selectElement, List<FunctionDecl> funcs) throws CompilationException {
        Pair<Boolean, Expression> p = inlineUdfsInExpr(selectElement.getExpression(), funcs);
        selectElement.setExpression(p.second);
        return p.first;
    }

    @Override
    public Boolean visit(SelectRegular selectRegular, List<FunctionDecl> funcs) throws CompilationException {
        boolean changed = false;
        for (Projection projection : selectRegular.getProjections()) {
            changed |= projection.accept(this, funcs);
        }
        return changed;
    }

    @Override
    public Boolean visit(SelectSetOperation selectSetOperation, List<FunctionDecl> funcs) throws CompilationException {
        boolean changed = false;
        changed |= selectSetOperation.getLeftInput().accept(this, funcs);
        for (SetOperationRight right : selectSetOperation.getRightInputs()) {
            changed |= right.getSetOperationRightInput().accept(this, funcs);
        }
        return changed;
    }

    @Override
    public Boolean visit(SelectExpression selectExpression, List<FunctionDecl> funcs) throws CompilationException {
        boolean changed = false;
        if (selectExpression.hasLetClauses()) {
            for (LetClause letClause : selectExpression.getLetList()) {
                changed |= letClause.accept(this, funcs);
            }
        }
        changed |= selectExpression.getSelectSetOperation().accept(this, funcs);
        if (selectExpression.hasOrderby()) {
            changed |= selectExpression.getOrderbyClause().accept(this, funcs);
        }
        if (selectExpression.hasLimit()) {
            changed |= selectExpression.getLimitClause().accept(this, funcs);
        }
        return changed;
    }

    @Override
    public Boolean visit(UnnestClause unnestClause, List<FunctionDecl> funcs) throws CompilationException {
        Pair<Boolean, Expression> p = inlineUdfsInExpr(unnestClause.getRightExpression(), funcs);
        unnestClause.setRightExpression(p.second);
        return p.first;
    }

    @Override
    public Boolean visit(HavingClause havingClause, List<FunctionDecl> funcs) throws CompilationException {
        Pair<Boolean, Expression> p = inlineUdfsInExpr(havingClause.getFilterExpression(), funcs);
        havingClause.setFilterExpression(p.second);
        return p.first;
    }

    @Override
    public Boolean visit(IndependentSubquery independentSubquery, List<FunctionDecl> funcs)
            throws CompilationException {
        Pair<Boolean, Expression> p = inlineUdfsInExpr(independentSubquery.getExpr(), funcs);
        independentSubquery.setExpr(p.second);
        return p.first;
    }

    @Override
    public Boolean visit(CaseExpression caseExpr, List<FunctionDecl> funcs) throws CompilationException {
        Pair<Boolean, Expression> result = inlineUdfsInExpr(caseExpr.getConditionExpr(), funcs);
        caseExpr.setConditionExpr(result.second);
        boolean inlined = result.first;

        Pair<Boolean, List<Expression>> inlinedList = inlineUdfsInExprList(caseExpr.getWhenExprs(), funcs);
        inlined = inlined || inlinedList.first;
        caseExpr.setWhenExprs(inlinedList.second);

        inlinedList = inlineUdfsInExprList(caseExpr.getThenExprs(), funcs);
        inlined = inlined || inlinedList.first;
        caseExpr.setThenExprs(inlinedList.second);

        result = inlineUdfsInExpr(caseExpr.getElseExpr(), funcs);
        caseExpr.setElseExpr(result.second);
        return inlined || result.first;
    }

    private Map<Expression, Expression> extractLetBindingVariableExpressionMappings(List<LetClause> letClauses)
            throws CompilationException {
        Map<Expression, Expression> varExprMap = new HashMap<>();
        for (LetClause lc : letClauses) {
            // inline let variables one by one iteratively.
            lc.setBindingExpr(SqlppRewriteUtil.substituteExpression(lc.getBindingExpr(),
                    varExprMap, context));
            varExprMap.put(lc.getVarExpr(), lc.getBindingExpr());
        }
        return varExprMap;
    }

}


text:
Home	ANS Reports	Pat Boone believes that he will meet Hollywood star, Rock Hudson, again in heaven
Pat Boone believes that he will meet Hollywood star, Rock Hudson, again in heaven
by Dan Wooding March 19, 2018
written by Dan Wooding March 19, 2018
The veteran entertainer reveals how he and his wife Shirley, were able to minister to Hudson, just before he died in 1995 from complications of AIDS, and how, because of Susan Stafford, former host of "Wheel of Fortune," the Hollywood star prayed the "sinners prayer," with a priest, just before he passed away.
By Dan Wooding, Founder of ASSIST News Service
BEVERLY HILLS, CA (ANS – March 19, 2018) – Veteran singer, actor and author, Pat Boone, has revealed that he believes he will again meet with Hollywood star, Rock Hudson, in heaven, after ministering to him at his Beverly Hills home just before his death on October 2, 1985, of complications from AIDS.
Viewed as a prominent "heartthrob" of the Hollywood Golden Age, Hudson achieved stardom with roles in films such as Magnificent Obsession (1954), All That Heaven Allows (1955) and Giant (1956), and found continued success with a string of romantic comedies co-starring Doris Day in Pillow Talk (1959), Lover Come Back (1961) and Send Me No Flowers (1964). After appearing in films including Seconds (1966), Tobruk (1967) and Ice Station Zebra (1968) during the late 1960s, Hudson began a second career in television through the 1970s and 1980s, starring in the popular mystery series McMillan & Wife and the soap opera Dynasty.
Boone, who had been friends with Rock Hudson, also known as Roy Fitzgerald, during his Hollywood acting days, said in an extraordinary interview for my "Front Page Radio" show, that he, his wife Shirley, and a Christian lady from New Zealand, had visited him as the hours ticked down before his passing, and were able to pray for him.
Boone, who had not talked publically before about his role in the death-bed conversation of Rock Hudson, explained that by the time they went to see him, he could not speak because of the ravages of AIDS, but responded with his eyes.
Pat Boone said: "I had known Rock when we were both making movies and we spent some time once at Western Costuming, when we were both trying on costumes for roles that we were going to play. He was such a manly guy.
"It there was anybody that Shirley would have swooned over, it would have been Rock Hudson, and it never occurred to me that maybe he might have preferred my company to Shirley's, but in any case, he never betrayed that to me at all, and we were just kind of buddies."
Boone said that he had come back into Hudson's life when it became known that he was suffering from AIDS. "He was dying at that point, and nobody really knew how it was transferred, so a lot of his own friends were not coming to see him in those last days," he said.
"But we knew where he lived up in the hills of Beverly Hills and we had met a couple of Christian nurses who were taking care of him. They told Shirley that they had prayed with Rock and that he was in very poor state, but very open to the Gospel, wanting to be known to the Lord as a believer — a Christian. Rock knew he was soon to meet God face-to-face; and he wanted to meet him as a Child of God, and the nurses were conveying this to him and he had even taken communion with them.
"So Shirley asked if it would be possible for us to come see him and they made the arrangement with his buddy, Tom, who was looking after him in Rock's house. We went up twice just to meet and pray with him. He was emaciated, but even though he couldn't speak because his throat had been ravaged by the disease, his eyes were shiny bright out of sunken sockets. He didn't look like the Rock Hudson anybody had ever seen in his many films.
"He welcomed us even though he couldn't speak, but you could tell by the eyes, that he was glad that we were there. We prayed with him and then we asked if we could come back again and he nodded 'yes.' So about two nights later Shirley and I, and a dear friend of ours from New Zealand, went back to see him again."
As an elder of The Church on the Way in Van Nuys, California, Boone knew of the scripture which says that if any of you are sick, let him call for elders of the church and let them anoint the sick with oil and pray over them in the name of the Lord and he can be healed.
"Tom had him propped up in bed and again his eyes shining very brightly welcoming us although he was just skin and bones," said Boone. "And I said. 'Roy' – as I was now calling him Roy because his real name was Roy Fitzgerald — 'we're here and we love ya.' Then I read this little scripture in James I and asked him he would be willing to let me anoint him with oil in the name of Jesus and pray over you and ask the Lord to heal you, and he nodded his head affirmatively.
"He was now his pajamas and the top was open and still, not knowing how AIDS might be transferred, but remembering that Jesus touched lepers before he healed them, I just took the oil and I made a big sign of the cross in oil on his bare chest, and told him, 'I'm doing this because Jesus died for our sins.' I also said, 'Jesus, the Bible says, in 1 Peter, that by his stripes we are healed. He died for our illness our diseases our sins and I'm doing this in His name and I'm asking him to heal you, Roy.
"He was obviously eager to receive it. Then Tom came in right after that and there was something that was brighter and more kind of changed in Roy's countenance. And Tom said, 'Boy, Roy, you look better you're gonna have a great day tomorrow man. I'm gonna lay out your happy clothes.' And Roy nodded, we prayed again and left.
"The next morning, we got the word on the news that Rock Hudson had died. Well we couldn't believe it. Shirley and her friend went up the hill to the house again, and there was the hearse. They had not taken him out, but they were getting some things together. Tom, Shirley, and her friend, were allowed to go in and Shirley put her hands on Rock's cold feet and prayed for him and asked the Lord to raise him. Tom told Shirley that he had put on Rock's 'happy clothes,' opened the shutters to let the morning sunrise come in, and Rock passed looking at the rising sun propped up in bed in his 'happy clothes.'
"We all wept afterwards, and I told Shirley, 'You know it was a happy day. He went to be with the Lord. He was raised through a brand new body. AIDS had ruined his normal physical body, but now the Bible says we're given new bodies eternal bodies. And now we believe that Roy Fitzgerald, better known as Rock Hudson, is there with the Lord and he'll welcome us when we come to our eternal habitations. So that's the story. Of course, took him away to bury the body. But they didn't bury Rock or Roy, as he was not in that body then."
In a previous interview, Susan Stafford, the original hostess of "Wheel of Fortune," had revealed how she was present when a Catholic priest led Rock Hudson in the "sinner's prayer" to receive Jesus Christ into his life, just hours before his death.
Stafford, who preceded Vanna White as the first hostess on the popular American game show, "Wheel of Fortune," (from January 6, 1975 until she left on October 22, 1982), told me, "Yes, it is true that Rock Hudson accepted Jesus Christ on his deathbed," she told me. "I was staying with Rock Hudson at his home at the time, and Pat and Shirley Boone and also 'Love Boat' captain, Gavin MacLeod and his wife, Patti, came to pray with him."
A born-again Christian, Stafford said that also there at that time was Fr. Terrance A. Sweeney, a five-time Emmy Award winning producer, an ex-Jesuit priest who was ordained to the priesthood on June 15, 1973.
"Rock was a Roman Catholic and so we called in Fr. Sweeney and he prayed the 'sinner's prayer,' with him and then I prayed as did one of his nurses called Toni," she said. "I later did Rock's funeral."
Susan went on to say, "He was a real gentleman and accepted it with a great sense of humor despite being in a lot of pain."
I asked Susan to comment on Christians who criticize people who have HIV/AIDS and say that they "deserve to have the illness because of their lifestyle."
"It's easy to say this because I believe, with every portion of my heart, that you are talking to a sinner," she said. "Some [of us] sin more than others, but we're all sinners one way or the other. I do not think that a homosexual is less or more of a sinner than I am, and I don't dare to judge that. Shame on the Christians that do it, because love is the answer. If we don't love each other, and instead just keep on judging everybody, we're not going to have any friends left."
In the same interview, Pat Boone also talked about his upcoming historic pilgrimage to the Holy Land (http://patbooneisraeltour.com/) from May 9, 2019 – May 18, 2019, during which he, and his fellow pilgrims, will be helping celebrate the 70th anniversary of the founding of the State of Israel.
He mentioned that both he and Susan Stafford will be on the trip and would be happy to share more about the Rock Hudson story with their fellow pilgrims.
To listen to the complete interview with Pat Boone, please go to: http://frontpageradio.net/frontpageradiofiles/PatBooneFPR20180318Mono.mp3
**I would like to thank Robin Frost for transcribing all of the above interviews.
Photo captions: 1) Doris Day and Rock Hudson speak at a news conference in Monterey, California, on July 18, 1985. 2) Shirley and Pat Boone, who prayed for Rock Hudson. 3) Hudson (left) with President Ronald Reagan and first lady Nancy Reagan at a White House state dinner, May 1984, less than three weeks before he was diagnosed with HIV/AIDS. 4) Pat Sajak, Susan Stafford and Merv Griffin, during Susan's days on "Wheel of Fortune." 5) Rock Hudson on the cover of LIFE magazine. 6) Dan Wooding with Pat Boone at an event in Beverly Hills.
About the writer: Dan Wooding, 77, is an award-winning author, broadcaster and journalist who was born in Nigeria of British missionary parents and is now living in Southern California with his wife Norma, to whom he has been married for nearly 55 years. They have two sons, Andrew and Peter, and six grandchildren, who all live in the UK. He has authored numerous books, including "He Intends Victory," a book about people with HIV/AIDS and how Jesus touched their lives.
** You may republish this and any of our ANS stories with attribution to the ASSIST News Service (www.assistnews.net). Please tell your friends that they can receive a complimentary subscription to our news service by going to the above ANS website and signing up there.
Dan Wooding
Dan Wooding is the founder of the Assist News Service. He was an award-winning journalist and is one of the few Christian journalists to ever be allowed to report from inside of North Korea. Dan was promoted to Heaven on March 18, 2020, after a long battle with Leukemia. Dan's legacy lives on at Assist News Service. His son Peter is now Senior Editor.
Clinging to the "If Only's"
Texas Farm Girl's Tragedy, 'My Daddy Is In Heaven,' Debuts on DVD, Digital and On Demand
Golfing for a Purpose
Easter Drive-in Church Services Banned But Abortion Clinics...
Faith-Based Streaming App Minno Assists #StayAtHome Families
BREAKING NEWS: Evangelist Luis Palau has Lung Cancer
Special Moments and Miracles
Literacy Training—the Life-Transforming Tool That is Impacting Communities
Remembering Dr. Richard A. Bennett (1927-2019)
Catholic nun in Syria describes how she narrowly...


text:
FactoryGirl.define do
  factory :urgency_node_base, class: Urgency::Node::Base, traits: [:cms_node] do
    route "urgency/base"
  end

  factory :urgency_node_layout, class: Urgency::Node::Layout, traits: [:cms_node] do
    route "urgency/layout"
    #urgency_default_layout_id { create(:cms_layout).id }
    urgency_default_layout_id { 1 }
  end
end


text:
namespace GameStates
{
	//New states will be added here to be able to
	//-call them for their creation
	enum States
	{
		RUNNING = 0,
		MAIN_MENU,
		MAP_EDITOR,
		SCENE_MANAGER,
		TESTING_REALM
	};
}

class GameState
{
public:
	//Function called every frame
	//Looks for GameStates::States::(state to change to) on return
	//All gamestates will require the (elapsed time for the frame) and (controller inmput) function.
	virtual GameStates::States Update() = 0;
	virtual void Draw() = 0;
	virtual bool CreateDeviceIndependentResources() = 0;
	virtual void CreateDeviceDependentResources() = 0;
	virtual void Close() = 0;
	virtual void OnWindowResize() = 0;
};


French Word Wizard is a unique app that lets kids hear the sounds of French letters and words using a talking movable alphabet. Featuring advanced text to speech capabilities, the app can pronounce and spell-check an unlimited number of original French words.
• Read each word or all the words created as a sentence.
3 spelling activities of increasing difficulty are provided to adapt the activity to the spelling level of the child. You can use the built-in word lists or create your own.
2 - "Scrambled Letters" only displays the letters needed to build the word or sentence, and ask the child to reorder the letters.
3 - "Spelling Quizzes" is a standard spelling test. However, the app won't go to the next word until the child has correctly spelled the word, which is better to remember the correct spelling.
Please send your suggestions, comment or questions to support@lescapadou.com. We are listening to our users to make our products even better.
This app has helped my daughter a lot with learning and practicing French syllables. In addition, the ability to create word lists has helped her score high on every spelling test to date. Most importantly, this app helps me teach her how to pronounce words better. Prior to this app, I paid for a tutor two times a week. I can cut the tutor sessions in half now!!!
The only helpful suggestion I can add is the ability to add words to the word list via ones camera.
Due to the success I have been experiencing with this app, I bought Word Wizard in French and English too. Great job developers.
Please disregard my previous post regarding word error. Apparently the word we accidentally typed was not a good word. Ironically we were trying to type cornet. My daughter forgot to type the 'r'.
Please send me an email to support@lescapadou.com so I can help you. Everything is working fine, the app has not changed.
I just started using this for my kids - love the option to create personal spelling tests, since it gives me the ability to quiz them on their weekly words!