コード例 #1
0
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            var reader  = new StreamReader(context.Request.Body);
            var request = JsonConvert.DeserializeObject <PostComplexARequest>(reader.ReadToEnd());

            return(request);
        }
コード例 #2
0
        /// <summary>
        ///     Bind to the given model type
        /// </summary>
        /// <param name="context">Current context</param>
        /// <param name="modelType">Model type to bind to</param>
        /// <param name="instance">Optional existing instance</param>
        /// <param name="configuration">The <see cref="BindingConfig" /> that should be applied during binding.</param>
        /// <param name="blackList">Blacklisted property names</param>
        /// <returns>Bound model</returns>
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration,
            params string[] blackList)
        {
            Type genericType = null;
            if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable())
            {
                //make sure it has a generic type
                if (modelType.IsGenericType())
                {
                    genericType = modelType.GetGenericArguments().FirstOrDefault();
                }
                else
                {
                    var implementingIEnumerableType =
                        modelType.GetInterfaces().Where(i => i.IsGenericType()).FirstOrDefault(
                            i => i.GetGenericTypeDefinition() == typeof (IEnumerable<>));
                    genericType = implementingIEnumerableType == null ? null : implementingIEnumerableType.GetGenericArguments().FirstOrDefault();
                }

                if (genericType == null)
                {
                    throw new ArgumentException("When modelType is an enumerable it must specify the type", "modelType");
                }
            }

            var bindingContext =
                CreateBindingContext(context, modelType, instance, configuration, blackList, genericType);

            var bodyDeserializedModel = DeserializeRequestBody(bindingContext);

            return (instance as IEnumerable<string>) ?? bodyDeserializedModel;
        }
コード例 #3
0
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration,
                           params string[] blackList)
        {
            using (var streamReader = new StreamReader(context.Request.Body))
            {
                var jsonBody = JObject.Parse(streamReader.ReadToEnd());

                JToken purposeId;
                JToken providerId;
                JToken virtualNumber;

                jsonBody.TryGetValue("purposeId", out purposeId);
                jsonBody.TryGetValue("providerId", out providerId);
                jsonBody.TryGetValue("virtualPhoneNumber", out virtualNumber);

                if (purposeId == null ||
                    providerId == null ||
                    virtualNumber == null)
                {
                    throw new ArgumentException();
                }

                var phoneNumber = virtualNumber.ToObject <PhoneNumber>();

                return(new VirtualNumber
                {
                    PurposeId = purposeId.ToObject <int>(),
                    ProviderId = providerId.ToObject <int>(),
                    VirtualPhoneNumber = phoneNumber
                });
            }
        }
コード例 #4
0
        /// <summary>
        /// Optional override to create listeners (e.g., TCP, HTTP) for this service replica to handle client or user requests.
        /// </summary>
        /// <returns>A collection of listeners.</returns>
        protected override IEnumerable <ServiceInstanceListener> CreateServiceInstanceListeners()
        {
            Binding binding = new BindingConfig().GetBinding();

            string host           = this.Context.NodeContext.IPAddressOrFQDN;
            var    endpointConfig = this.Context.CodePackageActivationContext.GetEndpoint("ServiceEndpoint");
            int    port           = endpointConfig.Port;
            string scheme         = endpointConfig.Protocol.ToString();
            string nodeName       = this.Context.NodeContext.NodeName;
            string servicename    = this.Context.ServiceTypeName;
            string uri            = string.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}/{3}/{4}.svc", "net." + scheme, host, port, nodeName, servicename);

            WcfCommunicationListener <IPresidentialService> pressListener = new WcfCommunicationListener <IPresidentialService>(this.Context, this, binding, new EndpointAddress(uri));

            // Check to see if the service host already has a ServiceMetadataBehavior, If not, add one                      // For net.tcp need to find a way to expose metadata
            //if (pressListener.ServiceHost.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
            //{
            //    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
            //    behavior.HttpGetEnabled = true;           // need to figure it out how to bypass this for net.tcp
            //    behavior.HttpGetUrl = new Uri(uri + "mex/");  // need to figure it out how to bypass this for net.tcp
            //    pressListener.ServiceHost.Description.Behaviors.Add(behavior);
            //    pressListener.ServiceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), uri + "mex/");
            //}

            ServiceInstanceListener listener = new ServiceInstanceListener(context => pressListener);

            return(new[] { listener });
        }
