public ScenarioInterpreterForType(ContextType contextType,                                         
     IInterpreterForTypeFactory factory,
     ParameterConverter parameterConverter)
 {
     _contextType = contextType;
     _factory = factory;
     _parameterConverter = parameterConverter;
 }
		/// <summary>
		/// Obtains the list of contructors for <paramref name="type"/> using the supplied parameter values
		/// and invokes the best match. This overload requires that the supplied <paramref name="parameterValues"/> 
		/// are all used in the order in which they are supplied. Parameter values can be null.
		/// 
		/// This method is very liberal and attempts to convert values that are not otherwise
		/// considered compatible, such as between strings and enums or numbers, Guids and byte[16], etc.
		/// You should carefully test any usage to ensure correct program behavior.
		/// 
		/// If the default conversion rule doesn't do what you want, you can supply a custom converter.
		/// If it is null, default conversion rule is used.
		/// </summary>
		/// <param name="type">The type of which an instance should be created.</param>
		/// <param name="converter">The converter delegate used to perform user-defined conversion.</param>
		/// <param name="flags">Binding flags for look up constructors.</param>
		/// <param name="parameterValues">The values to use when invoking the constructor.</param>
		/// <returns>The result of the invocation.</returns>
		public static object TryCreateInstanceWithValues(this Type type, ParameterConverter converter, BindingFlags flags, params object[] parameterValues)
		{
			var ctors = type.Constructors();
			try
			{
				return TryCall(converter, ctors.Cast<MethodBase>(), type, parameterValues);
			}
			catch (MissingMemberException)
			{
				var values = parameterValues ?? new object[0];
				throw new MissingMemberException(string.Format("Unable to locate a matching constructor on type {0} for parameters: {1}",
																 type.Name, string.Join(", ", values.Select(v => v == null ? "null" : v.ToString()).ToArray())));
			}
		}
		/// <summary>
		/// Implementation details:
		/// 
		/// Matching process is done on a shallow copy of parametersValues so that 
		/// the converter could "modify" elements at will.  
		/// 
		/// There will be a problem if the converter modifies a child array and the 
		/// method ends up not being matched (because of another parameter).  
		/// 
		/// The standard Fasterflect converter doesn't modify child array so it's safe.
		/// This is only problematic when a custom converter is provided.
		///   
		/// TODO How to fix it? a deep clone?
		/// </summary>
		public static object TryCall(ParameterConverter converter, IEnumerable<MethodBase> methodBases, 
			object obj, object[] parameterValues)
		{
			converter = converter ?? new ParameterConverter(StandardConvert);
			if (parameterValues == null)
			{
				parameterValues = new object[0];
			}
			foreach (var mb in GetCandidates(parameterValues, methodBases))
			{
				var convertedArgs = new List<object>();
				var parameters = mb.GetParameters();
				bool isMatch = true;
				for (int paramIndex = 0; paramIndex < parameters.Length; paramIndex++)
				{
					var parameter = parameters[paramIndex];
					if (paramIndex == parameters.Length - 1 && IsParams(parameter))
					{
						object paramArg;
						if (parameters.Length - 1 == parameterValues.Length)
						{
							paramArg = parameter.ParameterType.CreateInstance(0);
						}
						else
						{
							paramArg = parameter.ParameterType.CreateInstance(parameterValues.Length - parameters.Length + 1);
							var elementType = parameter.ParameterType.GetElementType();
							for (int argIndex = paramIndex; argIndex < parameterValues.Length; argIndex++)
							{
								var value = parameterValues[argIndex];
								if (!converter(elementType, obj, ref value))
								{
									isMatch = false;
									goto end_of_loop;
								}
								((Array)paramArg).SetValue( value, argIndex - paramIndex );
							}
						}
						convertedArgs.Add(paramArg);
					}
					else
					{
						var value = parameterValues[paramIndex];
						if (!converter(parameter.ParameterType, obj, ref value))
						{
							isMatch = false;
							goto end_of_loop;
						}
						convertedArgs.Add(value);
					}
				}

			end_of_loop:
				if (isMatch)
				{
					parameterValues = convertedArgs.Count == 0 ? null : convertedArgs.ToArray();
					return mb is ConstructorInfo
							   ? ((ConstructorInfo) mb).Invoke(parameterValues)
							   : mb.Invoke(obj is Type ? null : obj, parameterValues);
				}
			} // foreach loop
			throw new MissingMemberException();
		}
		/// <summary>
		/// Obtains the list of methods for <paramref name="obj"/> using the supplied parameter values
		/// and invokes the best match. This overload requires that the supplied <paramref name="parameterValues"/> 
		/// are all used in the order in which they are supplied. Parameter values can be null.
		/// 
		/// This method is very liberal and attempts to convert values that are not otherwise
		/// considered compatible, such as between strings and enums or numbers, Guids and byte[16], etc.
		/// You should carefully test any usage to ensure correct program behavior.
		/// 
		/// If the default conversion rule doesn't do what you want, you can supply a custom converter.
		/// If it is null, default conversion rule is used.
		/// </summary>
		/// <param name="obj">The object whose method is to be invoked.</param>
		/// <param name="converter">The converter delegate used to perform user-defined conversion.</param>
		/// <param name="methodName">The name of the method to be invoked.</param>
		/// <param name="flags">Binding flags for look up methods.</param>
		/// <param name="parameterValues">The values to use when invoking the method.</param>
		/// <returns>The result of the invocation.</returns>
		public static object TryCallMethodWithValues(this object obj, ParameterConverter converter, string methodName, BindingFlags flags, params object[] parameterValues)
		{
			return TryCallMethodWithValues(obj, converter, methodName,Type.EmptyTypes, flags, parameterValues);
		}
 public void ToMessageStringTest()
 {
     Assert.That(ParameterConverter.ToMessage("Hello", out message, out errorMsg), Is.True);
     Assert.That(message.StringParam, Is.EqualTo("Hello"));
 }
 public void ToMessageFloatTest()
 {
     Assert.That(ParameterConverter.ToMessage(42.0f, out message, out errorMsg), Is.True);
     Assert.That(message.FloatParam, Is.EqualTo(42.0f));
 }
 public void ToMessageUintTest()
 {
     Assert.That(ParameterConverter.ToMessage((uint)42, out message, out errorMsg), Is.True);
     Assert.That(message.UintParam, Is.EqualTo(42));
 }
 public void ToMessageCharTest()
 {
     Assert.That(ParameterConverter.ToMessage('a', out message, out errorMsg), Is.True);
     Assert.That((char)message.UintParam, Is.EqualTo('a'));
 }
 public SimpleArrayConverter(ParameterConverter parameterConverter)
 {
     _parameterConverter = parameterConverter;
 }
