コード例 #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Binding"/> class.
 /// </summary>
 public BindingConfiguration()
 {
     Metadata = new BindingMetadata();
     Parameters = new List<IParameter>();
     ActivationActions = new List<Action<IContext, object>>();
     DeactivationActions = new List<Action<IContext, object>>();
     ScopeCallback = StandardScopeCallbacks.Transient;
 }
コード例 #2
0
		/// <summary>
		///   Transforms the <paramref name="binding" />.
		/// </summary>
		private static Ssm.Binding Transform(BindingMetadata binding)
		{
			return new Ssm.Binding(
				GetComponentPath(binding.ProvidedPort.DeclaringObject),
				GetComponentPath(binding.RequiredPort.DeclaringObject),
				binding.ProvidedPort.Name,
				binding.RequiredPort.Name,
				Ssm.BindingKind.Instantaneous);
		}
コード例 #3
0
        /// <summary>
        /// Creates a new <see cref="BindingMetadataProviderContext"/>.
        /// </summary>
        /// <param name="key">The <see cref="ModelMetadataIdentity"/> for the <see cref="ModelMetadata"/>.</param>
        /// <param name="attributes">The attributes for the <see cref="ModelMetadata"/>.</param>
        public BindingMetadataProviderContext(
            ModelMetadataIdentity key,
            ModelAttributes attributes)
        {
            if (attributes == null)
            {
                throw new ArgumentNullException(nameof(attributes));
            }

            Key = key;
            Attributes = attributes.Attributes;
            PropertyAttributes = attributes.PropertyAttributes;
            TypeAttributes = attributes.TypeAttributes;

            BindingMetadata = new BindingMetadata();
        }
コード例 #4
0
        public void GenerateTimerTriggerFunction()
        {
            BindingMetadata trigger = BindingMetadata.Create(new JObject
            {
                { "type", "TimerTrigger" },
                { "name", "timerInfo" },
                { "schedule", "* * * * * *" },
                { "runOnStartup", true },
                { "direction", "in" }
            });
            MethodInfo method = GenerateMethod(trigger);

            VerifyCommonProperties(method);

            // verify trigger parameter
            ParameterInfo parameter = method.GetParameters()[0];

            Assert.Equal("timerInfo", parameter.Name);
            Assert.Equal(typeof(TimerInfo), parameter.ParameterType);
            TimerTriggerAttribute attribute = parameter.GetCustomAttribute <TimerTriggerAttribute>();

            Assert.Equal("* * * * * *", attribute.ScheduleExpression);
            Assert.True(attribute.RunOnStartup);
        }
コード例 #5
0
 internal static void PopulateScopeStorages(BindingStorage bindingStorage, MultiValuedProperty <BindingMetadata> scopes)
 {
     ArgumentValidator.ThrowIfNull("bindingStorage", bindingStorage);
     ArgumentValidator.ThrowIfNull("scopes", scopes);
     if (scopes.Changed)
     {
         object[] removed = scopes.Removed;
         for (int i = 0; i < removed.Length; i++)
         {
             BindingMetadata removedScope = (BindingMetadata)removed[i];
             ScopeStorage    scopeStorage = bindingStorage.AppliedScopes.Find((ScopeStorage item) => string.Equals(BindingMetadata.FromStorage(item.Scope).ImmutableIdentity, removedScope.ImmutableIdentity, StringComparison.OrdinalIgnoreCase));
             scopeStorage.Mode          = Mode.PendingDeletion;
             scopeStorage.PolicyVersion = CombGuidGenerator.NewGuid();
         }
         object[] added = scopes.Added;
         for (int j = 0; j < added.Length; j++)
         {
             BindingMetadata addedScope    = (BindingMetadata)added[j];
             ScopeStorage    scopeStorage2 = bindingStorage.AppliedScopes.Find((ScopeStorage item) => string.Equals(BindingMetadata.FromStorage(item.Scope).ImmutableIdentity, addedScope.ImmutableIdentity, StringComparison.OrdinalIgnoreCase));
             if (scopeStorage2 == null)
             {
                 Guid objectGuid = Guid.NewGuid();
                 scopeStorage2 = new ScopeStorage();
                 scopeStorage2[ADObjectSchema.OrganizationalUnitRoot] = bindingStorage.OrganizationalUnitRoot;
                 scopeStorage2.Name = objectGuid.ToString();
                 scopeStorage2.SetId(new ADObjectId(PolicyStorage.PoliciesContainer.GetChildId(scopeStorage2.Name).DistinguishedName, objectGuid));
                 bindingStorage.AppliedScopes.Add(scopeStorage2);
             }
             scopeStorage2.Mode          = Mode.Enforce;
             scopeStorage2.Scope         = BindingMetadata.ToStorage(addedScope);
             scopeStorage2.PolicyVersion = CombGuidGenerator.NewGuid();
         }
         bindingStorage.PolicyVersion = CombGuidGenerator.NewGuid();
         scopes.ResetChangeTracking();
     }
 }
コード例 #6
0
        public void GenerateQueueTriggerFunction()
        {
            string          inputBindingName = "inputData";
            BindingMetadata trigger          = BindingMetadata.Create(new JObject
            {
                { "type", "QueueTrigger" },
                { "name", inputBindingName },
                { "direction", "in" },
                { "queueName", "test" }
            });

            MethodInfo method = GenerateMethod(trigger);

            VerifyCommonProperties(method);

            // verify trigger parameter
            ParameterInfo parameter = method.GetParameters()[0];

            Assert.Equal(inputBindingName, parameter.Name);
            Assert.Equal(typeof(string), parameter.ParameterType);
            QueueTriggerAttribute attribute = parameter.GetCustomAttribute <QueueTriggerAttribute>();

            Assert.Equal("test", attribute.QueueName);
        }