コード例 #5
0
        public Injector()
        {
            // Registration of resolvers
            allResolvers = new SafeDictionary <BindingKey, IResolver>(syncLock);

            // Registration of binding key resolvers
            implicitBindingResolver = new ImplicitBindingResolver(syncLock);
            genericBindingRresolver = new GenericBindingResolver(this, syncLock);

            // Init resolvers cache
            instanceResolversCache = new SafeDictionary <Type, IResolver>(syncLock);

            // Init resolver
            Expression <Action> tmpExpr = () => CreateResolverInstance <Exception, Exception>(null, null);

            createResolverInstanceGeneric = ((MethodCallExpression)tmpExpr.Body).Method.GetGenericMethodDefinition();

            // Init bindExplicit
            Expression <Action> tmpBindExpr = () => BindExplicit <Exception, Exception> (null, null);

            bindExplicitGeneric = ((MethodCallExpression)tmpBindExpr.Body).Method.GetGenericMethodDefinition();

            // Implicitly resolvable
            Expression <Func <Injector> > injectorFactoryExpr = () => this;
            var bindingConfig = new BindingConfig(typeof(Injector));

            bindingConfig.FactoryExpression = injectorFactoryExpr;
            bindingConfig.Lifestyle         = Lifestyle.Singleton;
            var injectorResolver = BindExplicit <Injector, Injector>(BindingKey.Get(typeof(Injector)), bindingConfig);
        }
コード例 #6
0
        /// <summary>
        ///     Bind to the given model type
        /// </summary>
        /// <param name="context">Current context</param>
        /// <param name="modelType">Model type to bind to</param>
        /// <param name="instance">Optional existing instance</param>
        /// <param name="configuration">The <see cref="BindingConfig" /> that should be applied during binding.</param>
        /// <param name="blackList">Blacklisted property names</param>
        /// <returns>Bound model</returns>
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration,
                           params string[] blackList)
        {
            Type genericType = null;

            if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable())
            {
                //make sure it has a generic type
                if (modelType.IsGenericType())
                {
                    genericType = modelType.GetGenericArguments().FirstOrDefault();
                }
                else
                {
                    var implementingIEnumerableType =
                        modelType.GetInterfaces().Where(i => i.IsGenericType()).FirstOrDefault(
                            i => i.GetGenericTypeDefinition() == typeof(IEnumerable <>));
                    genericType = implementingIEnumerableType == null ? null : implementingIEnumerableType.GetGenericArguments().FirstOrDefault();
                }

                if (genericType == null)
                {
                    throw new ArgumentException("When modelType is an enumerable it must specify the type", "modelType");
                }
            }

            var bindingContext =
                CreateBindingContext(context, modelType, instance, configuration, blackList, genericType);

            var bodyDeserializedModel = DeserializeRequestBody(bindingContext);

            return((instance as IEnumerable <string>) ?? bodyDeserializedModel);
        }
コード例 #7
0
        public void ShouldAuthBeforeManaging()
        {
            // Arrange
            BindingConfig testData = new BindingConfig()
            {
                ComponentName = "exchange_1",
                Bindings      = new List <BindingConfigEntry>
                {
                    new BindingConfigEntry {
                        ComponentName = "queue_1", RoutingKey = "#1"
                    },
                    new BindingConfigEntry {
                        ComponentName = "queue_2", RoutingKey = "#2"
                    }
                }
            };
            var managementProvider   = Substitute.For <IRmqManagementService>();
            var configurationService = new RmqBindingService(managementProvider);

            // Act
            configurationService.Build(testData);

            // Assert
            Received.InOrder(() =>
            {
                managementProvider.Auth();
                managementProvider.CreateDirectExchange(Arg.Any <string>());
                managementProvider.CreateQueue(Arg.Any <string>());
                managementProvider.BindQueueToExchange(Arg.Any <string>(), Arg.Any <BindingConfigEntry>());
                managementProvider.CreateQueue(Arg.Any <string>());
                managementProvider.BindQueueToExchange(Arg.Any <string>(), Arg.Any <BindingConfigEntry>());
            });
        }
コード例 #8
0
        public void ShouldNotCallManagementProviderIfExchangeNameIsWhitespace()
        {
            // Arrange
            BindingConfig testData = new BindingConfig()
            {
                ComponentName = " ",
                Bindings      = new List <BindingConfigEntry>
                {
                    new BindingConfigEntry {
                        ComponentName = "queue_1", RoutingKey = "#1"
                    },
                    new BindingConfigEntry {
                        ComponentName = "queue_2", RoutingKey = "#2"
                    }
                }
            };
            var managementProvider   = Substitute.For <IRmqManagementService>();
            var configurationService = new RmqBindingService(managementProvider);

            // Act
            try
            {
                configurationService.Build(testData);
            }
            catch (AggregateException ex)
            {
                Assert.AreEqual(
                    "Exchange name cannot be empty",
                    ex.InnerException.Message);
            }
        }
