public override void deserializeFromMocaTree(Serialization.MocaTree.MocaNode actNode) { this.MethodGuid = actNode.getAttributeOrCreate("methodGuid").Value; this.MethodNameOld = actNode.getAttributeOrCreate("methodName").Value; this.MethodReturnType = actNode.getAttributeOrCreate("methodReturnType").Value; SQLMethod mt = Repository.GetMethodByGuid(this.MethodGuid); if (mt != null) { this.MethodName = mt.Name; } else { this.MethodName = MethodNameOld; } MocaNode targetNode = actNode.getChildNodeWithName("target"); this.Target = Expression.createExpression(targetNode.getAttributeOrCreate("type").Value, Repository); this.Target.deserializeFromMocaTree(targetNode); foreach (MocaNode childNode in actNode.Children) { if (childNode.Name == "ownedParameterBinding") { ParameterBinding paramBinding = new ParameterBinding(Repository); paramBinding.deserializeFromMocaTree(childNode); this.OwnedParameterBinding.Add(paramBinding); } } }
public void BeforeFunctionInvocation_Throws_OnOrchestrationFunctionWithoutContextParameter() { var durableController = CreateDurableController(DurableFunctionType.OrchestrationFunction); var inputData = new ParameterBinding[0]; Assert.ThrowsAny <ArgumentException>(() => durableController.BeforeFunctionInvocation(inputData)); }
/// <summary> /// Set the 'ReturnValue' and 'OutputData' based on the invocation results appropriately. /// </summary> private void BindOutputFromResult(InvocationResponse response, AzFunctionInfo functionInfo, Hashtable results) { switch (functionInfo.Type) { case AzFunctionType.RegularFunction: // Set out binding data and return response to be sent back to host foreach (KeyValuePair <string, BindingInfo> binding in functionInfo.OutputBindings) { // if one of the bindings is '$return' we need to set the ReturnValue string outBindingName = binding.Key; if (string.Equals(outBindingName, AzFunctionInfo.DollarReturn, StringComparison.OrdinalIgnoreCase)) { response.ReturnValue = results[outBindingName].ToTypedData(_powerShellManager); continue; } ParameterBinding paramBinding = new ParameterBinding() { Name = outBindingName, Data = results[outBindingName].ToTypedData(_powerShellManager) }; response.OutputData.Add(paramBinding); } break; case AzFunctionType.OrchestrationFunction: case AzFunctionType.ActivityFunction: response.ReturnValue = results[AzFunctionInfo.DollarReturn].ToTypedData(_powerShellManager); break; default: throw new InvalidOperationException("Unreachable code."); } }
/// <summary> /// Appends the current parameter name and value, e.g. <c>@P0</c>, to the attribute buffer. /// </summary> /// <param name="attribute">The current attribute.</param> /// <returns>A new attribute containing the appended buffer.</returns> public static IProjectionAttribute Par(this IProjectionAttribute attribute) { IField value = attribute.Field?.Invoke(); if (value != null) { string paramName = attribute.Context.Lookup.Parameter(attribute.Identity, value); string dialectName = attribute.Context.Domain.Dialect.Parameter(paramName); Parameter param = new Parameter(paramName, value); IProjectionAttribute result = attribute.Append(dialectName).Append(param); if (attribute.Metadata.HasFlag(ProjectionMetadataFlags.Output)) { ParameterBinding binding = new ParameterBinding(param.Name, value); result = result.Append(binding); } return(result); } else { string paramName = attribute.Context.Lookup.Parameter(attribute.Identity, attribute.Metadata.Identity); string dialectName = attribute.Context.Domain.Dialect.Parameter(paramName); return(attribute.Append(dialectName)); } }
/// <summary> /// Set the 'ReturnValue' and 'OutputData' based on the invocation results appropriately. /// </summary> private static void BindOutputFromResult(InvocationResponse response, AzFunctionInfo functionInfo, IDictionary results) { if (functionInfo.DurableFunctionInfo.Type == DurableFunctionType.None) // TODO: but let activity functions have output bindings, too { // Set out binding data and return response to be sent back to host foreach (var(bindingName, bindingInfo) in functionInfo.OutputBindings) { var outValue = results[bindingName]; var transformedValue = Utils.TransformOutBindingValueAsNeeded(bindingName, bindingInfo, outValue); var dataToUse = transformedValue.ToTypedData(); // if one of the bindings is '$return' we need to set the ReturnValue if (string.Equals(bindingName, AzFunctionInfo.DollarReturn, StringComparison.OrdinalIgnoreCase)) { response.ReturnValue = dataToUse; continue; } var paramBinding = new ParameterBinding() { Name = bindingName, Data = dataToUse }; response.OutputData.Add(paramBinding); } } if (functionInfo.DurableFunctionInfo.ProvidesForcedDollarReturnValue) { response.ReturnValue = results[AzFunctionInfo.DollarReturn].ToTypedData(); } }
/// <summary> /// Appends the current parameter name and value, e.g. <c>@P0</c>, to the attribute buffer. /// </summary> /// <param name="attribute">The current attribute.</param> /// <returns>A new attribute containing the appended buffer.</returns> public static IProjectionAttribute Par(this IProjectionAttribute attribute) { if (!attribute.Context.Domain.Dialect.Support.HasFlag(DialectSupport.InputParameters)) { throw ProjectionException.FromProjection(attribute, $"Dialect '{attribute.Context.Domain.Dialect.GetType().Name}' does not support input parameters."); } IField value = attribute.Field?.Invoke(); if (value != null) { string paramName = attribute.Context.Lookup.Parameter(attribute.Identity, value); string dialectName = attribute.Context.Domain.Dialect.Parameter(paramName); Parameter param = new Parameter(paramName, value); IProjectionAttribute result = attribute.Append(dialectName).Append(param); if (attribute.Metadata.HasFlag(ProjectionMetadataFlags.Output) && attribute.Context.Domain.Dialect.Support.HasFlag(DialectSupport.OutputParameters)) { ParameterBinding binding = new ParameterBinding(param); result = result.Append(binding); } return(result); } else { string paramName = attribute.Context.Lookup.Parameter(attribute.Identity, attribute.Metadata.Identity); string dialectName = attribute.Context.Domain.Dialect.Parameter(paramName); return(attribute.Append(dialectName)); } }
public void SetParameter(ModuleBinding module, ParameterBinding param, object value) { var binding = new Binding(); binding.Module = module; binding.Parameter = param; SetParameter(binding, value); }
public static MethodCallExpression generateMethodCallExpression(SQLRepository sqlRepository, Object target, SQLMethod method) { MethodCallExpression methodCallExpression = new MethodCallExpression(method, sqlRepository); Expression targetExpression = null; foreach (SQLParameter parameter in method.Parameters) { ParameterBinding parameterBinding = new ParameterBinding(sqlRepository, parameter); Expression expression = new LiteralExpression("null"); parameterBinding.ValueExpression = expression; methodCallExpression.OwnedParameterBinding.Add(parameterBinding); } //check if the target is an ObjectVariable or a Parameter if (target is SQLParameter) { SQLParameter parameter = target as SQLParameter; ParameterExpression parameterExpression = new ParameterExpression(sqlRepository, parameter); targetExpression = parameterExpression; } else if (target is SQLElement) { SQLElement element = target as SQLElement; ObjectVariableExpression ovExp = new ObjectVariableExpression(element, sqlRepository); targetExpression = ovExp; } methodCallExpression.Target = targetExpression; return(methodCallExpression); }
public async Task <InvocationResponse> InvokeAsync(FunctionInvocation invocation) { // TODO: File InvocationResponse removal issue InvocationResponse response = new InvocationResponse { InvocationId = invocation.InvocationId }; FunctionExecutionContext?executionContext = null; try { executionContext = _functionExecutionContextFactory.Create(invocation, _functionMap[invocation.FunctionId]); await _functionExecutionDelegate(executionContext); var parameterBindings = executionContext.OutputBindings; var result = executionContext.InvocationResult; foreach (var paramBinding in parameterBindings) { // TODO: ParameterBinding shouldn't happen here foreach (var binding in executionContext.OutputBindings) { var parameterBinding = new ParameterBinding { Name = binding.Key, Data = binding.Value.ToRpc() }; response.OutputData.Add(parameterBinding); } } if (result != null) { var returnVal = result.ToRpc(); response.ReturnValue = returnVal; } response.Result = new StatusResult { Status = Status.Success }; } catch (Exception ex) { response.Result = new StatusResult { Exception = ex.ToRpcException(), Status = Status.Failure }; } finally { (executionContext as IDisposable)?.Dispose(); } return(response); }
private void evaluatableBrowser_DoubleClick(object sender, EventArgs e) { ParameterBinding selectedParameter = evaluatableBrowser.SelectedItem as ParameterBinding; if (selectedParameter != null) { EditParameter(selectedParameter); } }
/// <summary> /// Builds an expression from the specified target for the given <see cref="IExpressionCompileContext" /> /// </summary> /// <param name="target">The target whose expression is to be built.</param> /// <param name="context">The compilation context.</param> /// <param name="compiler">The expression compiler to be used to build any other expressions for targets /// which might be required by the <paramref name="target" />. Note that unlike on the interface, where this /// parameter is optional, this will always be provided</param> /// <exception cref="NotImplementedException"></exception> protected override Expression Build(DelegateTarget target, IExpressionCompileContext context, IExpressionCompiler compiler) { var bindings = ParameterBinding.BindWithRezolvedArguments(target.Factory.GetMethodInfo()); return(Expression.Invoke(Expression.Constant(target.Factory), bindings.Select(b => b.Parameter.ParameterType == typeof(ResolveContext) ? context.ResolveContextParameterExpression : compiler.Build(b.Target, context.NewContext(b.Parameter.ParameterType))))); }
private static Dictionary <string, ParameterBinding> GetSubBinding(string FieldName, Type FieldType) { Dictionary <string, ParameterBinding> bindings = new Dictionary <string, ParameterBinding>(); if (TypeHelper.IsFieldType(FieldType)) { ParameterBinding binding = new ParameterBinding(); binding.Binding = FieldName; binding.FullTypeName = FieldType.FullName; bindings.Add(FieldName, binding); } else if (TypeHelper.IsDictionary(FieldType)) { ParameterBinding binding = new ParameterBinding(); binding.FullTypeName = FieldType.FullName; binding.IsDictionary = true; binding.KeyType = Lib.Reflection.TypeHelper.GetDictionaryKeyType(FieldType).FullName; binding.ValueType = Lib.Reflection.TypeHelper.GetDictionaryValueType(FieldType).FullName; bindings.Add(FieldName, binding); } else if (TypeHelper.IsCollection(FieldType)) { ParameterBinding binding = new ParameterBinding(); binding.FullTypeName = FieldType.FullName; binding.IsCollection = true; binding.IsContentFolder = IsContentFolder(FieldName); binding.IsProductType = IsProductType(FieldName); binding.KeyType = Lib.Reflection.TypeHelper.GetEnumberableType(FieldType).FullName; bindings.Add(FieldName, binding); } else if (FieldType.IsClass) { string classname = FieldType.Name; ParameterBinding binding = new ParameterBinding(); binding.Binding = FieldName; binding.FullTypeName = FieldType.FullName; bindings.Add(FieldName, binding); foreach (var FieldItem in Lib.Reflection.TypeHelper.GetPublicFieldOrProperties(FieldType)) { var dict = GetSubBinding(FieldItem.Key, FieldItem.Value); foreach (var item in dict) { if (!string.IsNullOrEmpty(item.Value.Binding) && !item.Value.Binding.Contains(".")) { item.Value.Binding = classname + "." + item.Value.Binding; } bindings.Add(FieldName + "." + item.Key, item.Value); } } } return(bindings); }
private static void EditParameter(ParameterBinding parameter) { using (EditParameterForm dlg = new EditParameterForm(false, parameter.Name, parameter.DataType, parameter.Value)) { if (dlg.ShowDialog() == DialogResult.OK) { parameter.Value = dlg.ParameterValue; } } }
public CodeField(ParameterBinding binding, ShortSymbolGenerator generator) { ParameterBinding = binding; Name = generator.GetNextGuid().ToString(); QualifiedTypeName = Primitives.GetSystemTypeFromNType(binding.SourceParameterDefinition.Type).FullName; SourceNodeGuid = binding.SourceNode.Guid.ToString(); SourceParamDisplayName = binding.SourceNode.NodeDefinition.DisplayName; TargetNodeGuid = binding.TargetNode.Guid.ToString(); TargetParamDisplayName = binding.TargetNode.NodeDefinition.DisplayName; }
public static async Task <InvocationRequest> ToRpcInvocationRequest(this ScriptInvocationContext context, ILogger logger, GrpcCapabilities capabilities) { bool excludeHttpTriggerMetadata = !string.IsNullOrEmpty(capabilities.GetCapabilityState(RpcWorkerConstants.RpcHttpTriggerMetadataRemoved)); var invocationRequest = new InvocationRequest { FunctionId = context.FunctionMetadata.GetFunctionId(), InvocationId = context.ExecutionContext.InvocationId.ToString(), TraceContext = GetRpcTraceContext(context.Traceparent, context.Tracestate, context.Attributes, logger), }; var rpcValueCache = new Dictionary <object, TypedData>(); foreach (var input in context.Inputs) { TypedData rpcValue = null; if (input.val == null || !rpcValueCache.TryGetValue(input.val, out rpcValue)) { rpcValue = await input.val.ToRpc(logger, capabilities); if (input.val != null) { rpcValueCache.Add(input.val, rpcValue); } } var parameterBinding = new ParameterBinding { Name = input.name, Data = rpcValue }; invocationRequest.InputData.Add(parameterBinding); } foreach (var pair in context.BindingData) { if (ShouldSkipBindingData(pair, context, excludeHttpTriggerMetadata)) { continue; } if (!rpcValueCache.TryGetValue(pair.Value, out TypedData rpcValue)) { rpcValue = await pair.Value.ToRpc(logger, capabilities); rpcValueCache.Add(pair.Value, rpcValue); } invocationRequest.TriggerMetadata.Add(pair.Key, rpcValue); } return(invocationRequest); }
private async Task <object> GetBindingDataAsync(ParameterBinding binding, string invocationId) { switch (binding.RpcDataCase) { case ParameterBindingType.RpcSharedMemory: // Data was transferred by the worker using shared memory return(await binding.RpcSharedMemory.ToObjectAsync(_workerChannelLogger, invocationId, _sharedMemoryManager)); case ParameterBindingType.Data: // Data was transferred by the worker using RPC return(binding.Data.ToObject()); default: throw new InvalidOperationException("Unknown ParameterBindingType"); } }
private void NewParameter() { string parameterName = "Param" + (_evaluatable.Parameters.Count + 1); Type parameterType = typeof(string); string parameterValue = null; using (EditParameterForm dlg = new EditParameterForm(true, parameterName, parameterType, parameterValue)) { if (dlg.ShowDialog() == DialogResult.OK) { ParameterBinding newParameter = new ParameterBinding(dlg.ParameterName, dlg.ParameterType); newParameter.Value = dlg.ParameterValue; _evaluatable.Parameters.Add(newParameter); } } }
public static List <DataMethodSetting> GetCodeMethods(SiteDb sitedb) { var type = typeof(Kooboo.Sites.DataSources.kScript); var allcodes = sitedb.Code.ListByCodeType(Sites.Models.CodeType.Datasource); List <DataMethodSetting> settings = new List <DataMethodSetting>(); foreach (var item in allcodes) { DataMethodSetting setting = new DataMethodSetting(); setting.DeclareType = type.FullName; setting.OriginalMethodName = item.Name; setting.MethodName = item.Name; setting.CodeId = item.Id; setting.IsPublic = true; setting.ReturnType = typeof(IJson).FullName; setting.MethodSignatureHash = methodSignatureHash(item.Id); var config = Kooboo.Sites.Scripting.Manager.GetSetting(sitedb.WebSite, item); if (config != null && config.Count > 0) { foreach (var con in config) { setting.Parameters.Add(con.Name, typeof(string).FullName); ParameterBinding binding = new ParameterBinding(); binding.DisplayName = con.Name; setting.ParameterBinding.Add(con.Name, binding); } } // add the samplecode. ParameterBinding samplecode = new ParameterBinding(); samplecode.IsData = true; samplecode.DisplayName = SampleResponseFieldName; setting.Parameters.Add(samplecode.DisplayName, typeof(string).FullName); setting.ParameterBinding.Add(SampleResponseFieldName, samplecode); settings.Add(setting); } return(settings); }
public void DictionaryProperties() { Query query = QueryFactory.CreateQuery(); query.Text = @" SELECT e.EmployeeID, e.FirstName, e.LastName FROM Employees e WHERE e.EmployeeID BETWEEN 1 AND 2 ORDER BY 1 "; Hashtable hashtable = new Hashtable(); hashtable["EmployeeID"] = -1; hashtable["FirstName"] = ""; hashtable["LastName"] = ""; ParameterBinding param = new ParameterBinding("@ROW", typeof(IDictionary), DictionaryPropertyProvider.GetProperties(hashtable)); Expression <object> expr = new Expression <object>(); expr.DataContext = query.DataContext; expr.Parameters.Add(param); DataTable dataTable = query.ExecuteDataTable(); foreach (DataRow row in dataTable.Rows) { Hashtable rowHashtable = new Hashtable(); param.Value = rowHashtable; foreach (DataColumn col in dataTable.Columns) { rowHashtable[col.ColumnName] = row[col]; } foreach (DataColumn col in dataTable.Columns) { expr.Text = "@ROW.[" + col.ColumnName + "]"; Assert.AreEqual(row[col], expr.Evaluate()); } } }
/// <summary> /// Appends the current parameter name and value, e.g. <c>@P0</c>, to the attribute buffer. /// </summary> /// <param name="attribute">The current attribute.</param> /// <returns>A new attribute containing the appended buffer.</returns> public static IProjectionAttribute Par(this IProjectionAttribute attribute) { if (!attribute.Context.Domain.Dialect.Support.HasFlag(DialectSupport.InputParameters)) { throw ProjectionException.ParametersNotSupported(attribute); } if (attribute.Data?.Input != null) { string paramName = attribute.Context.Lookup.Parameter(attribute.Identity, attribute.Data.Input); string dialectName = attribute.Context.Domain.Dialect.Parameter(paramName); Parameter param = new Parameter(paramName, attribute.Data.Input); IProjectionAttribute result = attribute.Append(dialectName).Append(param); if (attribute.Metadata.HasFlag(ProjectionMetadataFlags.Output)) { if (attribute.Context.Domain.Dialect.Support.HasFlag(DialectSupport.OutputParameters)) { ParameterBinding binding = new ParameterBinding(attribute.Data.Output, param.Name); result = result.Append(binding); } if (attribute.Metadata.HasAnyFlag(ProjectionMetadataFlags.Cascade)) { CascadeBinding binding = new CascadeBinding(attribute.Data.Output, attribute.Data.Input); result = result.Append(binding); } } return(result); } else { string paramName = attribute.Context.Lookup.Parameter(attribute.Identity, attribute.Metadata.Identity); string dialectName = attribute.Context.Domain.Dialect.Parameter(paramName); return(attribute.Append(dialectName)); } }
public static void Insert(int idTask, int idCate, int idParamName) { db = new ProjectDbContext(); var obj = db.ParameterBindings.Where(x => x.IDTask == idTask && x.IDCategory == idCate && x.IDParameterName == idParamName); if (obj.Count() != 0) { return; } var res = new ParameterBinding() { CreateDate = DateTime.Now, IDTask = idTask, IDCategory = idCate, IDParameterName = idParamName }; db.ParameterBindings.Add(res); db.SaveChanges(); }
private void RefreshParameters() { // call it with already locked parameterLock var parameterList = new ObservableCollection <ParameterBinding>(); foreach (var kvp in KControls.parameterStateDict) { ParameterInfo info = KControls.parameterInfoDict[kvp.Key]; KControls.ParameterState state = KControls.parameterStateDict[kvp.Key]; ParameterBinding parameterBinding = new ParameterBinding { Parameter = info.parameter, Format = info.ParameterLabel(), Value = state.value.ToString("G4"), Locked = info.locked, }; parameterList.Add(parameterBinding); } parameterView.ItemsSource = parameterList; }
private static void Main(string[] args) { var module = ModuleDefinition.LoadFromAssemblyNamespace( Assembly.LoadFrom("NodeFlow.Core.Module.dll"), "NodeFlow.Core.Module"); var json = module.ToJson(); module = ModuleDefinition.LoadFromJson(json); var nGraph = new Graph(); // Print var printNode = nGraph.MakeNewNode(module.Functions.First(f => f.DisplayName == "Print")); var printValue = printNode.NodeDefinition.Parameters.First(p => p.DisplayName == "Value"); var printIntValue = printNode.NodeDefinition.Parameters.First(p => p.DisplayName == "Int Value"); var printStringValue = printNode.NodeDefinition.Parameters.First(p => p.DisplayName == "String Value"); // Begin var beginNode = nGraph.MakeNewNode(module.Functions.First(f => f.DisplayName == "Begin")); var beginOutValue = beginNode.NodeDefinition.Parameters.First(p => p.DisplayName == "Value"); var beginStartAction = beginNode.NodeDefinition.Parameters.Find(p => p.DisplayName == "Start"); var beginTickAction = beginNode.NodeDefinition.Parameters.Find(p => p.DisplayName == "Tick"); // Begin -> Print //beginNode.ImplicitContinuation = printNode; beginNode.ParameterBindings.Add(new ParameterBinding(beginStartAction, beginNode, printNode.Guid.ToString())); // Bind: Being.value -> Print.value var valueBinding = new ParameterBinding(beginOutValue, printValue, beginNode, printNode); beginNode.ParameterBindings.Add(valueBinding); printNode.ParameterBindings.Add(valueBinding); // Print Literals printNode.ParameterBindings.Add(new ParameterBinding(printIntValue, printNode, "42")); printNode.ParameterBindings.Add(new ParameterBinding(printStringValue, printNode, "\"Hello, world!\"")); // Code generation var codeGenerator = new CSharpCodeGenerator(nGraph); var code = codeGenerator.Compile(); File.WriteAllText("../../Generated.cs", code); // Module loading var moduleRegistry = new NModuleRegistry(); moduleRegistry.AddModule(code); }
/// <summary> /// Set the 'ReturnValue' and 'OutputData' based on the invocation results appropriately. /// </summary> private void BindOutputFromResult(InvocationResponse response, AzFunctionInfo functionInfo, Hashtable results) { switch (functionInfo.Type) { case AzFunctionType.RegularFunction: // Set out binding data and return response to be sent back to host foreach (KeyValuePair <string, ReadOnlyBindingInfo> binding in functionInfo.OutputBindings) { string outBindingName = binding.Key; ReadOnlyBindingInfo bindingInfo = binding.Value; object outValue = results[outBindingName]; object transformedValue = Utils.TransformOutBindingValueAsNeeded(outBindingName, bindingInfo, outValue); TypedData dataToUse = transformedValue.ToTypedData(); // if one of the bindings is '$return' we need to set the ReturnValue if (string.Equals(outBindingName, AzFunctionInfo.DollarReturn, StringComparison.OrdinalIgnoreCase)) { response.ReturnValue = dataToUse; continue; } ParameterBinding paramBinding = new ParameterBinding() { Name = outBindingName, Data = dataToUse }; response.OutputData.Add(paramBinding); } break; case AzFunctionType.OrchestrationFunction: case AzFunctionType.ActivityFunction: response.ReturnValue = results[AzFunctionInfo.DollarReturn].ToTypedData(); break; default: throw new InvalidOperationException("Unreachable code."); } }
private void ok_Click(object sender, EventArgs e) { if (lbBinding.Items.Count > 1) { List <IParameter> parameters = new List <IParameter>(); int i; for (i = 0; i < lbBinding.Items.Count; i++) { parameters.Add(((ListBoxParameterItem)lbBinding.Items[i]).parameter); } if (_binding == null) { _binding = new ParameterBinding(parameters, project, txtName.Text); } else { _binding.Name = txtName.Text; _binding.setParameters(parameters); } } }
public void DataRowProperties() { Query query = QueryFactory.CreateQuery(); query.Text = @" SELECT e.EmployeeID, e.FirstName, e.LastName FROM Employees e WHERE e.EmployeeID BETWEEN 1 AND 2 ORDER BY 1 "; DataTable result = query.ExecuteDataTable(); Assert.AreEqual(2, result.Rows.Count); Expression <object> expr = new Expression <object>(); expr.DataContext = query.DataContext; ParameterBinding param = new ParameterBinding("@ROW", typeof(DataRow), DataRowPropertyProvider.GetProperties(result)); expr.Parameters.Add(param); param.Value = result.Rows[0]; expr.Text = "@ROW.EmployeeID"; Assert.AreEqual(1, expr.Evaluate()); expr.Text = "@ROW.FirstName"; Assert.AreEqual("Nancy", expr.Evaluate()); expr.Text = "@ROW.LastName"; Assert.AreEqual("Davolio", expr.Evaluate()); param.Value = result.Rows[1]; expr.Text = "@ROW.EmployeeID"; Assert.AreEqual(2, expr.Evaluate()); expr.Text = "@ROW.FirstName"; Assert.AreEqual("Andrew", expr.Evaluate()); expr.Text = "@ROW.LastName"; Assert.AreEqual("Fuller", expr.Evaluate()); }
private Expression GetBindingExpression(IEntityType type, ParameterBinding binding, Func <IProperty, Expression> makeColumnExpression) { switch (binding) { case ServiceMethodParameterBinding service: { return(new ContextServiceDelegateInjectionExpression( service.ParameterType, service.ServiceType, service.Method)); } case DefaultServiceParameterBinding service: { return(new ContextServiceInjectionExpression(service.ParameterType)); } case PropertyParameterBinding _ when binding.ConsumedProperties[0] is IProperty property: { return(makeColumnExpression(property)); } case EntityTypeParameterBinding _: { return(new EntityTypeInjectionExpression(type)); } case ContextParameterBinding _: { return(new ContextServiceInjectionExpression(binding.ParameterType)); } default: { throw new NotSupportedException($"The {binding.GetType().Name} is not supported."); } } }
public CodeParameter(ParameterDefinition parameterDefinition, ParameterBinding parameterBinding, IReadOnlyDictionary <ParameterBinding, CodeField> bindingsToCFields, bool isLast) { IsOut = parameterDefinition.IsOut; NeedsComma = !isLast; if (parameterBinding == null) { if (!parameterDefinition.IsOptional && parameterDefinition.Type != Primitives.NAction) { throw new Exception("Required parameter is not bound."); } IsUnboundOptional = parameterDefinition.IsOptional; IsUnboundContinuation = !parameterDefinition.IsOptional; } else if (parameterDefinition.Type == Primitives.NAction) { IsBoundContinuation = true; FieldNameOrValue = parameterBinding.LiteralValue; } else if (parameterBinding.LiteralValue != null) { IsLiteral = true; FieldNameOrValue = parameterBinding.LiteralValue; } else { IsField = true; FieldNameOrValue = bindingsToCFields[parameterBinding].Name; } // If it's bound, save some meta-data aboud it for comments and debug code generation. if (parameterBinding == null) { return; } SourceNodeGuid = parameterBinding.SourceNode?.Guid.ToString(); SourceParamDisplayName = parameterBinding.SourceParameterDefinition?.DisplayName; TargetNodeGuid = parameterBinding.TargetNode.Guid.ToString(); TargetParamDisplayName = parameterBinding.TargetParameterDefinition.DisplayName; }
public static void AppendProductTypeParameter(Dictionary <string, ParameterBinding> currentBinding) { bool hasfolder = false; foreach (var item in currentBinding) { string lowerkey = item.Key.ToLower(); if (lowerkey.Contains("producttype") || lowerkey.Contains("producttypeid")) { hasfolder = true; item.Value.IsProductType = true; break; } } if (!hasfolder) { ParameterBinding binding = new ParameterBinding(); binding.FullTypeName = typeof(System.Guid).Name; binding.Binding = default(Guid).ToString(); binding.IsProductType = true; currentBinding.Add("ProductTypeId", binding); } }
public static Dictionary <string, ParameterBinding> GetDefaultBinding(Dictionary <string, string> Parameters) { Dictionary <string, ParameterBinding> Bindings = new Dictionary <string, ParameterBinding>(); foreach (var item in Parameters) { Type itemtype = Kooboo.Data.TypeCache.GetType(item.Value); ParameterBinding binding = new ParameterBinding(); binding.FullTypeName = itemtype.FullName; if (TypeHelper.IsFieldType(itemtype)) { binding.Binding = "{" + item.Key + "}"; binding.IsContentFolder = IsContentFolder(item.Key); binding.IsProductType = IsProductType(item.Key); binding.IsData = IsData(item.Key); binding.IsOrderBy = IsOrderBy(item.Key); } else if (TypeHelper.IsDictionary(itemtype)) { binding.KeyType = TypeHelper.GetDictionaryKeyType(itemtype).FullName; binding.ValueType = TypeHelper.GetDictionaryValueType(itemtype).FullName; binding.IsDictionary = true; binding.Binding = "{}"; } else if (TypeHelper.IsCollection(itemtype)) { binding.IsCollection = true; binding.IsContentFolder = IsContentFolder(item.Key); binding.IsProductType = IsProductType(item.Key); binding.Binding = "[]"; binding.KeyType = TypeHelper.GetEnumberableType(itemtype).FullName; } else if (itemtype.IsClass) { string ClassName = itemtype.Name; binding.Binding = "{" + ClassName + "}"; binding.IsClass = true; foreach (var FieldItem in Lib.Reflection.TypeHelper.GetPublicFieldOrProperties(itemtype)) { var subitems = GetSubBinding(FieldItem.Key, FieldItem.Value); foreach (var subitem in subitems) { string key = item.Key + "." + subitem.Key; var value = subitem.Value; if (!value.IsCollection && !value.IsDictionary) { if (!string.IsNullOrEmpty(value.Binding) && !value.Binding.Contains(".")) { value.Binding = "{" + ClassName + "." + value.Binding + "}"; } } value.IsContentFolder = IsContentFolder(subitem.Key); value.IsProductType = IsProductType(subitem.Key); value.IsData = IsData(subitem.Key); value.IsOrderBy = IsOrderBy(subitem.Key); Bindings.Add(key, value); } } } else { continue; } Bindings.Add(item.Key, binding); } return(Bindings); }
public static Parameter GetParameter(this Element element, string name, ParameterType type, ParameterBinding parameterBinding, ParameterSet set) { if (element is ElementType ? parameterBinding != ParameterBinding.Type : parameterBinding != ParameterBinding.Instance) { return(null); } return(GetParameter(element, name, type, set)); }
// Instead of overriding VisitRequiresPlain or VisitRequiresOtherwise, just process the list. // Almost all of the code is the same for both plain and otherwise requires. // This could be done by overriding VisitRequires -- but would depend upon introducing // a VisitRequires method in StandardVisitor. public override RequiresList VisitRequiresList(RequiresList Requires){ // add a default precondition here and not earlier in the pipeline so it doesn't confuse // the contract inheritance checks. // REVIEW: probably better to add it earlier and have a HasCompilerGeneratedSignature on it // so it can be ignored in the inheritance checks. bool addDefaultPrecondition = this.currentMethod != null && !this.currentMethod.IsStatic && !this.currentMethod.IsAbstract && this.currentMethod.Body != null && this.currentMethod.Body.Statements != null && !(this.currentMethod.HasCompilerGeneratedSignature && !this.currentMethod.Name.Name.StartsWith("get_") && !this.currentMethod.Name.Name.StartsWith("set_")) && this.currentMethod.NodeType != NodeType.InstanceInitializer && this.currentMethod.NodeType != NodeType.StaticInitializer && (this.currentType != null && this.currentType.Contract != null && this.currentType.Contract.FramePropertyGetter != null) && this.currentMethod.GetAttribute(SystemTypes.NoDefaultContractAttribute) == null ; RequiresList newRequires = new RequiresList(); if (addDefaultPrecondition){ Method frameGetter = this.currentType.Contract.FramePropertyGetter; Method m = null; // We used to use "get_CanStartWriting" for non-virtual methods. But Rustan and I decided // that it should be fine to use the transitive one for all methods. It is more liberal // but still prevents re-entrance into a method in a frame that is exposed. m = SystemTypes.Guard.GetMethod(Identifier.For("get_CanStartWritingTransitively"), null); // default precondition is (as normalized IR): // requires this.get_FrameGuard().get_CanStartWriting(); if it is a non-virtual method // requires this.get_FrameGuard().get_CanStartWritingTransitively(); if it is a virtual method if (frameGetter != null && m != null){ SourceContext sc = this.currentMethod.Name.SourceContext; MethodCall getFrameGuard = new MethodCall(new MemberBinding(this.currentThisParameter, frameGetter), null, NodeType.MethodCall, SystemTypes.Guard, sc); Requires r = new RequiresOtherwise( new MethodCall( new MemberBinding(getFrameGuard,m), null, NodeType.MethodCall, SystemTypes.Boolean), new Construct(new MemberBinding(null, SystemTypes.RequiresException.GetConstructor(SystemTypes.String)), new ExpressionList(new Literal("The target object of this call must be exposable.", SystemTypes.String)), SystemTypes.RequiresException) ); r.SourceContext = sc; newRequires.Add(r); } } if ((this.currentMethod.IsPublic || this.currentMethod.IsFamilyOrAssembly) && !(this.currentCompilation != null && this.currentCompilation.CompilerParameters != null && ((CompilerOptions)this.currentCompilation.CompilerParameters).DisableNullParameterValidation)){ ParameterList parameters = this.currentMethod.Parameters; for (int i = 0, n = parameters == null ? 0 : parameters.Count; i < n; i++){ Parameter parameter = parameters[i]; if (parameter != null && !parameter.IsOut && this.typeSystem.IsNonNullType(parameter.Type)){ RequiresOtherwise r; Reference rtype = parameter.Type as Reference; if (rtype == null) { TypeNode parameterType = TypeNode.StripModifier(parameter.Type, SystemTypes.NonNullType); Expression e = null; if (this.useGenerics && (parameterType is TypeParameter || parameterType is ClassParameter)) { e = new BinaryExpression(parameter, new MemberBinding(null, parameterType), NodeType.Box, SystemTypes.Object, parameter.SourceContext); } else { e = new ParameterBinding(parameter, parameter.SourceContext); } r = new RequiresOtherwise( new BinaryExpression(e, new Literal(null, TypeNode.StripModifiers(parameter.Type)), NodeType.Ne, SystemTypes.Boolean, parameter.SourceContext), new Construct(new MemberBinding(null, SystemTypes.ArgumentNullException.GetConstructor(SystemTypes.String)), new ExpressionList(new Literal(parameter.Name.Name, SystemTypes.String)), SystemTypes.ArgumentNullException)); } else { // have to perform deref r = new RequiresOtherwise( new BinaryExpression(new AddressDereference(new ParameterBinding(parameter, parameter.SourceContext), rtype.ElementType), new Literal(null, TypeNode.StripModifiers(rtype.ElementType)), NodeType.Ne, SystemTypes.Boolean, parameter.SourceContext), new Construct(new MemberBinding(null, SystemTypes.ArgumentNullException.GetConstructor(SystemTypes.String)), new ExpressionList(new Literal(parameter.Name.Name, SystemTypes.String)), SystemTypes.ArgumentNullException)); } r.SourceContext = parameter.SourceContext; newRequires.Add(r); } } } for (int i = 0, n = Requires == null ? 0 : Requires.Count; i < n; i++){ newRequires.Add(Requires[i]); } if (newRequires.Count == 0) return Requires; Block preConditionBlock = new Block(new StatementList()); preConditionBlock.HasLocals = true; for (int i = 0, n = newRequires.Count; i < n; i++) { Requires r = newRequires[i]; if (r == null) continue; if (r.Condition == null) continue; // Code generation for preconditions needs to be such that the // data flow analysis will "see" the consequences. If the value // of the precondition is assigned to a local, then the information // is lost. // // try { // if re goto pre_i_holds; // } // catch { throw new ErrorDuringPreConditionEvaluation(...); } // throw new PreConditionException(...); // pre_i_holds: nop bool noAllocationAllowed = this.currentMethod.GetAttribute(SystemTypes.BartokNoHeapAllocationAttribute) != null; Local exceptionDuringPreCondition = new Local(Identifier.For("SS$exceptionDuringPreCondition" + i),SystemTypes.Exception); Local exceptionDuringPreCondition3 = new Local(Identifier.For("SS$objectExceptionDuringPreCondition" + i),SystemTypes.Object); Expression cond = r.Condition; string condition = cond != null && cond.SourceContext.SourceText != null && cond.SourceContext.SourceText.Length > 0 ? cond.SourceContext.SourceText : "<unknown condition>"; Expression ec2; Expression ec3; if (noAllocationAllowed) { ec2 = ec3 = new MemberBinding(null, SystemTypes.PreAllocatedExceptions.GetField(Identifier.For("InvalidContract"))); } else { MemberBinding excBinding2 = new MemberBinding(null, SystemTypes.InvalidContractException.GetConstructor(SystemTypes.String, SystemTypes.Exception)); MemberBinding excBinding3 = new MemberBinding(null, SystemTypes.InvalidContractException.GetConstructor(SystemTypes.String)); string msg2 = "Exception occurred during evaluation of precondition '" + condition + "' in method '" + currentMethod.FullName + "'"; ec2 = new Construct(excBinding2, new ExpressionList(new Literal(msg2, SystemTypes.String), exceptionDuringPreCondition)); ec3 = new Construct(excBinding3, new ExpressionList(new Literal(msg2, SystemTypes.String))); } #region If the precondition fails, throw an exception Expression throwExpression = null; #region Create the expression to throw. Deal with different subtypes of Requires if (noAllocationAllowed) { throwExpression = new MemberBinding(null, SystemTypes.PreAllocatedExceptions.GetField(Identifier.For("Requires"))); } else { if (r is RequiresPlain) { MemberBinding excBinding = new MemberBinding(null, SystemTypes.RequiresException.GetConstructor(SystemTypes.String)); Construct ec = new Construct(excBinding, new ExpressionList()); string msg = "Precondition '" + condition + "' violated from method '" + currentMethod.FullName + "'"; ec.Operands.Add(new Literal(msg, SystemTypes.String)); throwExpression = ec; } else if (r is RequiresOtherwise) { RequiresOtherwise otherwise = (RequiresOtherwise)r; if (otherwise.ThrowException is Literal) { // it was "requires P otherwise E" where E is a type name of an exception class Literal l = (Literal)otherwise.ThrowException; Class exceptionClass = (Class)l.Value; MemberBinding excBinding = new MemberBinding(null, this.GetTypeView(exceptionClass).GetConstructor()); // what to do if there is no nullary constructor? I guess that should have been checked in the context checker Construct ec = new Construct(excBinding, new ExpressionList()); throwExpression = ec; } else { // it was "requires P otherwise new E(...)" (or some other expression whose value is an exception) throwExpression = this.VisitExpression(otherwise.ThrowException); } } else { Debug.Assert(false, "Expecting only RequiresOtherwise and RequiresPlain as subtypes of Requires"); } } #endregion Throw t = new Throw(throwExpression,r.SourceContext); #endregion Block pre_i_holds = new Block(); //CatchList cl = new CatchList(2); //cl.Add(new Catch(new Block(new StatementList(new Throw(ec2,r.Condition.SourceContext))),exceptionDuringPreCondition,SystemTypes.Exception)); //cl.Add(new Catch(new Block(new StatementList(new Throw(ec3,r.Condition.SourceContext))),exceptionDuringPreCondition3,SystemTypes.Object)); //Try tryPre = new Try(new Block(new StatementList(new If(r.Condition,new Block(new StatementList(new Branch(null,pre_i_holds))),null))),cl,null,null,null); //preConditionBlock.Statements.Add(tryPre); preConditionBlock.Statements.Add(new If(r.Condition,new Block(new StatementList(new Branch(null,pre_i_holds))),null)); preConditionBlock.Statements.Add(t); preConditionBlock.Statements.Add(pre_i_holds); } preConditionBlock = this.VisitBlock(preConditionBlock); this.currentContractPrelude.Statements.Add(preConditionBlock); return Requires; }
public static void SetBinding(this System.Windows.Controls.Control control, ModuleBinding module, ParameterBinding parameter) { var map = new Binding(); map.Module = module; map.Parameter = parameter; ParameterBindings[control] = map; }