예제 #10
0
 public virtual IQuery <T> Query <T>(string tableNameOrSelectSql, object parameters) where T : class
 {
     return(Query <T>(tableNameOrSelectSql, ParameterConverter.GetParameters(parameters)));
 }
        public List <Script> GetScripts()
        {
            List <Script> result = new List <Script>();

            FilterScriptService manager = new FilterScriptService();
            var filterScripts           = manager.ReadFilterScripts(_appSettings.ScriptDirectory);

            if (filterScripts != null && filterScripts.Any())
            {
                foreach (var filterScript in filterScripts)
                {
                    Script s = new Script();
                    s.FileName    = filterScript.Filename;
                    s.Description = filterScript.name;
                    if (filterScript.Items != null)
                    {
                        s.LstFilters = new List <FilterScriptParameter>();
                        foreach (var item in filterScript.Items)
                        {
                            FilterScriptParameter fsp = new FilterScriptParameter();

                            if (item.GetType() == typeof(FilterScriptXmlfilter))
                            {
                                var filterScriptXmlItem = (FilterScriptXmlfilter)item;
                                fsp.LstParameters = new List <ScriptParameter>();
                                fsp.Name          = filterScriptXmlItem.name;
                                if (filterScriptXmlItem.xmlparam != null)
                                {
                                    foreach (var param in filterScriptXmlItem?.xmlparam)
                                    {
                                        ScriptParameter p = new ScriptParameter();
                                        p.DefaultValue = param.value;
                                        p.Name         = param.name;
                                        p.Type         = ScriptParameterType.Text;
                                        fsp.LstParameters.Add(p);
                                    }
                                }

                                s.LstFilters.Add(fsp);
                            }

                            if (item.GetType() == typeof(FilterScriptFilter))
                            {
                                var filterScriptXmlItem = (FilterScriptFilter)item;
                                fsp.LstParameters = new List <ScriptParameter>();
                                fsp.Name          = filterScriptXmlItem.name;
                                if (filterScriptXmlItem.Param != null)
                                {
                                    foreach (var param in filterScriptXmlItem?.Param)
                                    {
                                        ScriptParameter p = new ScriptParameter();
                                        p.Description  = param.description;
                                        p.DefaultValue = param.value;
                                        p.Name         = param.name;
                                        p.Tooltip      = param.tooltip;
                                        p.Type         = ParameterConverter.ConvertParameter(param.type);
                                        fsp.LstParameters.Add(p);
                                    }
                                }

                                s.LstFilters.Add(fsp);
                            }
                        }
                    }

                    result.Add(s);
                }
            }

            return(result);
        }