コード例 #9
0
        public static bool LoadBindingConfigFromFile(string configPath)
        {
            if (string.IsNullOrEmpty(configPath) || !File.Exists(configPath))
            {
                return(false);
            }

            using (var inputFile = new StreamReader(configPath))
            {
                s_bindingConfig = JsonUtility.FromJson <BindingConfig>(inputFile.ReadToEnd());

                foreach (var roleData in s_bindingConfig.roles)
                {
                    foreach (var binding in roleData.bindings)
                    {
                        if (VRModule.IsDeviceConnected(binding.device_sn))
                        {
                            s_modelHintTable[binding.device_sn] = VRModule.GetCurrentDeviceState(VRModule.GetConnectedDeviceIndex(binding.device_sn)).deviceModel;
                        }
                        else
                        {
                            s_modelHintTable[binding.device_sn] = binding.device_model;
                        }
                    }
                }

                return(true);
            }
        }
コード例 #10
0
 public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
 {
     using (var rdr = new StreamReader(context.Request.Body))
     {
         return(rdr.ReadToEnd());
     }
 }
コード例 #11
0
        /// <summary>
        /// Optional override to create listeners (e.g., TCP, HTTP) for this service replica to handle client or user requests.
        /// </summary>
        /// <returns>A collection of listeners.</returns>
        protected override IEnumerable <ServiceInstanceListener> CreateServiceInstanceListeners()
        {
            Binding binding = new BindingConfig().GetBindingWSHttp();

            // set the proper way to expose the URI on cluster manager
            string host           = this.Context.NodeContext.IPAddressOrFQDN;
            var    endpointConfig = this.Context.CodePackageActivationContext.GetEndpoint("ServiceHttpEndPoint");
            int    port           = endpointConfig.Port;
            string scheme         = endpointConfig.Protocol.ToString();
            string nodeName       = this.Context.NodeContext.NodeName;
            string servicename    = this.Context.ServiceTypeName;
            string uri            = string.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}/{3}/{4}.svc", scheme, host, port, nodeName, servicename);

            WcfCommunicationListener <IPressContract> pressListener = new WcfCommunicationListener <IPressContract>(this.Context, this, binding, new EndpointAddress(uri));

            // Check to see if the service host already has a ServiceMetadataBehavior, If not, add one
            if (pressListener.ServiceHost.Description.Behaviors.Find <ServiceMetadataBehavior>() == null)
            {
                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                behavior.HttpGetEnabled = true;
                behavior.HttpGetUrl     = new Uri(uri + "/mex/");
                pressListener.ServiceHost.Description.Behaviors.Add(behavior);
                pressListener.ServiceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), uri + "/mex/");
            }

            ServiceInstanceListener listener = new ServiceInstanceListener(context => pressListener);

            return(new[] { listener });
        }
コード例 #12
0
        public async Task ExternalsAreNotDownloadedOnlyWhenRequested(bool shouldDownload)
        {
            var externals = Path.Combine(RootDirectory, "externals");
            var generated = Path.Combine(RootDirectory, "generated");

            var config = new BindingConfig
            {
                DownloadExternals = shouldDownload,
                ExternalsDir      = externals,
                BasePath          = RootDirectory,
                Templates         = { new TemplateConfig(CreateTemplate(), "generated/{artifactid}.csproj") },
                MavenArtifacts    =
                {
                    new MavenArtifactConfig
                    {
                        GroupId        = "androidx.annotation",
                        ArtifactId     = "annotation",
                        Version        = "1.0.2",
                        NugetPackageId = "Xamarin.AndroidX.Annotation",
                    }
                }
            };

            await Engine.BinderateAsync(config);

            Assert.True(File.Exists(Path.Combine(generated, "annotation.csproj")));
            Assert.Equal(shouldDownload, Directory.Exists(externals));
            Assert.Equal(shouldDownload, File.Exists(Path.Combine(externals, "androidx.annotation", "annotation.jar")));
        }
コード例 #13
0
        public Packets()
        {
            InitializeGet(Helper.Servers, "packets");
            InitializeGetAll(Helper.Servers, "packets");
            InitializeEnable(Helper.Servers, "packets");

            Put["/packets", true] = async(_, ct) =>
            {
                Request.PacketDownload request;
                try
                {
                    var config = new BindingConfig {
                        BodyOnly = true, IgnoreErrors = false
                    };
                    request        = this.Bind <Request.PacketDownload>(config);
                    request.ApiKey = Guid.Parse(Context.CurrentUser.UserName);

                    var results = Validate(request);
                    if (results.Count > 0)
                    {
                        return(CreateErrorResponseAndUpdateApiKey((from result in results select result.ErrorMessage).Implode(", ")));
                    }
                }
                catch (Exception ex)
                {
                    return(CreateErrorResponseAndUpdateApiKey(ex.Message));
                }

                return(ExecuteDownloadRequest(request));
            };
        }