コード例 #7
0
        private static MethodInfo GenerateMethod(BindingMetadata trigger, ScriptHostInfo scriptHostInfo)
        {
            FunctionMetadata metadata = new FunctionMetadata();

            metadata.Name       = FunctionName;
            metadata.ScriptFile = Path.Combine(scriptHostInfo.RootPath, @"Common\test.ps1");
            metadata.Bindings.Add(trigger);
            metadata.ScriptType = ScriptType.PowerShell;

            List <FunctionMetadata> metadatas = new List <FunctionMetadata>();

            metadatas.Add(metadata);
            FunctionDescriptorProvider[] descriptorProviders = new FunctionDescriptorProvider[]
            {
                new PowerShellFunctionDescriptorProvider(scriptHostInfo.Host, scriptHostInfo.Configuration)
            };

            var  functionDescriptors = scriptHostInfo.Host.ReadFunctions(metadatas, descriptorProviders);
            Type t = FunctionGenerator.Generate("TestScriptHost", "Host.Functions", functionDescriptors);

            MethodInfo method = t.GetMethods(BindingFlags.Public | BindingFlags.Static).First();

            return(method);
        }
コード例 #8
0
 public HttpBinding(ScriptJobHostOptions config, BindingMetadata metadata, FileAccess access)
     : base(config, metadata, access)
 {
 }
コード例 #9
0
        public async Task ToRpcInvocationRequest_RpcDataTransfer()
        {
            var logger = new TestLogger("test");

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Host   = new HostString("local");
            httpContext.Request.Path   = "/test";
            httpContext.Request.Method = "Post";

            var poco = new TestPoco {
                Id = 1, Name = "Test"
            };

            var bindingData = new Dictionary <string, object>
            {
                { "req", httpContext.Request },
                { "$request", httpContext.Request },
                { "headers", httpContext.Request.Headers.ToDictionary(p => p.Key, p => p.Value) },
                { "query", httpContext.Request.QueryString.ToString() },
                { "sys", new SystemBindingData() }
            };

            const int inputStringLength = 32;
            string    inputString       = TestUtils.GetRandomString(inputStringLength);

            const int inputBytesLength = 32;

            byte[] inputBytes = TestUtils.GetRandomBytesInArray(inputBytesLength);

            var inputs = new List <(string name, DataType type, object val)>
            {
                ("req", DataType.String, httpContext.Request),
                ("fooStr", DataType.String, inputString),
                ("fooBytes", DataType.Binary, inputBytes),
            };

            var invocationContext = new ScriptInvocationContext()
            {
                ExecutionContext = new ExecutionContext()
                {
                    InvocationId = Guid.NewGuid(),
                    FunctionName = "Test",
                },
                BindingData           = bindingData,
                Inputs                = inputs,
                ResultSource          = new TaskCompletionSource <ScriptInvocationResult>(),
                Logger                = logger,
                AsyncExecutionContext = System.Threading.ExecutionContext.Capture()
            };

            var functionMetadata = new FunctionMetadata
            {
                Name = "Test"
            };

            var httpTriggerBinding = new BindingMetadata
            {
                Name      = "req",
                Type      = "httpTrigger",
                Direction = BindingDirection.In,
                Raw       = new JObject()
            };

            var fooStrInputBinding = new BindingMetadata
            {
                Name      = "fooStr",
                Type      = "fooStr",
                Direction = BindingDirection.In
            };

            var fooBytesInputBinding = new BindingMetadata
            {
                Name      = "fooBytes",
                Type      = "fooBytes",
                Direction = BindingDirection.In
            };

            var httpOutputBinding = new BindingMetadata
            {
                Name      = "res",
                Type      = "http",
                Direction = BindingDirection.Out,
                Raw       = new JObject(),
                DataType  = DataType.String
            };

            functionMetadata.Bindings.Add(httpTriggerBinding);
            functionMetadata.Bindings.Add(fooStrInputBinding);
            functionMetadata.Bindings.Add(fooBytesInputBinding);
            functionMetadata.Bindings.Add(httpOutputBinding);
            invocationContext.FunctionMetadata = functionMetadata;

            GrpcCapabilities capabilities = new GrpcCapabilities(logger);
            var result = await invocationContext.ToRpcInvocationRequest(logger, capabilities, isSharedMemoryDataTransferEnabled : true, _sharedMemoryManager);

            Assert.Equal(3, result.InputData.Count);

            Assert.Equal("fooStr", result.InputData[1].Name);
            Assert.Equal("fooBytes", result.InputData[2].Name);

            // The input data should be transferred over regular RPC despite enabling shared memory
            Assert.Equal(inputString, result.InputData[1].Data.String);
            Assert.Equal(inputBytes, result.InputData[2].Data.Bytes);
        }