예제 #12
0
 public Statement <T, U> Stmt <T, U>(string sql, ResultConverter <T> rc, ParameterConverter <U> pc)
 => Connection.CompileStatement(sql, rc, pc);
예제 #13
0
 public Statement <T> Stmt <T>(string sql, ParameterConverter <T> converter) => Connection.CompileStatement(sql, converter);
        /// <summary>
        /// Implementation details:
        ///
        /// Matching process is done on a shallow copy of parametersValues so that
        /// the converter could "modify" elements at will.
        ///
        /// There will be a problem if the converter modifies a child array and the
        /// method ends up not being matched (because of another parameter).
        ///
        /// The standard Fasterflect converter doesn't modify child array so it's safe.
        /// This is only problematic when a custom converter is provided.
        ///
        /// TODO How to fix it? a deep clone?
        /// </summary>
        public static object TryCall(ParameterConverter converter, IEnumerable <MethodBase> methodBases,
                                     object obj, object[] parameterValues)
        {
            converter = converter ?? new ParameterConverter(StandardConvert);
            if (parameterValues == null)
            {
                parameterValues = Constants.EmptyObjectArray;
            }
            foreach (MethodBase mb in GetCandidates(parameterValues, methodBases))
            {
                List <object>   convertedArgs = new List <object>();
                ParameterInfo[] parameters    = mb.GetParameters();
                bool            isMatch       = true;
                for (int paramIndex = 0; paramIndex < parameters.Length; paramIndex++)
                {
                    ParameterInfo parameter = parameters[paramIndex];
                    if (paramIndex == parameters.Length - 1 && IsParams(parameter))
                    {
                        object paramArg;
                        if (parameters.Length - 1 == parameterValues.Length)
                        {
                            paramArg = parameter.ParameterType.CreateInstance(0);
                        }
                        else
                        {
                            paramArg = parameter.ParameterType.CreateInstance(parameterValues.Length - parameters.Length + 1);
                            Type elementType = parameter.ParameterType.GetElementType();
                            for (int argIndex = paramIndex; argIndex < parameterValues.Length; argIndex++)
                            {
                                object value = parameterValues[argIndex];
                                if (!converter(elementType, obj, ref value))
                                {
                                    isMatch = false;
                                    goto end_of_loop;
                                }
                                ((Array)paramArg).SetValue(value, argIndex - paramIndex);
                            }
                        }
                        convertedArgs.Add(paramArg);
                    }
                    else
                    {
                        object value = parameterValues[paramIndex];
                        if (!converter(parameter.ParameterType, obj, ref value))
                        {
                            isMatch = false;
                            goto end_of_loop;
                        }
                        convertedArgs.Add(value);
                    }
                }

end_of_loop:
                if (isMatch)
                {
                    parameterValues = convertedArgs.Count == 0 ? null : convertedArgs.ToArray();
                    return(mb is ConstructorInfo
                                                           ? ((ConstructorInfo)mb).Invoke(parameterValues)
                                                           : mb.Invoke(obj is Type ? null : obj, parameterValues));
                }
            }             // foreach loop
            throw new MissingMemberException();
        }
예제 #15
0
 public DictionaryConverter(ParameterConverter parameterConverter)
 {
     ParameterConverter = parameterConverter;
 }
 /// <summary>
 /// Obtains the list of methods for <paramref name="obj"/> using the supplied parameter values
 /// and invokes the best match. This overload requires that the supplied <paramref name="parameterValues"/>
 /// are all used in the order in which they are supplied. Parameter values can be null.
 ///
 /// This method is very liberal and attempts to convert values that are not otherwise
 /// considered compatible, such as between strings and enums or numbers, Guids and byte[16], etc.
 /// You should carefully test any usage to ensure correct program behavior.
 ///
 /// If the default conversion rule doesn't do what you want, you can supply a custom converter.
 /// If it is null, default conversion rule is used.
 /// </summary>
 /// <param name="obj">The object whose method is to be invoked.</param>
 /// <param name="converter">The converter delegate used to perform user-defined conversion.</param>
 /// <param name="methodName">The name of the method to be invoked.</param>
 /// <param name="flags">Binding flags for look up methods.</param>
 /// <param name="parameterValues">The values to use when invoking the method.</param>
 /// <returns>The result of the invocation.</returns>
 public static object TryCallMethodWithValues(this object obj, ParameterConverter converter, string methodName, BindingFlags flags, params object[] parameterValues)
 {
     return(TryCallMethodWithValues(obj, converter, methodName, Type.EmptyTypes, flags, parameterValues));
 }