コード例 #14
0
ファイル: ModelBinder.cs プロジェクト: amacal/tick-tock
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            IDictionary <string, object> data  = GetDataFields(context);
            DynamicDictionary            model = DynamicDictionary.Create(data);

            return(model);
        }
コード例 #15
0
        static void Main(string[] args)
        {
            // binding data
            Binding binding = new BindingConfig().GetBindingWSHttp();

            ServicePartitionResolver spr = new ServicePartitionResolver(() => new FabricClient());
            WcfCommunicationClientFactory <IPressContract> communicationClientFactory = new WcfCommunicationClientFactory <IPressContract>(binding, servicePartitionResolver: spr);
            Uri uri = new Uri("fabric:/Political/PressService");

            PresidentialServiceClient pressClient = new PresidentialServiceClient(communicationClientFactory, uri);

            int Id = 15;

            Console.WriteLine(pressClient.InterviewPresidentName(Id).Result);

            ListEndpoints();    // DANIEL: List the total available endpoints in the cluster

            Console.ReadKey();

            // test the deployment
            //int number = 0;
            //while (true)
            //{
            //    number++;
            //    Console.WriteLine(pressClient.InterviewPresidentName(number).Result);
            //    Thread.Sleep(1000);
            //}
        }
コード例 #16
0
        static void Main(string[] args)
        {
            // binding data
            Binding binding = new BindingConfig().GetBinding();

            ServicePartitionResolver spr = new ServicePartitionResolver(() => new FabricClient());
            WcfCommunicationClientFactory <IPresidentialService> communicationClientFactory = new WcfCommunicationClientFactory <IPresidentialService>(binding, servicePartitionResolver: spr);
            Uri uri = new Uri("fabric:/Political/PresidentialService");

            PresidentialServiceClient presidentialServiceClient = new PresidentialServiceClient(communicationClientFactory, uri);

            //int Id = 15;
            //string presidentName = presidentialServiceClient.PresidentName(Id).Result;
            //Console.WriteLine(presidentName);
            //string presidents = presidentialServiceClient.Presidents().Result;
            //Console.WriteLine(presidents);
            //Console.ReadKey();

            // test the deployment
            int number = 0;

            while (true)
            {
                number++;
                Console.WriteLine(presidentialServiceClient.PresidentName(number).Result);
                Console.WriteLine(presidentialServiceClient.Presidents().Result);
                Console.WriteLine(" ");
                Thread.Sleep(1000);
            }
        }
コード例 #17
0
        /// <summary>
        /// Retrieves an instance of the type bound to the specified interface based on its
        /// unique key. This is how you retrieve a multibound concrete type. Just provide
        /// the interface type and the key you provided during binding. The optional
        /// parameter allows you to force the retrieval of a singleton or instance binding,
        /// in case you have multibound the same interface to both a singleton and an
        /// instance. By default, the method will check for a singleton first, if none is
        /// found, then an instance is returned.
        /// </summary>
        /// <typeparam name="T">The interface type to which a concrete type is multibound</typeparam>
        /// <param name="multiBindKey">The key used to identify a particular multibinding</param>
        /// <returns>A concrete instance of the specified multibound interface type</returns>
        public static T Get <T>(string multiBindKey, BindingConfig config = BindingConfig.Default)
        {
            AssertInterface <T>("Factory.New");

            T instance = multiBindMap.Get <T>(multiBindKey, config);

            return(instance);
        }
コード例 #18
0
        public SingularityAdapter()
        {
            Scene.ComponentAdded += OnComponentAdded;
            Scene.Entered        += OnSceneEnter;
            Scene.Leaving        += OnSceneLeave;

            _config = new BindingConfig();
        }
コード例 #19
0
 public static TModel Bind <TModel>(this NancyModule module, BindingConfig configuration)
 {
     if (module == null)
     {
         throw new ArgumentNullException(nameof(module));
     }
     return(module.Bind <TModel>(configuration, null));
 }
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            var request = (instance as GetActiveCardsRequest) ?? new GetActiveCardsRequest();

            request.CRACKER_API_KEY = context.Request.Headers[nameof(request.CRACKER_API_KEY)].FirstOrDefault();

            return(request);
        }