コード例 #10
0
        public async Task ToRpcInvocationRequest_RpcSharedMemoryDataTransfer()
        {
            var logger = new TestLogger("test");

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Host   = new HostString("local");
            httpContext.Request.Path   = "/test";
            httpContext.Request.Method = "Post";

            var poco = new TestPoco {
                Id = 1, Name = "Test"
            };

            var bindingData = new Dictionary <string, object>
            {
                { "req", httpContext.Request },
                { "$request", httpContext.Request },
                { "headers", httpContext.Request.Headers.ToDictionary(p => p.Key, p => p.Value) },
                { "query", httpContext.Request.QueryString.ToString() },
                { "sys", new SystemBindingData() }
            };

            const int inputStringLength = 2 * 1024 * 1024;
            string    inputString       = TestUtils.GetRandomString(inputStringLength);

            const int inputBytesLength = 2 * 1024 * 1024;

            byte[] inputBytes = TestUtils.GetRandomBytesInArray(inputBytesLength);

            var inputs = new List <(string name, DataType type, object val)>
            {
                ("req", DataType.String, httpContext.Request),
                ("fooStr", DataType.String, inputString),
                ("fooBytes", DataType.Binary, inputBytes),
            };

            var invocationContext = new ScriptInvocationContext()
            {
                ExecutionContext = new ExecutionContext()
                {
                    InvocationId = Guid.NewGuid(),
                    FunctionName = "Test",
                },
                BindingData           = bindingData,
                Inputs                = inputs,
                ResultSource          = new TaskCompletionSource <ScriptInvocationResult>(),
                Logger                = logger,
                AsyncExecutionContext = System.Threading.ExecutionContext.Capture()
            };

            var functionMetadata = new FunctionMetadata
            {
                Name = "Test"
            };

            var httpTriggerBinding = new BindingMetadata
            {
                Name      = "req",
                Type      = "httpTrigger",
                Direction = BindingDirection.In,
                Raw       = new JObject()
            };

            var fooStrInputBinding = new BindingMetadata
            {
                Name      = "fooStr",
                Type      = "fooStr",
                Direction = BindingDirection.In
            };

            var fooBytesInputBinding = new BindingMetadata
            {
                Name      = "fooBytes",
                Type      = "fooBytes",
                Direction = BindingDirection.In
            };

            var httpOutputBinding = new BindingMetadata
            {
                Name      = "res",
                Type      = "http",
                Direction = BindingDirection.Out,
                Raw       = new JObject(),
                DataType  = DataType.String
            };

            functionMetadata.Bindings.Add(httpTriggerBinding);
            functionMetadata.Bindings.Add(fooStrInputBinding);
            functionMetadata.Bindings.Add(fooBytesInputBinding);
            functionMetadata.Bindings.Add(httpOutputBinding);
            invocationContext.FunctionMetadata = functionMetadata;

            GrpcCapabilities capabilities = new GrpcCapabilities(logger);
            var result = await invocationContext.ToRpcInvocationRequest(logger, capabilities, isSharedMemoryDataTransferEnabled : true, _sharedMemoryManager);

            Assert.Equal(3, result.InputData.Count);

            Assert.Equal("fooStr", result.InputData[1].Name);
            Assert.Equal("fooBytes", result.InputData[2].Name);

            // The input data should be transferred over shared memory
            RpcSharedMemory sharedMem1 = result.InputData[1].RpcSharedMemory;

            // This is what the expected byte[] representation of the string should be
            // We use that to find expected length
            byte[] contentBytes = Encoding.UTF8.GetBytes(inputString);
            Assert.Equal(contentBytes.Length, sharedMem1.Count);

            // Check that the name of the shared memory map is a valid GUID
            Assert.True(Guid.TryParse(sharedMem1.Name, out _));

            // Check the type being sent
            Assert.Equal(sharedMem1.Type, RpcDataType.String);

            // The input data should be transferred over shared memory
            RpcSharedMemory sharedMem2 = result.InputData[2].RpcSharedMemory;

            Assert.Equal(inputBytes.Length, sharedMem2.Count);

            // Check that the name of the shared memory map is a valid GUID
            Assert.True(Guid.TryParse(sharedMem2.Name, out _));

            // Check the type being sent
            Assert.Equal(sharedMem2.Type, RpcDataType.Bytes);
        }
コード例 #11
0
        public static FunctionMetadata GetTestFunctionMetadata(string name, bool addHttpTriggerBinding = true, bool addQueueInput = false, bool addQueueOutput = false, bool addHttpOut = false, bool addHttpReturn = false)
        {
            var functionMetadata = new FunctionMetadata
            {
                Name = name
            };
            var httpTriggerBinding = new BindingMetadata
            {
                Name      = "req",
                Type      = "httpTrigger",
                Direction = BindingDirection.In,
                Raw       = new JObject()
            };
            var queueInputBinding = new BindingMetadata
            {
                Name      = "queueInput",
                Type      = "queue",
                Direction = BindingDirection.In
            };
            var httpOutputBinding = new BindingMetadata
            {
                Name      = "res",
                Type      = "http",
                Direction = BindingDirection.Out,
                Raw       = new JObject()
            };
            var httpReturnOutputBinding = new BindingMetadata
            {
                Name      = "$return",
                Type      = "http",
                Direction = BindingDirection.Out,
                Raw       = new JObject()
            };
            var queueReturnOutputBinding = new BindingMetadata
            {
                Name      = "$return",
                Type      = "queue",
                Direction = BindingDirection.Out,
                Raw       = new JObject()
            };

            if (addHttpTriggerBinding)
            {
                functionMetadata.Bindings.Add(httpTriggerBinding);
            }
            if (addHttpOut)
            {
                functionMetadata.Bindings.Add(httpOutputBinding);
            }
            if (addHttpReturn)
            {
                functionMetadata.Bindings.Add(httpReturnOutputBinding);
            }
            if (addQueueInput)
            {
                functionMetadata.Bindings.Add(queueInputBinding);
            }
            if (addQueueOutput)
            {
                functionMetadata.Bindings.Add(queueReturnOutputBinding);
            }
            return(functionMetadata);
        }