예제 #17
0
파일: Query.cs 프로젝트: akawa777/Dagent
 public virtual IQuery <T> Parameters(object parameters)
 {
     return(Parameters(ParameterConverter.GetParameters(parameters)));
 }
 public void ToMessageShortTest()
 {
     Assert.That(ParameterConverter.ToMessage((short)-42, out message, out errorMsg), Is.True);
     Assert.That(message.IntParam, Is.EqualTo(-42));
 }
예제 #19
0
파일: Query.cs 프로젝트: akawa777/Dagent
        protected virtual IEnumerable <T> Fetch(int sliceIndex, int sliceNo)
        {
            using (ConnectionScope connectionScope = new ConnectionScope(dagentKernel))
            {
                DbCommand command = dagentKernel.CreateDbCommand(selectSql);

                ParameterConverter.SetParamters(command, parameters, dagentKernel.CreateDbParameter);

                List <T> models = new List <T>();

                using (DbDataReader reader = command.ExecuteReader())
                {
                    int uniqueRowIndex = -1;
                    int sliceCount     = 0;

                    bool requestNewModel = true;

                    CurrentRow currentRow = null;
                    CurrentRow prevRow    = null;

                    bool firstRow = true;
                    bool canYeld  = sliceNo == 0 ? true : false;

                    List <CurrentRow> currentRows = new List <CurrentRow>();

                    T model = null;

                    string[] validColumnNames = new string[0];

                    while (reader.Read())
                    {
                        if (firstRow)
                        {
                            currentRow = new CurrentRow(reader);
                            model      = create(currentRow);
                            firstRow   = false;
                        }
                        else
                        {
                            prevRow = new CurrentRow(currentRow, true);

                            currentRow = new CurrentRow(currentRow, false);
                            reader.GetValues(currentRow.Values);
                            currentRow.PrevRow = prevRow;

                            requestNewModel = uniqueColumnNames.Length == 0 ? true : !currentRow.Compare(currentRow.PrevRow, uniqueColumnNames);

                            if (canYeld && requestNewModel)
                            {
                                yield return(model);

                                // for iterator
                                //yield return GetModel(validColumnNames, prefixColumnName, columnNamePropertyMap, ignoreCase, currentRows);
                                //currentRows = new List<CurrentRow>();
                            }

                            if (sliceNo != 0 && sliceNo == sliceCount && requestNewModel)
                            {
                                break;
                            }
                        }

                        if (sliceNo != 0)
                        {
                            if (requestNewModel)
                            {
                                uniqueRowIndex++;
                            }

                            if (sliceIndex > uniqueRowIndex)
                            {
                                canYeld = false;
                                continue;
                            }
                            else if (requestNewModel)
                            {
                                canYeld = true;
                                sliceCount++;
                            }
                        }

                        currentRows.Add(currentRow);

                        if (requestNewModel)
                        {
                            model = create(currentRow);

                            if (autoMapping)
                            {
                                ModelMapper <T> .Map(model, currentRow, validColumnNames, prefixColumnName, columnNamePropertyMap, ignoreCase);
                            }
                        }

                        if (mapAction != null)
                        {
                            mapAction(model, currentRow);
                        }
                    }

                    if (model != null)
                    {
                        yield return(model);
                    }

                    // for iterator
                    //if (currentRows != null)
                    //{
                    //    yield return GetModel(validColumnNames, prefixColumnName, columnNamePropertyMap, ignoreCase, currentRows);
                    //}
                }
            }
        }
 public void ToMessageUint64Test()
 {
     Assert.That(ParameterConverter.ToMessage((ulong)42000000000, out message, out errorMsg), Is.True);
     Assert.That(message.Uint64Param, Is.EqualTo(42000000000));
 }
 public void FromMessageNullStringTest()
 {
     message.IsNull = true;
     Assert.That(ParameterConverter.FromMessage(message, typeof(string), out param, out errorMsg), Is.True);
     Assert.That(param, Is.EqualTo(null));
 }
 public void ToMessageDoubleTest()
 {
     Assert.That(ParameterConverter.ToMessage(42.0, out message, out errorMsg), Is.True);
     Assert.That(message.DoubleParam, Is.EqualTo(42.0));
 }
 public void FromMessageNullProtoTest()
 {
     message.IsNull = true;
     Assert.That(ParameterConverter.FromMessage(message, typeof(MultiplyInput), out param, out errorMsg), Is.True);
     Assert.That(param, Is.EqualTo(null));
 }
 public TypedArrayTableConverter(ParameterConverter parameterConverter)
 {
     _parameterConverter = parameterConverter;
 }
 public void FromMessageUnsupportedValueTypeFailureTest()
 {
     message.IsNull = true;
     Assert.That(ParameterConverter.FromMessage(message, typeof(decimal), out param, out errorMsg), Is.False);
 }
 public StorEvilTableConverter(ParameterConverter converter)
 {
     _converter = converter;
 }
 public void FromMessageNonProtoFailureTest()
 {
     message.ProtoParam = new byte[10];
     Assert.That(ParameterConverter.FromMessage(message, typeof(NonProtoClass), out param, out errorMsg), Is.False);
 }
		/// <summary>
		/// Obtains the list of methods for <paramref name="obj"/> using the supplied parameter values
		/// and invokes the best match. This overload requires that the supplied <paramref name="parameterValues"/> 
		/// are all used in the order in which they are supplied. Parameter values can be null.
		/// 
		/// This method is very liberal and attempts to convert values that are not otherwise
		/// considered compatible, such as between strings and enums or numbers, Guids and byte[16], etc.
		/// You should carefully test any usage to ensure correct program behavior.
		/// 
		/// If the default conversion rule doesn't do what you want, you can supply a custom converter.
		/// If it is null, default conversion rule is used.
		/// </summary>
		/// <param name="obj">The object whose method is to be invoked.</param>
		/// <param name="converter">The converter delegate used to perform user-defined conversion.</param>
		/// <param name="methodName">The name of the method to be invoked.</param>
		/// <param name="genericTypes">The type parameter types of the method if it's a generic method.</param>
		/// <param name="flags">Binding flags for look up methods.</param>
		/// <param name="parameterValues">The values to use when invoking the method.</param>
		/// <returns>The result of the invocation.</returns>
		public static object TryCallMethodWithValues(this object obj, ParameterConverter converter, string methodName,
			Type[] genericTypes, BindingFlags flags, params object[] parameterValues)
		{
			var type = obj is Type ? (Type)obj : obj.GetType();
			var methods = type.Methods(genericTypes, null, flags, methodName)
							  .Select(m => m.IsGenericMethodDefinition ? m.MakeGeneric(genericTypes) : m);
			try
			{
				return TryCall(converter, methods.Cast<MethodBase>(), obj, parameterValues);
			}
			catch (MissingMemberException)
			{
				var values = parameterValues ?? new object[0];
				throw new MissingMethodException(string.Format("Unable to locate a matching method {0} on type {1} for parameters: {2}",
																 methodName, type.Name,
																 string.Join(", ", values.Select(v => v == null ? "null" : v.ToString()).ToArray())));
			}
		}
 public void FromMessageProtoMissingFailureTest()
 {
     message.IntParam = 10;
     Assert.That(ParameterConverter.FromMessage(message, typeof(MultiplyInput), out param, out errorMsg), Is.False);
 }
 public void ToMessageNullTest()
 {
     Assert.That(ParameterConverter.ToMessage(null, out message, out errorMsg), Is.True);
     Assert.That(message.IsNull, Is.True);
 }
 public void ToMessageBoolTest()
 {
     Assert.That(ParameterConverter.ToMessage(true, out message, out errorMsg), Is.True);
     Assert.That(message.BoolParam, Is.True);
 }
예제 #32
0
 public TableToTypeConverter(ParameterConverter parameterConverter)
 {
     _parameterConverter = parameterConverter;
 }
예제 #33
0
 public void EstablishContext()
 {
     _actionCatalog      = new ActionCatalog();
     _parameterConverter = new ParameterConverter(_actionCatalog);
 }