コード例 #21
0
ファイル: UploadRequest.cs プロジェクト: zjuidg/iStoryline
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration,
                           params string[] blackList)
        {
            var fileUploadRequest = instance as UploadRequest ?? new UploadRequest();

            fileUploadRequest.File = GetFileByKey(context, "file");
            return(fileUploadRequest);
        }
コード例 #22
0
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            var fileUploadRequest = (instance as FileUploadRequest) ?? new FileUploadRequest();

            fileUploadRequest.UserId = GetUserId(context);
            fileUploadRequest.File   = GetFile(context);

            return(fileUploadRequest);
        }
コード例 #23
0
        public void Should_allow_overwrite_on_new_instance()
        {
            // Given
            // When
            var instance = new BindingConfig();

            // Then
            instance.Overwrite.ShouldBeTrue();
        }
コード例 #24
0
        internal BoundOpenGenericBinding(Type bindingType, Type concreteType)
        {
            ValidateGenericType(bindingType);
            ValidateGenericType(concreteType);

            BindingConfig = new BindingConfig(concreteType);
            BindingKey    = BindingKey.Get(bindingType);
            ConcreteType  = concreteType;
        }
コード例 #25
0
        public TRequest BindFromBody <TRequest>() where TRequest : class, new()
        {
            var bindingConfig = new BindingConfig
            {
                BodyOnly = true
            };

            return(this.Bind <TRequest>(bindingConfig));
        }
コード例 #26
0
        /// <summary>
        /// Bind to the given model type
        /// </summary>
        /// <param name="context">Current context</param>
        /// <param name="modelType">Model type to bind to</param>
        /// <param name="instance">Optional existing instance</param>
        /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
        /// <param name="blackList">Blacklisted property names</param>
        /// <returns>Bound model</returns>
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            var customer = (instance as Customer) ?? new Customer();

            customer.Name        = customer.Name ?? context.Request.Form["Name"];
            customer.RenewalDate = customer.RenewalDate == default(DateTime) ? context.Request.Form["RenewalDate"] : customer.RenewalDate;

            return(customer);
        }
コード例 #27
0
 public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
 {
     using (var reader = new StreamReader(context.Request.Body))
     {
         var jObject         = JObject.Parse(reader.ReadToEnd());
         var machineTypeName = jObject["machineType"].Value <string>();
         return(jObject.ToObject(Machine.GetMachineType(machineTypeName)));
     }
 }
コード例 #28
0
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            var uploadFileRequest = (instance as UploadFileRequest) ?? new UploadFileRequest();

            uploadFileRequest.PetId = context.Request.Query.petId;
            uploadFileRequest.AdditionalMetadata = context.Request.Form.additionalMetadata;
            uploadFileRequest.File = context.Request.Files.FirstOrDefault();

            return(uploadFileRequest);
        }
        /// <summary>
        /// The bind.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <param name="modelType">
        /// The model type.
        /// </param>
        /// <param name="instance">
        /// The instance.
        /// </param>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        /// <param name="blackList">
        /// The black list.
        /// </param>
        /// <returns>
        /// The <see cref="object"/>.
        /// </returns>
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            var exchangeFileUpload = (instance as ExchangeFileUploadRequest) ?? new ExchangeFileUploadRequest();

            exchangeFileUpload.Password    = context.Request.Form["password"];
            exchangeFileUpload.File        = this.GetFileByKey(context, "file");
            exchangeFileUpload.ContentSize = this.GetContentSize(context);

            return(exchangeFileUpload);
        }
コード例 #30
0
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            var fileUploadRequest = (instance as FileUploadRequest) ?? new FileUploadRequest();

            var form = context.Request.Form;

            fileUploadRequest.Files = context.Request.Files.ToList();

            return(fileUploadRequest);
        }
コード例 #31
0
 public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
 {
     using (var sr = new StreamReader(context.Request.Body))
     {
         return((new JavaScriptSerializer()
         {
             RetainCasing = true
         }).Deserialize <Model>(sr.ReadToEnd()));
     }
 }
コード例 #32
0
 private BindingContext CreateBindingContext(NancyContext context, Type modelType, object instance,
     BindingConfig configuration, IEnumerable<string> blackList, Type genericType)
 {
     return new BindingContext
     {
         Configuration = configuration,
         Context = context,
         DestinationType = modelType,
         Model = CreateModel(modelType, genericType, instance),
         ValidModelProperties = GetProperties(modelType, genericType, blackList),
         RequestData = GetDataFields(context),
         GenericType = genericType,
         TypeConverters = typeConverters.Concat(defaults.DefaultTypeConverters),
     };
 }