コード例 #12
0
        private static BindingMetadata ParseBindingMetadata(JObject binding, INameResolver nameResolver)
        {
            BindingMetadata  bindingMetadata       = null;
            string           bindingTypeValue      = (string)binding["type"];
            string           bindingDirectionValue = (string)binding["direction"];
            string           connection            = (string)binding["connection"];
            BindingType      bindingType           = default(BindingType);
            BindingDirection bindingDirection      = default(BindingDirection);

            if (!string.IsNullOrEmpty(bindingDirectionValue) &&
                !Enum.TryParse <BindingDirection>(bindingDirectionValue, true, out bindingDirection))
            {
                throw new FormatException(string.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid binding direction.", bindingDirectionValue));
            }

            if (!string.IsNullOrEmpty(bindingTypeValue) &&
                !Enum.TryParse <BindingType>(bindingTypeValue, true, out bindingType))
            {
                throw new FormatException(string.Format("'{0}' is not a valid binding type.", bindingTypeValue));
            }

            if (!string.IsNullOrEmpty(connection) &&
                string.IsNullOrEmpty(Utility.GetAppSettingOrEnvironmentValue(connection)))
            {
                throw new FormatException("Invalid Connection value specified.");
            }

            switch (bindingType)
            {
            case BindingType.EventHubTrigger:
            case BindingType.EventHub:
                bindingMetadata = binding.ToObject <EventHubBindingMetadata>();
                break;

            case BindingType.QueueTrigger:
            case BindingType.Queue:
                bindingMetadata = binding.ToObject <QueueBindingMetadata>();
                break;

            case BindingType.BlobTrigger:
            case BindingType.Blob:
                bindingMetadata = binding.ToObject <BlobBindingMetadata>();
                break;

            case BindingType.ServiceBusTrigger:
            case BindingType.ServiceBus:
                bindingMetadata = binding.ToObject <ServiceBusBindingMetadata>();
                break;

            case BindingType.HttpTrigger:
                bindingMetadata = binding.ToObject <HttpTriggerBindingMetadata>();
                break;

            case BindingType.Http:
                bindingMetadata = binding.ToObject <HttpBindingMetadata>();
                break;

            case BindingType.Table:
                bindingMetadata = binding.ToObject <TableBindingMetadata>();
                break;

            case BindingType.ManualTrigger:
                bindingMetadata = binding.ToObject <BindingMetadata>();
                break;

            case BindingType.TimerTrigger:
                bindingMetadata = binding.ToObject <TimerBindingMetadata>();
                break;

            case BindingType.EasyTable:
                bindingMetadata = binding.ToObject <EasyTableBindingMetadata>();
                break;

            case BindingType.DocumentDB:
                bindingMetadata = binding.ToObject <DocumentDBBindingMetadata>();
                break;

            case BindingType.NotificationHub:
                bindingMetadata = binding.ToObject <NotificationHubBindingMetadata>();
                break;

            case BindingType.ApiHub:
            case BindingType.ApiHubTrigger:
                bindingMetadata = binding.ToObject <ApiHubBindingMetadata>();
                break;
            }

            bindingMetadata.Type       = bindingType;
            bindingMetadata.Direction  = bindingDirection;
            bindingMetadata.Connection = connection;

            nameResolver.ResolveAllProperties(bindingMetadata);

            return(bindingMetadata);
        }
 protected override IFunctionInvoker CreateFunctionInvoker(string scriptFilePath, BindingMetadata triggerMetadata, FunctionMetadata functionMetadata, Collection <FunctionBinding> inputBindings, Collection <FunctionBinding> outputBindings)
 {
     throw new NotImplementedException();
 }
コード例 #14
0
 public TestWorkerFunctionInvoker(ScriptHost host, BindingMetadata bindingMetadata, FunctionMetadata functionMetadata, ILoggerFactory loggerFactory,
                                  Collection <FunctionBinding> inputBindings, Collection <FunctionBinding> outputBindings, IFunctionInvocationDispatcher functionDispatcher, IApplicationLifetime applicationLifetime,
                                  TimeSpan initializationTimeout)
     : base(host, bindingMetadata, functionMetadata, loggerFactory, inputBindings, outputBindings, functionDispatcher, applicationLifetime, initializationTimeout)
 {
 }
コード例 #15
0
 protected override IFunctionInvoker CreateFunctionInvoker(string scriptFilePath, BindingMetadata triggerMetadata, FunctionMetadata functionMetadata, Collection <FunctionBinding> inputBindings, Collection <FunctionBinding> outputBindings)
 {
     return(new Mock <IFunctionInvoker>().Object);
 }
コード例 #16
0
        public static ScriptInvocationContext GetScriptInvocationContext(string functionName, Guid invocationId, ILogger testLogger, DataType dataType = DataType.String)
        {
            ScriptInvocationContext scriptInvocationContext = new ScriptInvocationContext()
            {
                ExecutionContext = new ExecutionContext()
                {
                    InvocationId = invocationId,
                    FunctionName = functionName,
                },
                BindingData           = GetScriptInvocationBindingData(),
                Inputs                = GetScriptInvocationInputs(),
                ResultSource          = new TaskCompletionSource <ScriptInvocationResult>(),
                Logger                = testLogger,
                AsyncExecutionContext = System.Threading.ExecutionContext.Capture()
            };
            var functionMetadata = new FunctionMetadata
            {
                Name = functionName
            };

            var httpTriggerBinding = new BindingMetadata
            {
                Name      = "req",
                Type      = "httpTrigger",
                Direction = BindingDirection.In,
                Raw       = new JObject()
            };

            var queueInputBinding = new BindingMetadata
            {
                Name      = "queueInput",
                Type      = "queue",
                Direction = BindingDirection.In,
                DataType  = dataType
            };

            var httpOutputBinding = new BindingMetadata
            {
                Name      = "res",
                Type      = "http",
                Direction = BindingDirection.Out,
                Raw       = new JObject(),
                DataType  = dataType
            };

            var queueOutputBinding1 = new BindingMetadata
            {
                Name      = "output1",
                Type      = "queue",
                Direction = BindingDirection.Out,
                DataType  = dataType
            };

            var queueOutputBinding2 = new BindingMetadata
            {
                Name      = "output2",
                Type      = "queue",
                Direction = BindingDirection.Out,
                DataType  = dataType
            };

            var queueOutputRetrun = new BindingMetadata
            {
                Name      = "$return",
                Type      = "queue",
                Direction = BindingDirection.Out,
                DataType  = dataType
            };

            functionMetadata.Bindings.Add(httpTriggerBinding);
            functionMetadata.Bindings.Add(queueOutputBinding1);
            functionMetadata.Bindings.Add(queueOutputBinding2);
            functionMetadata.Bindings.Add(queueOutputRetrun);
            scriptInvocationContext.FunctionMetadata = functionMetadata;
            return(scriptInvocationContext);
        }
コード例 #17
0
        public static (string, string) GenerateBindingIdentifier(string functionName, BindingMetadata binding)
        {
            // common parameters
            var queueName        = binding.Raw["queueName"];
            var connection       = binding.Raw["connection"] ?? "AzureWebJobsStorage";
            var path             = binding.Raw["path"];
            var topicName        = binding.Raw["topicName"];
            var subscriptionName = binding.Raw["subscriptionName"];

            var defaultId = $"{binding.Type} - {functionName}";

            switch (binding.Type)
            {
            case "queueTrigger":
            case "queue":
                return("Queue", $"Queue - {queueName} - {connection}");

            case "httpTrigger":
                var httpRoute = binding.Raw["route"] ?? $"/api/{functionName}";
                var httpCell  = $"<td bgcolor=\"/blues4/2\" port=\"{functionName}\"><font point-size=\"10\"><b>{httpRoute}</b></font></td>";
                return(httpCell, $"httpTrigger:\"{functionName}\"");

            case "http":     // elide http output bindings
                return(null, null);

            case "blobTrigger":
            case "blob":
                return("Blob", $"Blob - {path} - {connection}");

            case "serviceBusTrigger":
            case "serviceBus":
                return("Service Bus", $"ServiceBus - {queueName} - {topicName} - {subscriptionName} - {connection}");

            case "timerTrigger":
                var schedule = binding.Raw["schedule"];
                return($"Timer\n{schedule}", defaultId);

            case "eventHubTrigger":
            case "eventHub":
                return("Event Hub", $"EventHub - {path} - {connection}");

            case "documentDB":
                var collectionName = binding.Raw["collectionName"];
                var databaseName   = binding.Raw["databaseName"];
                return("DocumentDB", $"DocumentDB - {databaseName} - {collectionName} - {connection}");

            case "manualTrigger":
                return("Manual", defaultId);

            case "table":
                var tableName = binding.Raw["tableName"];
                return("Table", $"Table - {tableName} - {connection}");

            default:
                return(binding.Type, defaultId);
            }
        }
コード例 #18
0
 public UHSharepointBinding(BindingMetadata sharepointBinding)
 {
     ArgumentValidator.ThrowIfNull("sharepointBinding", sharepointBinding);
     this.siteUrl = sharepointBinding.Name;
 }
コード例 #19
0
 public BindingMetadataTests()
 {
     _bindingMetadata = new BindingMetadata();
 }
コード例 #20
0
 protected FunctionBinding(ScriptHostConfiguration config, BindingMetadata metadata, FileAccess access)
 {
     _config  = config;
     Access   = access;
     Metadata = metadata;
 }
        public async Task ToRpcInvocationRequest_RpcSharedMemoryDataTransfer_UsingFunctionDataCache_CacheMiss()
        {
            var logger = new TestLogger("test");

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Host   = new HostString("local");
            httpContext.Request.Path   = "/test";
            httpContext.Request.Method = "Post";

            var poco = new TestPoco {
                Id = 1, Name = "Test"
            };

            var bindingData = new Dictionary <string, object>
            {
                { "req", httpContext.Request },
                { "$request", httpContext.Request },
                { "headers", httpContext.Request.Headers.ToDictionary(p => p.Key, p => p.Value) },
                { "query", httpContext.Request.QueryString.ToString() },
                { "sys", new SystemBindingData() }
            };

            const int    inputStringLength  = 2 * 1024 * 1024;
            string       inputString        = TestUtils.GetRandomString(inputStringLength);
            Stream       inputStream1       = new MemoryStream();
            StreamWriter inputStreamWriter1 = new StreamWriter(inputStream1);
            await inputStreamWriter1.WriteAsync(inputString);

            await inputStreamWriter1.FlushAsync();

            inputStream1.Seek(0, SeekOrigin.Begin);

            FunctionDataCacheKey     key1      = new FunctionDataCacheKey("fooStr", "0x1");
            MockCacheAwareReadObject cacheObj1 = new MockCacheAwareReadObject(key1, inputStream1, _functionDataCache);

            const int inputBytesLength = 2 * 1024 * 1024;

            byte[] inputBytes   = TestUtils.GetRandomBytesInArray(inputBytesLength);
            Stream inputStream2 = new MemoryStream(inputBytes);

            inputStream2.Seek(0, SeekOrigin.Begin);

            FunctionDataCacheKey     key2      = new FunctionDataCacheKey("fooBytes", "0x1");
            MockCacheAwareReadObject cacheObj2 = new MockCacheAwareReadObject(key2, inputStream2, _functionDataCache);

            var inputs = new List <(string name, DataType type, object val)>
            {
                ("req", DataType.String, httpContext.Request),
                ("fooStr", DataType.String, cacheObj1),
                ("fooBytes", DataType.Binary, cacheObj2),
            };

            var invocationContext = new ScriptInvocationContext()
            {
                ExecutionContext = new ExecutionContext()
                {
                    InvocationId = Guid.NewGuid(),
                    FunctionName = "Test",
                },
                BindingData           = bindingData,
                Inputs                = inputs,
                ResultSource          = new TaskCompletionSource <ScriptInvocationResult>(),
                Logger                = logger,
                AsyncExecutionContext = System.Threading.ExecutionContext.Capture()
            };

            var functionMetadata = new FunctionMetadata
            {
                Name = "Test"
            };

            var httpTriggerBinding = new BindingMetadata
            {
                Name      = "req",
                Type      = "httpTrigger",
                Direction = BindingDirection.In,
                Raw       = new JObject()
            };

            var fooStrInputBinding = new BindingMetadata
            {
                Name      = "fooStr",
                Type      = "fooStr",
                Direction = BindingDirection.In
            };

            var fooBytesInputBinding = new BindingMetadata
            {
                Name      = "fooBytes",
                Type      = "fooBytes",
                Direction = BindingDirection.In
            };

            var httpOutputBinding = new BindingMetadata
            {
                Name      = "res",
                Type      = "http",
                Direction = BindingDirection.Out,
                Raw       = new JObject(),
                DataType  = DataType.String
            };

            functionMetadata.Bindings.Add(httpTriggerBinding);
            functionMetadata.Bindings.Add(fooStrInputBinding);
            functionMetadata.Bindings.Add(fooBytesInputBinding);
            functionMetadata.Bindings.Add(httpOutputBinding);
            invocationContext.FunctionMetadata = functionMetadata;

            GrpcCapabilities capabilities = new GrpcCapabilities(logger);
            var result = await invocationContext.ToRpcInvocationRequest(logger, capabilities, isSharedMemoryDataTransferEnabled : true, _sharedMemoryManager);

            Assert.Equal(3, result.InputData.Count);

            Assert.Equal("fooStr", result.InputData[1].Name);
            Assert.Equal("fooBytes", result.InputData[2].Name);

            // The input data should be transferred over shared memory
            RpcSharedMemory sharedMem1 = result.InputData[1].RpcSharedMemory;

            // This is what the expected byte[] representation of the string should be
            // We use that to find expected length
            byte[] contentBytes = Encoding.UTF8.GetBytes(inputString);
            Assert.Equal(contentBytes.Length, sharedMem1.Count);

            // Check that the name of the shared memory map is a valid GUID
            Assert.True(Guid.TryParse(sharedMem1.Name, out _));

            // Check the type being sent
            Assert.Equal(sharedMem1.Type, RpcDataType.String);

            // The input data should be transferred over shared memory
            RpcSharedMemory sharedMem2 = result.InputData[2].RpcSharedMemory;

            Assert.Equal(inputBytes.Length, sharedMem2.Count);

            // Check that the name of the shared memory map is a valid GUID
            Assert.True(Guid.TryParse(sharedMem2.Name, out _));

            // Check the type being sent
            Assert.Equal(sharedMem2.Type, RpcDataType.Bytes);

            // Check that the inputs were inserted into shared memory
            object inputStringReadObj = await _sharedMemoryManager.GetObjectAsync(sharedMem1.Name, 0, (int)sharedMem1.Count, typeof(string));

            Assert.NotNull(inputStringReadObj);
            string inputStringRead = inputStringReadObj as string;

            Assert.Equal(inputString, inputStringRead);

            object inputBytesReadObj = await _sharedMemoryManager.GetObjectAsync(sharedMem2.Name, 0, (int)sharedMem2.Count, typeof(byte[]));

            Assert.NotNull(inputBytesReadObj);
            byte[] inputBytesRead = inputBytesReadObj as byte[];
            Assert.Equal(inputBytes, inputBytesRead);

            // Check that the inputs were not marked to be removed after the invocation
            Assert.Empty(_sharedMemoryManager.InvocationSharedMemoryMaps);

            // Check that the inputs were inserted into the cache
            Assert.True(_functionDataCache.TryGet(key1, isIncrementActiveReference: false, out _));
            Assert.True(_functionDataCache.TryGet(key2, isIncrementActiveReference: false, out _));
        }
コード例 #22
0
 public UHExchangeBinding(BindingMetadata exchangeBinding)
 {
     ArgumentValidator.ThrowIfNull("exchangeBinding", exchangeBinding);
     this.PrimarySmtpAddress = exchangeBinding.Name;
     this.displayName        = exchangeBinding.DisplayName;
 }
コード例 #23
0
ファイル: ModelBinderFactoryTest.cs プロジェクト: ymd1223/Mvc
        public void CreateBinder_PassesExpectedBindingInfo(
            BindingInfo parameterBindingInfo,
            BindingMetadata bindingMetadata,
            BindingInfo expectedInfo)
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();
            metadataProvider.ForType<Employee>().BindingDetails(binding =>
            {
                binding.BinderModelName = bindingMetadata.BinderModelName;
                binding.BinderType = bindingMetadata.BinderType;
                binding.BindingSource = bindingMetadata.BindingSource;
                if (bindingMetadata.PropertyFilterProvider != null)
                {
                    binding.PropertyFilterProvider = bindingMetadata.PropertyFilterProvider;
                }
            });

            var modelBinder = Mock.Of<IModelBinder>();
            var modelBinderProvider = new TestModelBinderProvider(context =>
            {
                Assert.Equal(typeof(Employee), context.Metadata.ModelType);

                Assert.NotNull(context.BindingInfo);
                Assert.Equal(expectedInfo.BinderModelName, context.BindingInfo.BinderModelName, StringComparer.Ordinal);
                Assert.Equal(expectedInfo.BinderType, context.BindingInfo.BinderType);
                Assert.Equal(expectedInfo.BindingSource, context.BindingInfo.BindingSource);
                Assert.Same(expectedInfo.PropertyFilterProvider, context.BindingInfo.PropertyFilterProvider);

                return modelBinder;
            });

            var options = new TestOptionsManager<MvcOptions>();
            options.Value.ModelBinderProviders.Insert(0, modelBinderProvider);

            var factory = new ModelBinderFactory(metadataProvider, options);
            var factoryContext = new ModelBinderFactoryContext
            {
                BindingInfo = parameterBindingInfo,
                Metadata = metadataProvider.GetMetadataForType(typeof(Employee)),
            };

            // Act & Assert
            var result = factory.CreateBinder(factoryContext);

            // Confirm our IModelBinderProvider was called.
            Assert.Same(modelBinder, result);
        }
