public void Initialize() { var value = new Mock<IFoo>(); value.SetupProperty(x => x.Message); var valueProvider = new Mock<IValueProvider>(); valueProvider.Setup(x => x.Evaluate()).Returns(ValueProviderValue); var compositionService = new Mock<IBindingCompositionService>(); compositionService.Setup(cs => cs.GetExports<IFoo, IComponentMetadata>()) .Returns(new[] { new Lazy<IFoo, IComponentMetadata>(() => value.Object, Mocks.Of<IComponentMetadata>().First(m => m.CatalogName == Catalog.DefaultCatalogName && m.Id == "Foo")) }); compositionService.Setup(cs => cs.GetExports<IValueProvider, IComponentMetadata>()) .Returns(new[] { new Lazy<IValueProvider, IComponentMetadata>(() => valueProvider.Object, Mocks.Of<IComponentMetadata>().First(m => m.CatalogName == Catalog.DefaultCatalogName && m.Id == "ValueProvider")) }); this.target = new BindingFactory(compositionService.Object); }
public void CreatePropertyBinding_ValueConverterNull_Throws() { var subject = new BindingFactory(); // ReSharper disable once AssignNullToNotNullAttribute Assert.Throws<ArgumentNullException>(() => subject.CreatePropertyBinding( BindingType.TwoWay, Mock.Of<IDependencyProperty<int>>(), Mock.Of<INotifyingObject<int>>(), null)); }
public void CreatePropertyBinding_ParamsNotNull_NotNull() { var subject = new BindingFactory(); var result = subject.CreatePropertyBinding( BindingType.TwoWay, Mock.Of<IDependencyProperty<int>>(), Mock.Of<INotifyingObject<int>>(), Mock.Of<ValueConverter<int, int>>()); Assert.IsNotNull(result); }
public void when_resolving_binding_then_resolves_type() { var config = new BindingConfiguration(typeof(GenerateCode)) { Properties = { new PropertyBindingConfiguration("TargetFileName") { ValueProvider = new BindingConfiguration(typeof(ExpressionValueProvider)) { Properties = { new PropertyBindingConfiguration("Expression") { ValueProvider = new BindingConfiguration(typeof(ExpressionValueProvider)) { Properties = { new PropertyBindingConfiguration("Expression") { Value = "{Name}Controller", } } } } } } }, new PropertyBindingConfiguration("TargetPath") { Value = "~", }, } }; var context = new ComponentContext(); var factory = new BindingFactory(); var binding = factory.CreateBinding<GenerateCode>(context, config); var command = (GenerateCode)binding.Instance; binding.Refresh(); Assert.Equal("~", command.TargetPath); Assert.Equal("{Name}Controller11", command.TargetFileName); binding.Refresh(); Assert.Equal("~", command.TargetPath); Assert.Equal("{Name}Controller22", command.TargetFileName); }
public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } ParameterInfo parameter = context.Parameter; EventHubTriggerAttribute attribute = parameter.GetCustomAttribute <EventHubTriggerAttribute>(inherit: false); if (attribute == null) { return(Task.FromResult <ITriggerBinding>(null)); } Func <ListenerFactoryContext, bool, Task <IListener> > createListener = (factoryContext, singleDispatch) => { var options = _options.Value; var checkpointStore = new BlobCheckpointStoreInternal( _clientFactory.GetCheckpointStoreClient(), factoryContext.Descriptor.Id, _loggerFactory.CreateLogger <BlobCheckpointStoreInternal>()); IListener listener = new EventHubListener( factoryContext.Descriptor.Id, factoryContext.Executor, _clientFactory.GetEventProcessorHost(attribute.EventHubName, attribute.Connection, attribute.ConsumerGroup, singleDispatch), singleDispatch, _clientFactory.GetEventHubConsumerClient(attribute.EventHubName, attribute.Connection, attribute.ConsumerGroup), checkpointStore, options, _loggerFactory); return(Task.FromResult(listener)); }; #pragma warning disable 618 ITriggerBinding binding = BindingFactory.GetTriggerBinding(new EventHubTriggerBindingStrategy(), parameter, _converterManager, createListener); #pragma warning restore 618 ITriggerBinding eventHubTriggerBindingWrapper = new EventHubTriggerBindingWrapper(binding); return(Task.FromResult(eventHubTriggerBindingWrapper)); }
static void Main(string[] argv) { faceSearch = new FaceSearchWrapper.FaceSearch(); motionDetector = new MotionDetectWrapper.MotionDetector(); ImageSampleCount = System.IO.Directory.GetFiles(Properties.Settings.Default.FaceSampleLib, "*.jpg").Length; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); #if !DEBUG if (!Util.VerifyKey()) { RegisterForm form = new RegisterForm(); DialogResult res = form.ShowDialog(); if (res == DialogResult.OK) { Application.Restart(); } return; } #endif if (argv.Length > 0) { directory = argv[0]; } string baseAddress = string.Format("net.tcp://{0}:8000", System.Net.IPAddress.Any); Uri netTcpBaseAddress = new Uri(baseAddress); ServiceHost host = new ServiceHost(typeof(Service.Service), netTcpBaseAddress); NetTcpBinding tcpBinding = BindingFactory.CreateNetTcpBinding(); host.AddServiceEndpoint(typeof(RemoteControlService.IServiceFacade), tcpBinding, "TcpService"); host.Open(); Application.Run(new MainForm()); }
public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context) { if (context == null) { throw new ArgumentNullException("context"); } ParameterInfo parameter = context.Parameter; EventHubTriggerAttribute attribute = parameter.GetCustomAttribute <EventHubTriggerAttribute>(inherit: false); if (attribute == null) { return(Task.FromResult <ITriggerBinding>(null)); } string eventHubName = attribute.EventHubName; string resolvedEventHubName = _nameResolver.ResolveWholeString(eventHubName); string consumerGroup = attribute.ConsumerGroup; if (consumerGroup == null) { consumerGroup = Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName; } string resolvedConsumerGroup = _nameResolver.ResolveWholeString(consumerGroup); var eventHostListener = _eventHubConfig.GetEventProcessorHost(resolvedEventHubName, resolvedConsumerGroup); var options = _eventHubConfig.GetOptions(); var hooks = new EventHubTriggerBindingStrategy(); Func <ListenerFactoryContext, bool, Task <IListener> > createListener = (factoryContext, singleDispatch) => { IListener listener = new EventHubListener(factoryContext.Executor, eventHostListener, options, singleDispatch); return(Task.FromResult(listener)); }; ITriggerBinding binding = BindingFactory.GetTriggerBinding <EventData, EventHubTriggerInput>(hooks, parameter, _converterManager, createListener); return(Task.FromResult <ITriggerBinding>(binding)); }
private static void securelyUpdateEndpointConfiguration(ConfiguredEndpoint ep, ApplicationConfiguration applicationConfiguration) { // ep.UpdateFromServer(...) looks for matching endpoints on the server. // If there is no match with the same securityMode and securityPolicy, it will simply // _replace_ ep by one of the server endpoints, possibly lowering the security settings. Therefore: // save old settings - update from server - verify security settings -- and throw update from server away if security settings have changed. // note that ConfiguredEndpoints need a collection to live in. Note also that some settings of the configured endpoint may be changed nonetheless behind the scenes. ConfiguredEndpointCollection cepc = new ConfiguredEndpointCollection(); EndpointDescription epd = (EndpointDescription)ep.Description.Clone(); ConfiguredEndpoint cep = new ConfiguredEndpoint(cepc, epd); Opc.Ua.BindingFactory bindingFactory = BindingFactory.Create(applicationConfiguration, applicationConfiguration.CreateMessageContext()); ep.UpdateFromServer(bindingFactory); if (ep.Description.SecurityMode != epd.SecurityMode || ep.Description.SecurityPolicyUri != epd.SecurityPolicyUri) { ep.Update(cep); throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "No endpoint with matching security configuration could be found during updated on connect."); } }
private ITriggerBinding CreateBindingStrategy <TKey, TValue>(ParameterInfo parameter, KafkaListenerConfiguration listenerConfiguration, bool requiresKey, IDeserializer <TValue> valueDeserializer) { // TODO: reuse connections if they match with others in same function app Task <IListener> listenerCreator(ListenerFactoryContext factoryContext, bool singleDispatch) { var listener = new KafkaListener <TKey, TValue>( factoryContext.Executor, singleDispatch, this.options.Value, listenerConfiguration, requiresKey, valueDeserializer, this.logger, factoryContext.Descriptor.Id); return(Task.FromResult <IListener>(listener)); } return(BindingFactory.GetTriggerBinding(new KafkaTriggerBindingStrategy <TKey, TValue>(), parameter, new KafkaEventDataConvertManager(this.converterManager, this.logger), listenerCreator)); }
/// <summary> /// Creates a session. /// </summary> private Session CreateSession( ApplicationConfiguration configuration, BindingFactory bindingFactory, ConfiguredEndpoint endpoint, IUserIdentity identity) { Report("Creating new Session with URL = {0}", endpoint.EndpointUrl); // Initialize the channel which will be created with the server. ITransportChannel channel = SessionChannel.Create( configuration, endpoint.Description, endpoint.Configuration, configuration.SecurityConfiguration.ApplicationCertificate.Find(true), configuration.CreateMessageContext()); // Wrap the channel with the session object. Session session = new Session(channel, configuration, endpoint, null); session.ReturnDiagnostics = DiagnosticsMasks.All; // register keep alive callback. session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); // create the user identity. if (identity == null) { if (endpoint.Description.UserIdentityTokens.Count > 0) { identity = CreateUserIdentity(endpoint.Description.UserIdentityTokens[0]); } } // Create the session. This actually connects to the server. session.Open(Guid.NewGuid().ToString(), identity); Report("Successfully created new Session."); // return the session. return(session); }
/// <inheritdoc /> public void Initialize(ExtensionConfigContext context) { if (context == null) { throw new ArgumentNullException("context"); } _nameResolver = context.Config.GetService <INameResolver>(); IConverterManager converterManager = context.Config.GetService <IConverterManager>(); // Set defaults, to be used if no other values are found: _defaultApiKey = _nameResolver.Resolve(AzureWebJobsMobileAppApiKeyName); string uriString = _nameResolver.Resolve(AzureWebJobsMobileAppUriName); Uri.TryCreate(uriString, UriKind.Absolute, out _defaultMobileAppUri); BindingFactory factory = new BindingFactory(_nameResolver, converterManager); IBindingProvider outputProvider = factory.BindToCollector <MobileTableAttribute, OpenType>(typeof(MobileTableCollectorBuilder <>), this); IBindingProvider clientProvider = factory.BindToInput <MobileTableAttribute, IMobileServiceClient>(new MobileTableClientBuilder(this)); IBindingProvider queryProvider = factory.BindToInput <MobileTableAttribute, IMobileServiceTableQuery <OpenType> >(typeof(MobileTableQueryBuilder <>), this); queryProvider = factory.AddFilter <MobileTableAttribute>(IsQueryType, queryProvider); IBindingProvider jObjectTableProvider = factory.BindToInput <MobileTableAttribute, IMobileServiceTable>(new MobileTableJObjectTableBuilder(this)); IBindingProvider tableProvider = factory.BindToInput <MobileTableAttribute, IMobileServiceTable <OpenType> >(typeof(MobileTablePocoTableBuilder <>), this); tableProvider = factory.AddFilter <MobileTableAttribute>(IsTableType, tableProvider); IBindingProvider itemProvider = factory.BindToGenericValueProvider <MobileTableAttribute>(BindForItemAsync); itemProvider = factory.AddFilter <MobileTableAttribute>(IsItemType, itemProvider); IExtensionRegistry extensions = context.Config.GetService <IExtensionRegistry>(); extensions.RegisterBindingRules <MobileTableAttribute>(ValidateMobileAppUri, _nameResolver, outputProvider, clientProvider, jObjectTableProvider, queryProvider, tableProvider, itemProvider); }
public TextBox(ISpriteFont spriteFont) { _textBlock = new TextBlock(spriteFont) { Margin = new Thickness(3, 6), Foreground = new SolidColorBrush(Colors.Black), }; _textBlock.Bind(TextBlock.TextProperty, BindingFactory.CreateOneWay(this, TextProperty)); Content = new Border() { Background = new SolidColorBrush(Colors.Gray), BorderThickness = new Thickness(1), Child = _textBlock, }; _clickSubscription = Gestures .Where(gesture => gesture.Type == GestureType.LeftButtonDown) .Subscribe(HandleClick); }
public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context) { if (context == null) { throw new ArgumentNullException("context"); } ParameterInfo parameter = context.Parameter; EventHubTriggerAttribute attribute = parameter.GetCustomAttribute <EventHubTriggerAttribute>(inherit: false); if (attribute == null) { return(Task.FromResult <ITriggerBinding>(null)); } string resolvedEventHubName = _nameResolver.ResolveWholeString(attribute.EventHubName); string consumerGroup = attribute.ConsumerGroup ?? PartitionReceiver.DefaultConsumerGroupName; string resolvedConsumerGroup = _nameResolver.ResolveWholeString(consumerGroup); if (!string.IsNullOrWhiteSpace(attribute.Connection)) { attribute.Connection = _nameResolver.ResolveWholeString(attribute.Connection); var connectionString = _config.GetConnectionStringOrSetting(attribute.Connection); _options.Value.AddReceiver(resolvedEventHubName, connectionString); } var eventHostListener = _options.Value.GetEventProcessorHost(_config, resolvedEventHubName, resolvedConsumerGroup); Func <ListenerFactoryContext, bool, Task <IListener> > createListener = (factoryContext, singleDispatch) => { IListener listener = new EventHubListener(factoryContext.Executor, eventHostListener, singleDispatch, _options.Value, _logger); return(Task.FromResult(listener)); }; ITriggerBinding binding = BindingFactory.GetTriggerBinding(new EventHubTriggerBindingStrategy(), parameter, _converterManager, createListener); return(Task.FromResult <ITriggerBinding>(binding)); }
protected override void BeginProcessing() { base.BeginProcessing(); if (!(GetOfficeVersion.GetVersion("Excel")).IsInstalled) { ThrowTerminatingError(new ErrorRecord(new FileNotFoundException("Excel is not installed"), "1", ErrorCategory.InvalidOperation, null)); } //if (!ValidLicense()) // ThrowTerminatingError(new ErrorRecord(new Licensing.InvalidLicenseException("Product licence could not be verified"), "10", ErrorCategory.SecurityError, null)); msExcel = BindingFactory.CreateAutomationBinding("Excel.Application"); if (parDisplay) { WriteVerbose("Display have been set, making application visible"); msExcel.Property("Visible").Set(true); } currentCulture = Thread.CurrentThread.CurrentCulture; int langSettings = msExcel.Property("LanguageSettings").Get().Property("LanguageID").PropertyParam(2).Get <int>(); CultureInfo newCulture = new CultureInfo(langSettings); WriteVerbose(string.Format("Changing culture ({0}->{1})", currentCulture.DisplayName, newCulture.DisplayName)); Thread.CurrentThread.CurrentCulture = newCulture; switch (parFormat.ToLower()) { case "excel": format = 51; formatName = "xlsx"; break; case "excel97": format = 56; formatName = "xls"; break; case "pdf": format = 57; formatName = "pdf"; break; case "xps": format = 58; formatName = "xps"; break; } WriteVerbose(string.Format("Setting output format to {0} (.{1})", parFormat, formatName)); }
/// <inheritdoc /> public void Initialize(ExtensionConfigContext context) { if (context == null) { throw new ArgumentNullException("context"); } INameResolver nameResolver = context.Config.GetService <INameResolver>(); IConverterManager converterManager = context.Config.GetService <IConverterManager>(); BindingFactory factory = new BindingFactory(nameResolver, converterManager); IBindingProvider outputProvider = factory.BindToGenericAsyncCollector <DocumentDBAttribute>((attr, t) => BindForOutput(attr, t, context.Trace)); IBindingProvider clientProvider = factory.BindToExactType <DocumentDBAttribute, DocumentClient>(BindForClient); IBindingProvider itemProvider = factory.BindToGenericValueProvider <DocumentDBAttribute>((attr, t) => BindForItemAsync(attr, t, context.Trace)); IExtensionRegistry extensions = context.Config.GetService <IExtensionRegistry>(); extensions.RegisterBindingRules <DocumentDBAttribute>(ValidateConnection, nameResolver, outputProvider, clientProvider, itemProvider); }
protected virtual void OpenConnection() { String hostUrl = GetHostString(); Binding binding; if (BindingFactory != null) { binding = BindingFactory.CreateBinding(typeof(I), ServiceName, hostUrl); } else { binding = CreateDefaultBinding(); } if (ServiceName != null) { hostUrl += "/" + ServiceName; } ChannelFactory = ExtendChannelFactory(new ChannelFactory <I>(binding, new EndpointAddress(hostUrl))); }
private void Execute(IEvent <EventArgs> args) { using (tracer.StartActivity(Resources.EventAutomation_StartingExecution, this.Settings.Name)) { using (var context = BindingFactory.CreateContext()) { AddEventArgsToBindingContext(args, context); tracer.ShieldUI(() => { if (!conditionsResult.HasValue) { conditionsResult = this.Conditions.All(condition => Evaluate(condition, args)); } if (conditionsResult.Value) { using (var tx = this.Owner.BeginTransaction()) { if (this.ExecuteWizard(context)) { using (new MouseCursor(Cursors.Wait)) { if (this.ExecuteCommand(context)) { tx.Commit(); } } } } } else { tracer.Verbose(Resources.EventAutomation_ConditionsPreventExecution, this.Name); } }, Resources.EventAutomation_FailedToExecute, this.Name); } } }
private IElement CreateTeamDisplay(Team team) { var teamNameTextBlock = new TextBlock(this.lcd) { Foreground = new SolidColorBrush(Colors.LightGray), HorizontalAlignment = HorizontalAlignment.Center, Padding = new Thickness(25) }; var scoreTextBlock = new TextBlock(this.led) { Foreground = new SolidColorBrush(Colors.Green), HorizontalAlignment = HorizontalAlignment.Center }; teamNameTextBlock.Bind(TextBlock.TextProperty, BindingFactory.CreateOneWay <Team, string>(o => o.Name)); scoreTextBlock.Bind(TextBlock.TextProperty, BindingFactory.CreateOneWay <Team, int, string>(o => o.Score)); return(new StackPanel { Children = { teamNameTextBlock, scoreTextBlock }, DataContext = team }); }
/// <inheritdoc /> public void Initialize(ExtensionConfigContext context) { if (context == null) { throw new ArgumentNullException("context"); } _trace = context.Trace; INameResolver nameResolver = context.Config.GetService <INameResolver>(); IConverterManager converterManager = context.Config.GetService <IConverterManager>(); // Use this if there is no other connection string set. _defaultConnectionString = nameResolver.Resolve(AzureWebJobsDocumentDBConnectionStringName); BindingFactory factory = new BindingFactory(nameResolver, converterManager); IBindingProvider outputProvider = factory.BindToCollector <DocumentDBAttribute, OpenType>(typeof(DocumentDBCollectorBuilder <>), this); IBindingProvider clientProvider = factory.BindToInput <DocumentDBAttribute, DocumentClient>(new DocumentDBClientBuilder(this)); IBindingProvider jArrayProvider = factory.BindToInput <DocumentDBAttribute, JArray>(typeof(DocumentDBJArrayBuilder), this); IBindingProvider enumerableProvider = factory.BindToInput <DocumentDBAttribute, IEnumerable <OpenType> >(typeof(DocumentDBEnumerableBuilder <>), this); enumerableProvider = factory.AddValidator <DocumentDBAttribute>(ValidateInputBinding, enumerableProvider); IBindingProvider inputProvider = factory.BindToGenericValueProvider <DocumentDBAttribute>((attr, t) => BindForItemAsync(attr, t)); inputProvider = factory.AddValidator <DocumentDBAttribute>(ValidateInputBinding, inputProvider); IExtensionRegistry extensions = context.Config.GetService <IExtensionRegistry>(); extensions.RegisterBindingRules <DocumentDBAttribute>(ValidateConnection, nameResolver, outputProvider, clientProvider, jArrayProvider, enumerableProvider, inputProvider); context.Config.RegisterBindingExtensions(new CosmosDBTriggerAttributeBindingProvider(nameResolver, LeaseOptions)); }
public static void RunBindingFactorySample() { var binding = BindingFactory.Create <BasicHttpBinding>() as BasicHttpBinding; Console.WriteLine("MaxReceivedMessageSize = {0}", binding.MaxReceivedMessageSize); Console.WriteLine("MaxBufferSize = {0}", binding.MaxBufferSize); Console.WriteLine("MaxBufferPoolSize = {0}", binding.MaxBufferPoolSize); Console.WriteLine("OpenTimeout = {0}", binding.OpenTimeout); Console.WriteLine("SendTimeout = {0}", binding.SendTimeout); Console.WriteLine("----------------------------"); var binding2 = BindingFactory.Create(typeof(BasicHttpBinding)) as BasicHttpBinding; Console.WriteLine("MaxReceivedMessageSize = {0}", binding2.MaxReceivedMessageSize); Console.WriteLine("MaxBufferSize = {0}", binding2.MaxBufferSize); Console.WriteLine("MaxBufferPoolSize = {0}", binding2.MaxBufferPoolSize); Console.WriteLine("OpenTimeout = {0}", binding2.OpenTimeout); Console.WriteLine("SendTimeout = {0}", binding2.SendTimeout); Console.WriteLine("----------------------------"); var binding3 = BindingFactory.Create <BasicHttpBinding>("lucene") as BasicHttpBinding; Console.WriteLine("MaxReceivedMessageSize = {0}", binding3.MaxReceivedMessageSize); Console.WriteLine("MaxBufferSize = {0}", binding3.MaxBufferSize); Console.WriteLine("MaxBufferPoolSize = {0}", binding3.MaxBufferPoolSize); Console.WriteLine("OpenTimeout = {0}", binding3.OpenTimeout); Console.WriteLine("SendTimeout = {0}", binding3.SendTimeout); Console.WriteLine("----------------------------"); var binding4 = BindingFactory.Create <BasicHttpBinding>("promotion") as BasicHttpBinding; Console.WriteLine("MaxReceivedMessageSize = {0}", binding4.MaxReceivedMessageSize); Console.WriteLine("MaxBufferSize = {0}", binding4.MaxBufferSize); Console.WriteLine("MaxBufferPoolSize = {0}", binding4.MaxBufferPoolSize); Console.WriteLine("OpenTimeout = {0}", binding4.OpenTimeout); Console.WriteLine("SendTimeout = {0}", binding4.SendTimeout); Console.WriteLine("----------------------------"); }
public void Open() { var baseAddress = EndpointManager.GetServiceUri(this.endpoint.Port); var admin = new Uri(baseAddress, "Admin"); //var mex = new Uri(GetHttpMexUri(this.endpoint.Port + 1), "mex"); Log.Info($"Openning admin at: '{admin}'"); var binding = BindingFactory.GetTcpBinding(); this.serviceHost = new ServiceHost(typeof(HomeHubAdministrator), baseAddress); this.serviceHost.AddServiceEndpoint( typeof(IHomeHubAdministratorCom), binding, admin); this.serviceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "HomeHub-Admin-Server"); this.serviceHost.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "HomeHub-Admin-Client"); this.serviceHost.Open(); }
public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context) { ParameterInfo parameter = context.Parameter; FakeQueueTriggerAttribute attribute = parameter.GetCustomAttribute <FakeQueueTriggerAttribute>(inherit: false); if (attribute == null) { return(Task.FromResult <ITriggerBinding>(null)); } var hooks = new FakeQueueTriggerBindingStrategy(); Func <ListenerFactoryContext, bool, Task <IListener> > createListener = (factoryContext, singleDispatch) => { IListener listener = new FakeQueueListener(factoryContext.Executor, _client, singleDispatch); return(Task.FromResult(listener)); }; ITriggerBinding binding = BindingFactory.GetTriggerBinding <FakeQueueData, FakeQueueDataBatch>( hooks, parameter, _converterManager, createListener); return(Task.FromResult <ITriggerBinding>(binding)); }
public void ConvertToAmibroker(PSEDocument pseDocument, AmiOutputSettings amiOutputSettings) { if (!System.IO.Directory.Exists(amiOutputSettings.DatabaseDirectory)) { throw new Exception(amiOutputSettings.DatabaseDirectory + " does not exist"); } IOperationInvoker amiInvoker = BindingFactory.CreateAutomationBinding("Broker.Application"); amiInvoker.Method("LoadDatabase").AddParameter(amiOutputSettings.DatabaseDirectory).Invoke(); foreach (SectorItem sector in pseDocument.Sectors) { SetAmibrokerData(amiInvoker, pseDocument, sector, amiOutputSettings); foreach (SubSectorItem subSector in sector.SubSectors) { foreach (StockItem stockItem in subSector.Stocks) { SetAmibrokerData(amiInvoker, pseDocument, stockItem, amiOutputSettings); } } } amiInvoker.Method("SaveDatabase").Invoke(); amiInvoker.Method("RefreshAll").Invoke(); object x = amiInvoker.Property("Visible").Get <object>(); if (x.ToString() == "0") { x = 1; amiInvoker.Property("Visible").Set(x); } if (OnConvertComplete != null) { OnConvertComplete(pseDocument, new ConvertEventArgs(amiOutputSettings)); } }
// Helper to allocate a binding provider for [Queue]. // private instance method since it's refering to lambdas that close over the instance fields. private IBindingProvider New( INameResolver nameResolver, IConverterManager converterManager) { // IStorageQueueMessage is the core testing interface converterManager.AddConverter <byte[], IStorageQueueMessage, QueueAttribute>(ConvertByteArrayToCloudQueueMessage); converterManager.AddConverter <IStorageQueueMessage, byte[]>(ConvertCloudQueueMessageToByteArray); converterManager.AddConverter <string, IStorageQueueMessage, QueueAttribute>(ConvertStringToCloudQueueMessage); converterManager.AddConverter <IStorageQueueMessage, string>(ConvertCloudQueueMessageToString); converterManager.AddConverter <CloudQueueMessage, IStorageQueueMessage>(ConvertToStorageQueueMessage); var bindingFactory = new BindingFactory(nameResolver, converterManager); var bindAsyncCollector = bindingFactory.BindToAsyncCollector <QueueAttribute, IStorageQueueMessage>(BuildFromQueueAttribute, ToWriteParameterDescriptorForCollector, CollectAttributeInfo); var bindClient = bindingFactory.BindToExactAsyncType <QueueAttribute, IStorageQueue>(BuildClientFromQueueAttributeAsync, ToReadWriteParameterDescriptorForCollector, CollectAttributeInfo); var bindSdkClient = bindingFactory.BindToExactAsyncType <QueueAttribute, CloudQueue>(BuildRealClientFromQueueAttributeAsync, ToReadWriteParameterDescriptorForCollector, CollectAttributeInfo); var bindingProvider = new GenericCompositeBindingProvider <QueueAttribute>( ValidateQueueAttribute, nameResolver, bindClient, bindSdkClient, bindAsyncCollector); return(bindingProvider); }
private IElement CreateListBoxItem(GameViewModel content) { var textBlock = new TextBlock(FontManager[Fonts.Normal]) { Text = content.GameName, Foreground = new SolidColorBrush(Colors.White), Margin = new Thickness(0, 10, 0, 10), }; var border = new Border() { Child = textBlock }; var listBoxItem = new ListBoxItem() { Content = border }; textBlock.Bind(TextBlock.ForegroundProperty, listBoxItem.GetObservable <bool, ListBoxItem>(ListBoxItem.IsSelectedProperty) .Select( isSelected => (Brush) (isSelected ? new SolidColorBrush(Colors.Black) : new SolidColorBrush(Colors.White)))); border.Bind(Border.BackgroundProperty, listBoxItem.GetObservable <bool, ListBoxItem>(ListBoxItem.IsSelectedProperty) .Select( isSelected => (Brush) (isSelected ? new SolidColorBrush(Colors.Gray) : new SolidColorBrush(Colors.Black)))); content.PropertyChanged += delegate { listBoxItem.IsSelected = content.IsSelected; }; listBoxItem.Bind(ListBoxItem.IsSelectedProperty, BindingFactory.CreateTwoWay(content, c => c.IsSelected)); return(listBoxItem); }
public Task <IBinding> TryCreateAsync(BindingProviderContext context) { ParameterInfo parameter = context.Parameter; FakeQueueAttribute attribute = parameter.GetCustomAttribute <FakeQueueAttribute>(inherit: false); if (attribute == null) { return(Task.FromResult <IBinding>(null)); } string resolvedName = "fakequeue"; Func <string, FakeQueueClient> invokeStringBinder = (invokeString) => _client; IBinding binding = BindingFactory.BindCollector <FakeQueueData, FakeQueueClient>( parameter, _converterManager, (client, valueBindingContext) => client, resolvedName, invokeStringBinder ); return(Task.FromResult(binding)); }
/// <inheritdoc /> public void Initialize(ExtensionConfigContext context) { if (context == null) { throw new ArgumentNullException("context"); } INameResolver nameResolver = context.Config.NameResolver; IExtensionRegistry extensions = context.Config.GetService <IExtensionRegistry>(); _defaultConnectionString = nameResolver.Resolve(NotificationHubConnectionStringName); _defaultHubName = nameResolver.Resolve(NotificationHubSettingName); var converterManager = context.Config.GetService <IConverterManager>(); converterManager.AddNotificationHubConverters(); var bindingFactory = new BindingFactory(nameResolver, converterManager); IBindingProvider clientProvider = bindingFactory.BindToInput <NotificationHubAttribute, NotificationHubClient>(new NotificationHubClientBuilder(this)); var ruleOutput = bindingFactory.BindToCollector <NotificationHubAttribute, Notification>((attribute) => BuildFromAttribute(attribute, context.Trace)); extensions.RegisterBindingRules <NotificationHubAttribute>(ruleOutput, clientProvider); }
public static IBindingProvider Build(INameResolver nameResolver, IConverterManager converterManager, IStorageAccountProvider accountProvider, IExtensionRegistry extensions) { var original = new TableAttributeBindingProvider(nameResolver, accountProvider, extensions); converterManager.AddConverter <JObject, ITableEntity, TableAttribute>(original.JObjectToTableEntityConverterFunc); var bindingFactory = new BindingFactory(nameResolver, converterManager); var bindAsyncCollector = bindingFactory.BindToAsyncCollector <TableAttribute, ITableEntity>(original.BuildFromTableAttribute, null, original.CollectAttributeInfo); var bindToJobject = bindingFactory.BindToExactAsyncType <TableAttribute, JObject>(original.BuildJObject, null, original.CollectAttributeInfo); var bindToJArray = bindingFactory.BindToExactAsyncType <TableAttribute, JArray>(original.BuildJArray, null, original.CollectAttributeInfo); // Filter to just support JObject, and use legacy bindings for everything else. // Once we have ITableEntity converters for pocos, we can remove the filter. // https://github.com/Azure/azure-webjobs-sdk/issues/887 bindAsyncCollector = bindingFactory.AddFilter <TableAttribute>( (attr, type) => (type == typeof(IAsyncCollector <JObject>) || type == typeof(ICollector <JObject>)), bindAsyncCollector); var bindingProvider = new GenericCompositeBindingProvider <TableAttribute>( new IBindingProvider[] { bindToJArray, bindToJobject, bindAsyncCollector, original }); return(bindingProvider); }
void IExtensionConfigProvider.Initialize(ExtensionConfigContext context) { if (context == null) { throw new ArgumentNullException("context"); } // Deferred list foreach (var action in _deferredWork) { action(context.Config); } _deferredWork.Clear(); // get the services we need to construct our binding providers INameResolver nameResolver = context.Config.NameResolver; IExtensionRegistry extensions = context.Config.GetService <IExtensionRegistry>(); IConverterManager cm = context.Config.GetService <IConverterManager>(); cm.AddConverter <string, EventData>(ConvertString2EventData); cm.AddConverter <EventData, string>(ConvertEventData2String); cm.AddConverter <byte[], EventData>(ConvertBytes2EventData); // direct, handles non-string representations var bf = new BindingFactory(nameResolver, cm); // register our trigger binding provider var triggerBindingProvider = new EventHubTriggerAttributeBindingProvider(nameResolver, cm, this); extensions.RegisterExtension <ITriggerBindingProvider>(triggerBindingProvider); // register our binding provider var ruleOutput = bf.BindToAsyncCollector <EventHubAttribute, EventData>(BuildFromAttribute); extensions.RegisterBindingRules <EventHubAttribute>(ruleOutput); }
protected override void BeginProcessing() { base.BeginProcessing(); if (!(GetOfficeVersion.GetVersion("Excel")).IsInstalled) { ThrowTerminatingError(new ErrorRecord(new FileNotFoundException("Excel is not installed use Out-OExcel instead."), "1", ErrorCategory.InvalidOperation, null)); } if (parPath.StartsWith(@".\")) { parPath = System.IO.Path.Combine(this.CurrentProviderLocation("FileSystem").ProviderPath, parPath.Substring(2)); } parPath = System.IO.Path.GetFullPath(parPath); WriteVerbose(string.Format("Checking for existance of file {0}", parPath)); WriteProgress(new ProgressRecord(10, "Out-Excel", "Initializing..")); if (File.Exists(parPath)) { if (!parOverwrite) { WriteVerbose("File exists and -Overwrite have not been specified"); ThrowTerminatingError(new ErrorRecord(new System.IO.IOException("The file already exists and -Overwrite have not been specified"), "100", ErrorCategory.ResourceExists, parPath.ToString())); } else { WriteVerbose("File exists and -Override have been specified, will delete file"); File.Delete(Path); } } WriteVerbose("Starting Microsoft Excel"); msExcel = BindingFactory.CreateAutomationBinding("Excel.Application"); currentCulture = Thread.CurrentThread.CurrentCulture; int langSettings = msExcel.Property("LanguageSettings").Get().Property("LanguageID").PropertyParam(2).Get <int>(); CultureInfo newCulture = new CultureInfo(langSettings); WriteVerbose(string.Format("Changing culture ({0}->{1})", currentCulture.DisplayName, newCulture.DisplayName)); Thread.CurrentThread.CurrentCulture = newCulture; if (parDisplay) { WriteVerbose("Display have been set, making application visible"); msExcel.Property("Visible").Set(true); } WriteProgress(new ProgressRecord(10, "Out-Excel", "Creating document..")); try { WriteVerbose("Creating new document"); workBook = msExcel.Property("Workbooks").Get().Method("Add").Invoke(); } catch { workBook.Method("Close").AddParameter(0).Invoke(); msExcel.Method("Quit").AddParameter(0).Invoke(); WriteVerbose("Document creation failed "); ThrowTerminatingError(new ErrorRecord(new System.IO.IOException("Document creation failed"), "101", ErrorCategory.ResourceUnavailable, msExcel)); } WriteVerbose("Activating document"); workBook.Method("Activate").Invoke(); }
public static IBindingProvider BindToAsyncCollector <TAttribute, TMessage>(this BindingFactory factory, Func <TAttribute, TMessage, Task> processMessage) where TAttribute : Attribute { return(factory.BindToAsyncCollector <TAttribute, TMessage>(attrib => new AsyncCollector <TAttribute, TMessage>(attrib, processMessage))); }
protected override void LoadContent() { var spriteBatchAdapter = new SpriteBatchAdapter(new SpriteBatch(this.GraphicsDevice)); var spriteFontAdapter = new SpriteFontAdapter(this.Game.Content.Load <SpriteFont>("SpriteFont")); var renderer = new Renderer(spriteBatchAdapter, new PrimitivesService(this.GraphicsDevice)); this.rootElement = new RootElement(this.GraphicsDevice.Viewport.ToRect(), renderer, new InputManager()); // Setup Layout var cardImage = new Image { Stretch = Stretch.None }; var cardToggleButton = new ToggleButton { Content = cardImage, Margin = new Thickness(10) }; var resetButton = new Button { Content = new Border { Background = new SolidColorBrush(Colors.LightGray), Child = new TextBlock(spriteFontAdapter) { Text = "Reset", Margin = new Thickness(10) } }, Margin = new Thickness(10), HorizontalAlignment = HorizontalAlignment.Center }; var stackPanel = new StackPanel { Children = { cardToggleButton, resetButton } }; this.rootElement.Content = stackPanel; // Setup Data Binding var faceDownImage = new TextureImage(new Texture2DAdapter(this.Game.Content.Load <Texture2D>("FaceDown"))); var faceUpImage = new TextureImage(new Texture2DAdapter(this.Game.Content.Load <Texture2D>("FaceUp"))); var card = new Card(faceDownImage, faceUpImage); cardImage.Bind( Image.SourceProperty, BindingFactory.CreateOneWay <Card, ImageSource>(card, d => d.CardImage)); cardToggleButton.Bind( ToggleButton.IsCheckedProperty, BindingFactory.CreateTwoWay(card, d => d.IsCardFaceUp)); resetButton.Click += (sender, args) => card.Reset(); }
void IExtensionConfigProvider.Initialize(ExtensionConfigContext context) { if (context == null) { throw new ArgumentNullException("context"); } // Deferred list foreach (var action in _deferredWork) { action(context.Config); } _deferredWork.Clear(); // get the services we need to construct our binding providers INameResolver nameResolver = context.Config.NameResolver; IExtensionRegistry extensions = context.Config.GetService<IExtensionRegistry>(); IConverterManager cm = context.Config.GetService<IConverterManager>(); cm.AddConverter<string, EventData>(ConvertString2EventData); cm.AddConverter<EventData, string>(ConvertEventData2String); cm.AddConverter<byte[], EventData>(ConvertBytes2EventData); // direct, handles non-string representations var bf = new BindingFactory(nameResolver, cm); // register our trigger binding provider var triggerBindingProvider = new EventHubTriggerAttributeBindingProvider(nameResolver, cm, this); extensions.RegisterExtension<ITriggerBindingProvider>(triggerBindingProvider); // register our binding provider var ruleOutput = bf.BindToAsyncCollector<EventHubAttribute, EventData>(BuildFromAttribute); extensions.RegisterBindingRules<EventHubAttribute>(ruleOutput); }
protected override void LoadContent() { this.spriteBatchAdapter = new SpriteBatchAdapter(new SpriteBatch(this.GraphicsDevice)); var primitivesService = new PrimitivesService(this.GraphicsDevice); var renderer = new Renderer(this.spriteBatchAdapter, primitivesService); var spriteFontAdapter = new SpriteFontAdapter(this.Game.Content.Load <SpriteFont>("Segoe18")); var largeFont = new SpriteFontAdapter(this.Game.Content.Load <SpriteFont>("Segoe30")); var addButtonImageTexture = new TextureImage(new Texture2DAdapter(this.Game.Content.Load <Texture2D>("AddButton"))); var trashButtonImageTexture = new TextureImage(new Texture2DAdapter(this.Game.Content.Load <Texture2D>("TrashButton"))); this.rootElement = new RootElement(this.GraphicsDevice.Viewport.ToRect(), renderer, new InputManager()); var buttonClickResults = new ObservableCollection <string>(); var header1 = new TextBlock(spriteFontAdapter) { Text = "MY APPLICATION", Foreground = new SolidColorBrush(Colors.White), Margin = new Thickness(10) }; var header2 = new TextBlock(largeFont) { Text = "XNA Application Bar", Foreground = new SolidColorBrush(Colors.White), Margin = new Thickness(10) }; var itemsControl = new ItemsControl { ItemsSource = buttonClickResults, ItemTemplate = _ => { var textBlock = new TextBlock(spriteFontAdapter) { Foreground = new SolidColorBrush(Colors.White) }; textBlock.Bind( TextBlock.TextProperty, BindingFactory.CreateOneWay <string>()); return(textBlock); } }; var scrollViewer = new ScrollViewer { Content = itemsControl }; var applicationBar = new ApplicationBar { Buttons = { new ApplicationBarIconButton("Add", addButtonImageTexture), new ApplicationBarIconButton("Delete", trashButtonImageTexture) } }; var grid = new Grid { Background = new SolidColorBrush(Colors.Black), RowDefinitions = { new RowDefinition { Height = GridLength.Auto }, new RowDefinition { Height = GridLength.Auto }, new RowDefinition(), new RowDefinition { Height = new GridLength(70) } }, Children = { header1, header2, scrollViewer, applicationBar } }; applicationBar.Clicks.Subscribe( Observer.Create <ApplicationBarIconButton>(s => buttonClickResults.Add(s.Text))); Grid.SetRow(header1, 0); Grid.SetRow(header2, 1); Grid.SetRow(scrollViewer, 2); Grid.SetRow(applicationBar, 3); this.rootElement.Content = grid; }
// Binding rule only allowed on attributes that don't specify the RowKey. private static IBindingProvider AllowMultipleRows(BindingFactory bf, IBindingProvider innerProvider) { return(bf.AddFilter <TableAttribute>((attr, type) => attr.RowKey == null, innerProvider)); }
/// <summary> /// Creates the endpoints and creates the hosts. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="bindingFactory">The binding factory.</param> /// <param name="serverDescription">The server description.</param> /// <param name="endpoints">The endpoints.</param> /// <returns> /// Returns IList of a host for a UA service which type is <seealso cref="ServiceHost"/>. /// </returns> protected override IList<IBackgroundTask> InitializeServiceHosts( ApplicationConfiguration configuration, BindingFactory bindingFactory, out ApplicationDescription serverDescription, out EndpointDescriptionCollection endpoints) { serverDescription = null; endpoints = null; Dictionary<string, IBackgroundTask> hosts = new Dictionary<string, IBackgroundTask>(); // ensure at least one security policy exists. if (configuration.ServerConfiguration.SecurityPolicies.Count == 0) { configuration.ServerConfiguration.SecurityPolicies.Add(new ServerSecurityPolicy()); } // ensure at least one user token policy exists. if (configuration.ServerConfiguration.UserTokenPolicies.Count == 0) { UserTokenPolicy userTokenPolicy = new UserTokenPolicy(); userTokenPolicy.TokenType = UserTokenType.Anonymous; userTokenPolicy.PolicyId = userTokenPolicy.TokenType.ToString(); configuration.ServerConfiguration.UserTokenPolicies.Add(userTokenPolicy); } // set server description. serverDescription = new ApplicationDescription(); serverDescription.ApplicationUri = configuration.ApplicationUri; serverDescription.ApplicationName = configuration.ApplicationName; serverDescription.ApplicationType = configuration.ApplicationType; serverDescription.ProductUri = configuration.ProductUri; serverDescription.DiscoveryUrls = GetDiscoveryUrls(); endpoints = new EndpointDescriptionCollection(); IList<EndpointDescription> endpointsForHost = null; // create hosts for protocols that require one endpoints per security policy foreach (ServerSecurityPolicy securityPolicy in configuration.ServerConfiguration.SecurityPolicies) { endpointsForHost = CreateSinglePolicyServiceHost( hosts, configuration, bindingFactory, configuration.ServerConfiguration.BaseAddresses, serverDescription, securityPolicy.SecurityMode, securityPolicy.SecurityPolicyUri, String.Empty); for (int ii = 0; ii < endpointsForHost.Count; ii++) { endpointsForHost[ii].SecurityLevel = securityPolicy.SecurityLevel; } endpoints.AddRange(endpointsForHost); } // create UA TCP host. endpointsForHost = CreateUaTcpServiceHost( hosts, configuration, bindingFactory, configuration.ServerConfiguration.BaseAddresses, serverDescription, configuration.ServerConfiguration.SecurityPolicies); endpoints.InsertRange(0, endpointsForHost); // create HTTPS host. endpointsForHost = CreateHttpsServiceHost( hosts, configuration, bindingFactory, configuration.ServerConfiguration.BaseAddresses, serverDescription, configuration.ServerConfiguration.SecurityPolicies); endpoints.AddRange(endpointsForHost); return new List<IBackgroundTask>(hosts.Values); }
/// <summary> /// Creates a session. /// </summary> private Session CreateSession( ApplicationConfiguration configuration, BindingFactory bindingFactory, ConfiguredEndpoint endpoint, IUserIdentity identity) { Report("Creating new Session with URL = {0}", endpoint.EndpointUrl); // Initialize the channel which will be created with the server. ITransportChannel channel = SessionChannel.Create( configuration, endpoint.Description, endpoint.Configuration, configuration.SecurityConfiguration.ApplicationCertificate.Find(true), configuration.CreateMessageContext()); // Wrap the channel with the session object. Session session = new Session(channel, configuration, endpoint, null); session.ReturnDiagnostics = DiagnosticsMasks.All; // register keep alive callback. session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); // create the user identity. if (identity == null) { if (endpoint.Description.UserIdentityTokens.Count > 0) { identity = CreateUserIdentity(endpoint.Description.UserIdentityTokens[0]); } } // Create the session. This actually connects to the server. session.Open(Guid.NewGuid().ToString(), identity); Report("Successfully created new Session."); // return the session. return session; }
public void Setup() { Subject = new BindingFactory(); }