コード例 #24
0
 public HttpBinding(ScriptHostConfiguration config, BindingMetadata metadata, FileAccess access) :
     base(config, metadata, access)
 {
 }
コード例 #25
0
        private BindingStorage GetBindingStorageForSubWorkload(IEnumerable <BindingStorage> bindingContainers, Workload subWorkload, Guid universalIdentity, bool createNewIfNotFound)
        {
            IEnumerable <BindingStorage> enumerable = from s in bindingContainers
                                                      where s.Workload == Workload.SharePoint
                                                      select s;
            BindingStorage bindingStorage3 = (from bindingStorage in enumerable
                                              where bindingStorage.Scopes.Any <string>()
                                              select bindingStorage).FirstOrDefault((BindingStorage bindingStorage) => BindingMetadata.FromStorage(bindingStorage.Scopes.First <string>()).Workload == subWorkload);

            if (bindingStorage3 != null)
            {
                return(bindingStorage3);
            }
            foreach (BindingStorage bindingStorage2 in enumerable)
            {
                if (!bindingStorage2.Scopes.Any <string>())
                {
                    bindingStorage3 = bindingStorage2;
                    return(bindingStorage3);
                }
            }
            if (createNewIfNotFound)
            {
                bindingStorage3 = Utils.CreateNewBindingStorage(base.OrganizationalUnitRoot, Workload.SharePoint, universalIdentity);
                this.StorageBindings.Add(bindingStorage3);
            }
            return(bindingStorage3);
        }
コード例 #26
0
 protected FunctionBinding(ScriptJobHostOptions options, BindingMetadata metadata, FileAccess access)
 {
     _options = options;
     Access   = access;
     Metadata = metadata;
 }
コード例 #27
0
        public async Task ToRpcInvocationRequest_Http_OmitsDuplicateBodyOfBindingData()
        {
            var logger = new TestLogger("test");

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Host   = new HostString("local");
            httpContext.Request.Path   = "/test";
            httpContext.Request.Method = "Post";

            var inputs = new List <(string name, DataType type, object val)>
            {
                ("req", DataType.String, httpContext.Request)
            };

            var bindingData = new Dictionary <string, object>
            {
                { "req", httpContext.Request },
                { "$request", httpContext.Request },
                { "headers", httpContext.Request.Headers.ToDictionary(p => p.Key, p => p.Value) },
                { "query", httpContext.Request.QueryString.ToString() },
                { "sys", new SystemBindingData() }
            };

            var invocationContext = new ScriptInvocationContext()
            {
                ExecutionContext = new ExecutionContext()
                {
                    InvocationId = Guid.NewGuid(),
                    FunctionName = "Test",
                },
                BindingData           = bindingData,
                Inputs                = inputs,
                ResultSource          = new TaskCompletionSource <ScriptInvocationResult>(),
                Logger                = logger,
                AsyncExecutionContext = System.Threading.ExecutionContext.Capture()
            };

            var functionMetadata = new FunctionMetadata
            {
                Name = "Test"
            };

            var httpTriggerBinding = new BindingMetadata
            {
                Name      = "req",
                Type      = "httpTrigger",
                Direction = BindingDirection.In,
                Raw       = new JObject()
            };

            var httpOutputBinding = new BindingMetadata
            {
                Name      = "res",
                Type      = "http",
                Direction = BindingDirection.Out,
                Raw       = new JObject(),
                DataType  = DataType.String
            };

            functionMetadata.Bindings.Add(httpTriggerBinding);
            functionMetadata.Bindings.Add(httpOutputBinding);
            invocationContext.FunctionMetadata = functionMetadata;

            GrpcCapabilities          capabilities      = new GrpcCapabilities(logger);
            MapField <string, string> addedCapabilities = new MapField <string, string>
            {
                { RpcWorkerConstants.RpcHttpTriggerMetadataRemoved, "1" },
                { RpcWorkerConstants.RpcHttpBodyOnly, "1" }
            };

            capabilities.UpdateCapabilities(addedCapabilities);

            var result = await invocationContext.ToRpcInvocationRequest(logger, capabilities, isSharedMemoryDataTransferEnabled : false, _sharedMemoryManager);

            Assert.Equal(1, result.InputData.Count);
            Assert.Equal(2, result.TriggerMetadata.Count);
            Assert.True(result.TriggerMetadata.ContainsKey("headers"));
            Assert.True(result.TriggerMetadata.ContainsKey("query"));
        }
コード例 #28
0
 public ExtensionBinding(ScriptHostConfiguration config, ScriptBinding binding, BindingMetadata metadata) : base(config, metadata, binding.Context.Access)
 {
     _binding   = binding;
     Attributes = _binding.GetAttributes();
 }
コード例 #29
0
        public async Task ToRpcInvocationRequest_MultipleInputBindings()
        {
            var logger = new TestLogger("test");

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Host   = new HostString("local");
            httpContext.Request.Path   = "/test";
            httpContext.Request.Method = "Post";

            var poco = new TestPoco {
                Id = 1, Name = "Test"
            };

            var bindingData = new Dictionary <string, object>
            {
                { "req", httpContext.Request },
                { "$request", httpContext.Request },
                { "headers", httpContext.Request.Headers.ToDictionary(p => p.Key, p => p.Value) },
                { "query", httpContext.Request.QueryString.ToString() },
                { "sys", new SystemBindingData() }
            };

            var inputs = new List <(string name, DataType type, object val)>
            {
                ("req", DataType.String, httpContext.Request),
                ("blob", DataType.String, null),  // verify that null values are handled
                ("foo", DataType.String, "test"),
                ("bar1", DataType.String, poco),
                ("bar2", DataType.String, poco)
            };

            var invocationContext = new ScriptInvocationContext()
            {
                ExecutionContext = new ExecutionContext()
                {
                    InvocationId = Guid.NewGuid(),
                    FunctionName = "Test",
                },
                BindingData           = bindingData,
                Inputs                = inputs,
                ResultSource          = new TaskCompletionSource <ScriptInvocationResult>(),
                Logger                = logger,
                AsyncExecutionContext = System.Threading.ExecutionContext.Capture()
            };

            var functionMetadata = new FunctionMetadata
            {
                Name = "Test"
            };

            var httpTriggerBinding = new BindingMetadata
            {
                Name      = "req",
                Type      = "httpTrigger",
                Direction = BindingDirection.In,
                Raw       = new JObject()
            };

            var blobInputBinding = new BindingMetadata
            {
                Name      = "blob",
                Type      = "blob",
                Direction = BindingDirection.In
            };

            var fooInputBinding = new BindingMetadata
            {
                Name      = "foo",
                Type      = "foo",
                Direction = BindingDirection.In
            };

            var barInputBinding1 = new BindingMetadata
            {
                Name      = "bar1",
                Type      = "bar",
                Direction = BindingDirection.In
            };

            var barInputBinding2 = new BindingMetadata
            {
                Name      = "bar2",
                Type      = "bar",
                Direction = BindingDirection.In
            };

            var httpOutputBinding = new BindingMetadata
            {
                Name      = "res",
                Type      = "http",
                Direction = BindingDirection.Out,
                Raw       = new JObject(),
                DataType  = DataType.String
            };

            functionMetadata.Bindings.Add(httpTriggerBinding);
            functionMetadata.Bindings.Add(blobInputBinding);
            functionMetadata.Bindings.Add(fooInputBinding);
            functionMetadata.Bindings.Add(barInputBinding1);
            functionMetadata.Bindings.Add(barInputBinding2);
            functionMetadata.Bindings.Add(httpOutputBinding);
            invocationContext.FunctionMetadata = functionMetadata;

            GrpcCapabilities capabilities = new GrpcCapabilities(logger);
            var result = await invocationContext.ToRpcInvocationRequest(logger, capabilities, isSharedMemoryDataTransferEnabled : false, _sharedMemoryManager);

            Assert.Equal(5, result.InputData.Count);

            Assert.Equal("req", result.InputData[0].Name);
            var resultHttp = result.InputData[0].Data;

            Assert.Equal("http://local/test", ((RpcHttp)result.InputData[0].Data.Http).Url);

            // verify the null input was propagated properly
            Assert.Equal("blob", result.InputData[1].Name);
            Assert.Equal(string.Empty, result.InputData[1].Data.String);

            Assert.Equal("foo", result.InputData[2].Name);
            Assert.Equal("test", result.InputData[2].Data.String);

            Assert.Equal("bar1", result.InputData[3].Name);
            var resultPoco = result.InputData[3].Data;

            Assert.Equal("{\"Name\":\"Test\",\"Id\":1}", resultPoco.Json);

            Assert.Equal("bar2", result.InputData[4].Name);
            Assert.Same(resultPoco, result.InputData[4].Data);

            Assert.Equal(4, result.TriggerMetadata.Count);
            Assert.Same(resultHttp, result.TriggerMetadata["req"]);
            Assert.Same(resultHttp, result.TriggerMetadata["$request"]);
            Assert.True(result.TriggerMetadata.ContainsKey("headers"));
            Assert.True(result.TriggerMetadata.ContainsKey("query"));
        }