public override void SetUp() { base.SetUp(); var serviceProvider = new ServiceProvider(); myWebScrapSC = serviceProvider.Browser(); }
/// <summary> /// Initializes a new instance of the ScriptSynthesizer class. /// </summary> /// <param name="serviceProvider">Service provider.</param> /// <param name="commonConfig">Common config of script synthesizer.</param> /// <param name="scriptFeatureImportConfig">Config of script feature import.</param> /// <param name="customizedFeaturePluginManager">Plugin manager of customized feature extraction.</param> public ScriptSynthesizer(ServiceProvider serviceProvider, ScriptSynthesizerCommonConfig commonConfig, ScriptFeatureImportConfig scriptFeatureImportConfig, CustomizedFeaturePluginManager customizedFeaturePluginManager) { if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } // commonConfig can be null. // scriptFeatureImportConfig can be null. // customizedFeaturePluginManager can be null. _serviceProvider = serviceProvider; _scriptFeatureImportConfig = scriptFeatureImportConfig; if (commonConfig != null) { _logger = new TextLogger(commonConfig.TraceLogFile); _logger.Reset(); } if (_scriptFeatureImportConfig != null) { _scriptFeatureImport = new ScriptFeatureImport(commonConfig, _scriptFeatureImportConfig, _serviceProvider, _logger); } if (customizedFeaturePluginManager != null) { _customizedFeatureExtraction = new CustomizedFeatureExtraction(_serviceProvider, customizedFeaturePluginManager); } }
/// <summary> /// Initializes a new instance of the MixedVoiceSynthesizer class. /// </summary> /// <param name="donator">Service provider the donator.</param> /// <param name="receiver">Service provider the receiver.</param> /// <param name="config">Config object.</param> public MixedVoiceSynthesizer(ServiceProvider donator, ServiceProvider receiver, MixedVoiceSynthesizerConfig config) { if (donator == null) { throw new ArgumentNullException("donator"); } if (receiver == null) { throw new ArgumentNullException("receiver"); } if (config == null) { throw new ArgumentNullException("config"); } _donator = donator; _receiver = receiver; _config = config; _donator.Engine.AcousticProsodyTagger.Processed += new EventHandler<TtsModuleEventArgs>(OnDonatorAcousticProcessed); _receiver.Engine.AcousticProsodyTagger.Processed += new EventHandler<TtsModuleEventArgs>(OnReceiverAcousticProcessed); if (!string.IsNullOrEmpty(config.LogFile)) { _logger = new TextLogger(config.LogFile); _logger.Reset(); } }
/*******************************************************************************/ /* */ /* Конструктор */ public DMCC_service() { mPhones = new DMCC_phone[mPHONES_MAX]; mService =null ; mConnected=false ; }
public ServiceProvider[] ServiceProviders(string version) { ServiceProvider[] listServiceProviders = new ServiceProvider[1]; ServiceProvider nikotelServiceProvider = new ServiceProvider(); nikotelServiceProvider.Name = "nikotel - the voip network"; nikotelServiceProvider.Description = "Visit www.nikotel.com"; nikotelServiceProvider.IMServerAddress = "im.nikotel.com"; nikotelServiceProvider.IMServerPort = 5222; nikotelServiceProvider.SIPProxyRealm = "nikotel.com"; nikotelServiceProvider.SIPProxyAddress = "voip.nikotel.com"; nikotelServiceProvider.SIPProxyPort = 5060; nikotelServiceProvider.VideoProxyAddress = "video.nikotel.com"; nikotelServiceProvider.VideoProxyPort = 800; nikotelServiceProvider.SignupLink = "https://www.nikotel.com/nikotel-signup/nikotalk/register"; listServiceProviders[0] = nikotelServiceProvider; return listServiceProviders; }
public IServiceCallSite CreateCallSite(ServiceProvider provider, ISet<Type> callSiteChain) { ConstructorInfo[] constructors = _descriptor.ImplementationType.GetTypeInfo() .DeclaredConstructors .Where(IsInjectable) .ToArray(); // TODO: actual service-fulfillment constructor selection if (constructors.Length == 1) { ParameterInfo[] parameters = constructors[0].GetParameters(); IServiceCallSite[] parameterCallSites = new IServiceCallSite[parameters.Length]; for (var index = 0; index != parameters.Length; ++index) { parameterCallSites[index] = provider.GetServiceCallSite(parameters[index].ParameterType, callSiteChain); if (parameterCallSites[index] == null && parameters[index].HasDefaultValue) { parameterCallSites[index] = new ConstantCallSite(parameters[index].DefaultValue); } if (parameterCallSites[index] == null) { throw new InvalidOperationException(Resources.FormatCannotResolveService( parameters[index].ParameterType, _descriptor.ImplementationType)); } } return new ConstructorCallSite(constructors[0], parameterCallSites); } return new CreateInstanceCallSite(_descriptor); }
protected void allowAccessButton_Click(object sender, EventArgs e) { if (this.AuthorizationSecret != OAuthAuthorizationSecToken.Value) { throw new ArgumentException(); // probably someone trying to hack in. } this.AuthorizationSecret = null; // clear one time use secret var pending = Global.PendingOAuthAuthorization; Global.AuthorizePendingRequestToken(); multiView.ActiveViewIndex = 1; ServiceProvider sp = new ServiceProvider(Constants.SelfDescription, Global.TokenManager); var response = sp.PrepareAuthorizationResponse(pending); if (response != null) { sp.Channel.Send(response); } else { if (pending.IsUnsafeRequest) { verifierMultiView.ActiveViewIndex = 1; } else { string verifier = ServiceProvider.CreateVerificationCode(VerificationCodeFormat.AlphaNumericNoLookAlikes, 10); verificationCodeLabel.Text = verifier; ITokenContainingMessage requestTokenMessage = pending; var requestToken = Global.TokenManager.GetRequestToken(requestTokenMessage.Token); requestToken.VerificationCode = verifier; Global.TokenManager.UpdateToken(requestToken); } } }
/// <summary> /// Initializes a new instance of the CustomizedFeatureExtraction class. /// </summary> /// <param name="serviceProvider">Service provider.</param> /// <param name="customizedFeaturePluginManager">Plugin manager.</param> public CustomizedFeatureExtraction(ServiceProvider serviceProvider, CustomizedFeaturePluginManager customizedFeaturePluginManager) { if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } if (customizedFeaturePluginManager == null) { throw new ArgumentNullException("customizedFeaturePluginManager"); } _customizedFeaturePluginManager = customizedFeaturePluginManager; List<PluginInfo> pluginInfos = _customizedFeaturePluginManager.GetPlugins( CustomizedFeaturePluginManager.AttachBeforeExtraction); if (pluginInfos != null) { _utteranceExtenders = UtteranceExtenderFinder.LoadUtteranceExtenders(pluginInfos); } _serviceProvider = serviceProvider; _serviceProvider.Engine.AcousticProsodyTagger.Processing += new EventHandler<TtsModuleEventArgs>(OnAcousticProcessing); }
public void TestServiceCreatorCallback() { ServiceProvider provider = new ServiceProvider(); provider.Add<ILog>(new ServiceCreatorCallback<ILog>(ServiceRequested)); ILog log = provider.Get<ILog>(); Assert.IsNotNull(log); }
protected internal SignInPage(PhoneApplicationPage page) : base(page) { SignIn = new SimpleActionCommand(_ => SelectServiceProvider.Execute(ClientData.VidyanoServiceProvider)); RetryConnect = new SimpleActionCommand(async _ => { if (State == SignInPageState.NoInternet) await Connect(); }); SelectServiceProvider = new SimpleActionCommand(provider => { selectedProvider = (ServiceProvider)provider; promptServiceProviderWaiter.Set(); }); Page.BackKeyPress += (_, e) => { promptServiceProviderWaiter.Set(); if (oauthBrowserWaiter != null) oauthBrowserWaiter.Set(); if (ClientData != null && !String.IsNullOrEmpty(ClientData.DefaultUserName)) e.Cancel = true; }; }
public void TestAddDuplicateService2() { ServiceProvider provider = new ServiceProvider(); provider.Add<ILog>(new ServiceCreatorCallback<ILog>(ServiceRequested)); ILog log1 = new NoLog(); provider.Add<ILog>(log1); }
public string GetAllResultsAsJSON(ServiceProvider serviceProvider, string apiKey, string apiPwd) { if (serviceProvider == ServiceProvider.CoulombChargePoint) { //Coulomb notes: logdata.endTime field in Reference.cs autocreated as DateTime but needs to be serialized as string as value is often 24:00, change property type to string OCM.Import.NetworkServices.ThirdPartyServices.Coulomb.coulombservicesClient svc = new Import.NetworkServices.ThirdPartyServices.Coulomb.coulombservicesClient(); svc.ClientCredentials.UserName.UserName = apiKey; svc.ClientCredentials.UserName.Password = apiPwd; string output = ""; OCM.Import.NetworkServices.ThirdPartyServices.Coulomb.logdata[] stationData = { new OCM.Import.NetworkServices.ThirdPartyServices.Coulomb.logdata() { } }; string result = svc.getAllUSStations(new OCM.Import.NetworkServices.ThirdPartyServices.Coulomb.stationSearchRequest() { // Geo = new Import.NetworkServices.ThirdPartyServices.Coulomb.stationSearchRequestGeo { lat = "38.5846", @long = "-121.4961" }, Country = "USA", Proximity = 50000, postalCode = "95816" }, out output, out stationData); JavaScriptSerializer js = new JavaScriptSerializer(); js.MaxJsonLength = 10000000; string outputJS = js.Serialize(stationData); System.Diagnostics.Debug.WriteLine("<json>"+outputJS+"</json>"); return outputJS; } return null; }
public PropertiesEditorLauncher(ServiceProvider serviceProvider) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); this.serviceProvider = serviceProvider; }
public void TestAddDuplicateService1() { ServiceProvider provider = new ServiceProvider(); ILog log1 = new NoLog(); ILog log2 = new NoLog(); provider.Add<ILog>(log1); provider.Add<ILog>(log2); }
static Engine() { Status = EngineStatus.Stopped; // The service provider is always there so that // it can be mocked during unit tests. ServiceProvider = new ServiceProvider(); }
public void doWork() { ServiceProvider service; if((provider == null) || !provider.TryGetTarget(out service)){ service = new ServiceProvider(); provider = new WeakReference<ServiceProvider>(service); // !!!!! podem evitar instanciar uma nova WeakReference fazendo o SetTarget(T) } service.doWork(); }
public IServiceCallSite CreateCallSite(ServiceProvider provider, ISet<Type> callSiteChain) { var list = new List<IServiceCallSite>(); for (var service = _serviceEntry.First; service != null; service = service.Next) { list.Add(provider.GetResolveCallSite(service, callSiteChain)); } return new CallSite(_itemType, list.ToArray()); }
public object Invoke(ServiceProvider provider) { var array = Array.CreateInstance(_itemType, _serviceCallSites.Length); for (var index = 0; index < _serviceCallSites.Length; index++) { array.SetValue(_serviceCallSites[index].Invoke(provider), index); } return array; }
public void Setup() { serviceProvider = new ServiceProvider(); if (serviceProvider.ServiceExist(TEMP_SERVICE_NAME)) { serviceProvider.UnInstall(TEMP_SERVICE_NAME); } }
public AdalClient( AppConfig appConfig, CredentialType credentialType, IServiceInfoProvider serviceProvider = null) : base(appConfig, credentialType, serviceProvider) { appConfig.ServiceResource = Constants.Authentication.GraphServiceUrl; serviceProvider = new ServiceProvider(); this.ServiceInformation = _serviceInfoProvider.CreateServiceInfo(appConfig, credentialType).Result; }
private static IDocumentBrowser CreateEnhancedDocumentBrowser( ServiceProvider serviceProvider ) { var navigator = new CachingNavigator( new Navigator(), new DocumentCache() ); var browser = new DocumentBrowser( navigator ); return browser; }
public override void TearDown() { Interpreter.Context.TomScripting.Dispose(); myServiceProvider.Reset(); myInterpreter = null; myServiceProvider = null; myDataAccess = null; base.TearDown(); }
public object Create(ServiceProvider provider) { if (_descriptor.ImplementationInstance != null) { return _descriptor.ImplementationInstance; } else { return ActivatorUtilities.CreateInstance(provider, _descriptor.ImplementationType); } }
/// <include file='doc\CodeWindowManager.uex' path='docs/doc[@for="DocumentProperties.DocumentProperties"]/*' /> protected DocumentProperties(CodeWindowManager mgr) { this.mgr = mgr; this.visible = true; if (mgr != null) { IOleServiceProvider sp = mgr.CodeWindow as IOleServiceProvider; if (sp != null) { ServiceProvider site = new ServiceProvider(sp); this.tracker = site.GetService(typeof(SVsTrackSelectionEx)) as IVsTrackSelectionEx; } } }
private static IDocumentBrowser CreateLegacyDocumentBrowser( ServiceProvider serviceProvider ) { var browser = new LegacyDocumentBrowser(); browser.Init( serviceProvider ); browser.DownloadController.Options = BrowserOptions.NoActiveXDownload | BrowserOptions.NoBehaviors | BrowserOptions.NoJava | BrowserOptions.NoScripts | BrowserOptions.Utf8; return browser; }
public object Create(ServiceProvider provider) { var list = new List<object>(); for (var service = _serviceEntry.First; service != null; service = service.Next) { list.Add(provider.ResolveService(service)); } var array = Array.CreateInstance(_itemType, list.Count); Array.Copy(list.ToArray(), array, list.Count); return array; }
protected SelectionListener(ServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; this.monSel = serviceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; Debug.Assert(this.monSel != null, "Could not get the IVsMonitorSelection object from the services exposed by this project"); if (this.monSel == null) { throw new InvalidOperationException(); } }
protected ProjectDocumentsListener(ServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; this.projectDocTracker = serviceProvider.GetService(typeof(SVsTrackProjectDocuments)) as IVsTrackProjectDocuments2; Debug.Assert(this.projectDocTracker != null, "Could not get the IVsTrackProjectDocuments2 object from the services exposed by this project"); if (this.projectDocTracker == null) { throw new InvalidOperationException(); } }
public ServiceChannel[] GetChannels() { List<ServiceChannel> list = new List<ServiceChannel>(); foreach (var type in Builder.EntityTypes) { Type instance = typeof(CacheEntityQueryable<>).MakeGenericType(new Type[] { type }); Type contract = typeof(ICacheEntityQueryable<>).MakeGenericType(new Type[] { type }); ServiceProvider provider = new ServiceProvider(instance, contract); ServiceChannel channel = new ServiceChannel("Comboost_EntityChannel_" + type.Name, provider, DataFormatter); list.Add(channel); } return list.ToArray(); }
public void CreateCallSite_CreatesInstanceCallSite_IfTypeHasDefaultOrPublicParameterlessConstructor(Type type) { // Arrange var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient); var service = new Service(descriptor); var serviceProvider = new ServiceProvider(new[] { descriptor }); // Act var callSite = service.CreateCallSite(serviceProvider, new HashSet<Type>()); // Assert Assert.IsType<CreateInstanceCallSite>(callSite); }
public virtual int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) { _serviceProvider = new ServiceProvider(psp); return(VSConstants.S_OK); }
public static int Main(string[] args) { RegisterBlipTypes(); if (ServiceProvider == null) { ServiceProvider = GetServiceProvider(); } return(CLI.HandleErrors(() => { var app = CLI.Parser(); app.ExecutableName(typeof(Program).GetTypeInfo().Assembly.GetName().Name); app.FromAssembly(typeof(Program).GetTypeInfo().Assembly); app.HelpText("BLiP Command Line Interface"); _verbose = app.Switch("v").Alias("verbose").HelpText("Enable verbose output."); _force = app.Switch("force").HelpText("Enable force operation."); var pingHandler = new PingHandler(); var pingCommand = app.Command("ping"); pingHandler.Node = pingCommand.Parameter <string>("n").Alias("node").HelpText("Node to ping"); pingCommand.HelpText("Ping a specific bot (node)"); pingCommand.Handler(pingHandler.Run); var nlpImportHandler = new NLPImportHandler(); var nlpImportCommand = app.Command("nlp-import"); nlpImportHandler.Node = nlpImportCommand.Parameter <string>("n").Alias("node").HelpText("Node to receive the data"); nlpImportHandler.Authorization = nlpImportCommand.Parameter <string>("a").Alias("authorization").HelpText("Node Authorization to receive the data"); nlpImportHandler.EntitiesFilePath = nlpImportCommand.Parameter <string>("ep").Alias("entities").HelpText("Path to entities file in CSV format"); nlpImportHandler.IntentsFilePath = nlpImportCommand.Parameter <string>("ip").Alias("intents").HelpText("Path to intents file in CSV format"); nlpImportHandler.AnswersFilePath = nlpImportCommand.Parameter <string>("ap").Alias("answers").HelpText("Path to answers file in CSV format"); nlpImportCommand.HelpText("Import intents and entities to a specific bot (node)"); nlpImportCommand.Handler(nlpImportHandler.Run); var copyHandler = ServiceProvider.GetService <CopyHandler>(); var copyCommand = app.Command("copy"); copyHandler.From = copyCommand.Parameter <string>("f").Alias("from").HelpText("Node (bot) source."); copyHandler.To = copyCommand.Parameter <string>("t").Alias("to").HelpText("Node (bot) target"); copyHandler.FromAuthorization = copyCommand.Parameter <string>("fa").Alias("fromAuthorization").HelpText("Authorization key of source bot"); copyHandler.ToAuthorization = copyCommand.Parameter <string>("ta").Alias("toAuthorization").HelpText("Authorization key of target bot"); copyHandler.Contents = copyCommand.Parameter <List <BucketNamespace> >("c").Alias("contents").HelpText($"Define which contents will be copied. Examples: '{copyHandler.GetTypesListAsString<BucketNamespace>()}'").ParseUsing(copyHandler.CustomNamespaceParser); copyHandler.Verbose = _verbose; copyHandler.Force = _force; copyCommand.HelpText("Copy data from source bot (node) to target bot (node)"); copyCommand.Handler(copyHandler.Run); var saveNodeHandler = new SaveNodeHandler(); var saveNodeCommand = app.Command("saveNode"); saveNodeHandler.Node = saveNodeCommand.Parameter <string>("n").Alias("node").HelpText("Node (bot) to be saved"); saveNodeHandler.AccessKey = saveNodeCommand.Parameter <string>("k").Alias("accessKey").HelpText("Node accessKey"); saveNodeHandler.Authorization = saveNodeCommand.Parameter <string>("a").Alias("authorization").HelpText("Node authoriaztion header"); saveNodeCommand.HelpText("Save a node (bot) to be used next"); saveNodeCommand.Handler(saveNodeHandler.Run); var formatKeyHandler = new FormatKeyHandler(); var formatKeyCommand = app.Command("formatKey").Alias("fk"); formatKeyHandler.Identifier = formatKeyCommand.Parameter <string>("i").Alias("identifier").HelpText("Bot identifier").Required(); formatKeyHandler.AccessKey = formatKeyCommand.Parameter <string>("k").Alias("accessKey").HelpText("Bot accessKey"); formatKeyHandler.Authorization = formatKeyCommand.Parameter <string>("a").Alias("authorization").HelpText("Bot authoriaztion header"); formatKeyCommand.HelpText("Show all valid keys for a bot"); formatKeyCommand.Handler(formatKeyHandler.Run); var nlpAnalyseHandler = ServiceProvider.GetService <NLPAnalyseHandler>(); var nlpAnalyseCommand = app.Command("nlp-analyse").Alias("analyse"); nlpAnalyseHandler.Input = nlpAnalyseCommand.Parameter <string>("i").Alias("input").HelpText("Input to be analysed. Works with a single phrase or with a text file (new line separator)."); nlpAnalyseHandler.Authorization = nlpAnalyseCommand.Parameter <string>("a").Alias("authorization").HelpText("Bot authorization key"); nlpAnalyseHandler.ReportOutput = nlpAnalyseCommand.Parameter <string>("o").Alias("report").Alias("output").HelpText("Report's file fullname (path + name)"); nlpAnalyseHandler.Force = _force; nlpAnalyseHandler.Verbose = _verbose; nlpAnalyseCommand.HelpText("Analyse some text or file using a bot IA model"); nlpAnalyseCommand.Handler(nlpAnalyseHandler.Run); var exportHandler = ServiceProvider.GetService <ExportHandler>(); var exportCommand = app.Command("export").Alias("get"); exportHandler.Node = exportCommand.Parameter <string>("n").Alias("node").HelpText("Node (bot) source"); exportHandler.Authorization = exportCommand.Parameter <string>("a").Alias("authorization").HelpText("Authorization key of source bot"); exportHandler.OutputFilePath = exportCommand.Parameter <string>("o").Alias("output").Alias("path").HelpText("Output file path. Please use a full path."); exportHandler.Model = exportCommand.Parameter <ExportModel>("m").Alias("model").HelpText($"Model to be exported. Examples: \'{exportHandler.GetTypesListAsString<ExportModel>()}\'").ParseUsing(exportHandler.CustomParser); exportHandler.Verbose = _verbose; exportHandler.Excel = exportCommand.Parameter <string>("x").Alias("excel").HelpText("Export content in a excel file. Please specify the file name (without extension)"); exportCommand.HelpText("Export some BLiP model"); exportCommand.Handler(exportHandler.Run); var compareHandler = ServiceProvider.GetService <NLPCompareHandler>(); var compareCommand = app.Command("comp").Alias("compare"); compareHandler.Authorization1 = compareCommand.Parameter <string>("a1").Alias("authorization1").Alias("first").HelpText("Authorization key of first bot"); compareHandler.Bot1Path = compareCommand.Parameter <string>("p1").Alias("path1").Alias("firstpath").HelpText("Path of first bot containing exported model"); compareHandler.Authorization2 = compareCommand.Parameter <string>("a2").Alias("authorization2").Alias("second").HelpText("Authorization key of second bot"); compareHandler.Bot2Path = compareCommand.Parameter <string>("p2").Alias("path2").Alias("secondpath").HelpText("Path of second bot containing exported model"); compareHandler.OutputFilePath = compareCommand.Parameter <string>("o").Alias("output").Alias("path").HelpText("Output file path"); compareHandler.Method = compareCommand.Parameter <ComparisonMethod>("m").Alias("method").HelpText("Comparison method (exact, levenshtein)").ParseUsing(compareHandler.CustomMethodParser); compareHandler.Verbose = _verbose; compareCommand.HelpText("Compare two knowledgebases"); compareCommand.Handler(compareHandler.Run); app.HelpCommand(); return app.Parse(args).Run(); })); }
public virtual async Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> messages) { var eventDataList = new List <EventData>(); EventData lastEventData = null; if (ConsumerConfiguration.ConsumeDelayInSeconds == null) { lastEventData = messages.LastOrDefault(); eventDataList = messages.ToList(); } else { foreach (var eventData in messages) { if (ConsumerConfiguration.ConsumeDelayInSeconds != null && eventData.SystemProperties.EnqueuedTimeUtc <= DateTime.UtcNow.AddSeconds(ConsumerConfiguration.ConsumeDelayInSeconds.Value * (-1))) { lastEventData = eventData; eventDataList.Add(eventData); } else { break; } } } if (lastEventData != null) { try { bool sucess = await ProcessEventDataList(context, eventDataList); if (sucess) { await context.CheckpointAsync(lastEventData); } else if (!sucess && !string.IsNullOrWhiteSpace(ConsumerConfiguration.ProducerName)) { var sendToShuntList = new List <EventData>(); var sendToRetryList = new List <EventData>(); IEventHubProducerService eventHubProducerService = ServiceProvider.GetService <IEventHubProducerService>(); foreach (var eventData in eventDataList) { if (eventData.HasIsOkProperty()) { eventData.RemoveSendToShuntProperty().RemoveIsOkProperty().RemoveRetryProperty(); continue; } int incrementedRetryProperty = eventData.IncrementRetryProperty(); if (!string.IsNullOrWhiteSpace(ConsumerConfiguration.Shunt?.ProducerName) && (eventData.HasSendToShuntProperty() || (ConsumerConfiguration.Shunt.MaxRetry > 0 && incrementedRetryProperty > ConsumerConfiguration.Shunt.MaxRetry)) ) { eventData.RemoveSendToShuntProperty().RemoveIsOkProperty().RemoveRetryProperty(); sendToShuntList.Add(eventData); } else { sendToRetryList.Add(eventData); } } if (sendToShuntList.Any()) { await eventHubProducerService.SendEventDataAsync(ConsumerConfiguration.Shunt.ProducerName, sendToShuntList); } if (sendToRetryList.Any()) { await eventHubProducerService.SendEventDataAsync(ConsumerConfiguration.ProducerName, sendToRetryList); } await context.CheckpointAsync(lastEventData); } } catch (Exception ex) { IEventProcessorFactory eventProcessorFactory = null; try { await Task.Run(() => new ExecuteAsync(1, 1000, async() => { IEventHubConsumerService eventHubConsumerService = ServiceProvider.GetService <IEventHubConsumerService>(); eventProcessorFactory = await eventHubConsumerService.UnregisterEventMessageConsumerAsync(ConsumerConfiguration.Name); Thread.Sleep(10000); await eventHubConsumerService.RegisterEventMessageConsumerAsync(ConsumerConfiguration.Name, eventProcessorFactory); }).Do(true)); } catch (Exception ex2) { if (ServiceProvider != null) { IEventHubConsumerService eventHubConsumerService = ServiceProvider.GetService <IEventHubConsumerService>(); if (eventProcessorFactory != null) { await eventHubConsumerService.RegisterEventMessageConsumerAsync(ConsumerConfiguration.Name, eventProcessorFactory); } } } } } }
public EmployeeTest() { _notificationHandler = ServiceProvider.GetRequiredService <INotificationHandler>(); }
public virtual async Task DisposeAsync() { await ServiceProvider.DisposeAsync(); Dispose(); }
public async Task FutureEpochValidatorDuty() { // Arrange IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true); testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>()); ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); // Get genesis store initialise MemoryStoreProvider with the state IStore store = forkChoice.GetGenesisStore(state); // Move forward time TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; ulong time = state.GenesisTime + 1; ulong nextSlotTime = state.GenesisTime + timeParameters.SecondsPerSlot; // half way through epoch 4 ulong futureEpoch = 4uL; ulong slots = futureEpoch * timeParameters.SlotsPerEpoch + timeParameters.SlotsPerEpoch / 2; for (ulong slot = 1; slot < slots; slot++) { while (time < nextSlotTime) { forkChoice.OnTick(store, time); time++; } forkChoice.OnTick(store, time); time++; // Hash32 head = await forkChoice.GetHeadAsync(store); // store.TryGetBlockState(head, out BeaconState headState); BeaconState headState = state; BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, headState, signed: true); TestState.StateTransitionAndSignBlock(testServiceProvider, headState, block); forkChoice.OnBlock(store, block); nextSlotTime = nextSlotTime + timeParameters.SecondsPerSlot; } // halfway through slot ulong futureTime = nextSlotTime + timeParameters.SecondsPerSlot / 2; while (time < futureTime) { forkChoice.OnTick(store, time); time++; } Console.WriteLine(""); Console.WriteLine("***** State advanced to epoch {0}, slot {1}, time {2}, ready to start tests *****", futureEpoch, state.Slot, store.Time); Console.WriteLine(""); List <object?[]> data = FutureEpochValidatorDutyData().ToList(); for (int dataIndex = 0; dataIndex < data.Count; dataIndex++) { object?[] dataRow = data[dataIndex]; string publicKey = (string)dataRow[0] !; ulong epoch = (ulong)dataRow[1] !; bool success = (bool)dataRow[2] !; ulong attestationSlot = (ulong)dataRow[3] !; ulong attestationShard = (ulong)dataRow[4] !; ulong? blockProposalSlot = (ulong?)dataRow[5]; Console.WriteLine("** Test {0}, public key {1}, epoch {2}", dataIndex, publicKey, epoch); // Act ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>(); BlsPublicKey validatorPublicKey = new BlsPublicKey(publicKey); Epoch targetEpoch = new Epoch(epoch); // failure expected if (!success) { Should.Throw <Exception>(async() => { ValidatorDuty validatorDuty = await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch); Console.WriteLine( "Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}", validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot, (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot); }, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); continue; } ValidatorDuty validatorDuty = await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch); Console.WriteLine("Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}", validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot, (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot); // Assert validatorDuty.ValidatorPublicKey.ShouldBe(validatorPublicKey, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); Slot expectedBlockProposalSlot = blockProposalSlot.HasValue ? new Slot(blockProposalSlot.Value) : Slot.None; Slot expectedAttestationSlot = new Slot(attestationSlot); Shard expectedAttestationShard = new Shard(attestationShard); validatorDuty.BlockProposalSlot.ShouldBe(expectedBlockProposalSlot, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); validatorDuty.AttestationSlot.ShouldBe(expectedAttestationSlot, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); validatorDuty.AttestationShard.ShouldBe(expectedAttestationShard, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); } }
public void ReportIAmDead() { var limit = ServiceProvider.GetService<IActivationLimit>(); limit?.ReportIAmDead(); }
private void OnStartup(object sender, StartupEventArgs e) { var mainView = ServiceProvider.GetService <MainView>(); mainView.Show(); }
public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams) { try { Directory.Delete(replacementsDictionary["$destinationdirectory$"]); Directory.Delete(replacementsDictionary["$solutiondirectory$"]); } catch { // If it fails (doesn't exist/contains files/read-only), let the directory stay. } var oleProvider = automationObject as Microsoft.VisualStudio.OLE.Interop.IServiceProvider; if (oleProvider == null) { MessageBox.Show("Unable to start wizard: no automation object available.", "Visual Studio"); throw new WizardBackoutException(); } using (var serviceProvider = new ServiceProvider(oleProvider)) { int hr = EnsurePythonPackageLoaded(serviceProvider); if (ErrorHandler.Failed(hr)) { MessageBox.Show(string.Format("Unable to start wizard: failed to load Python support Package (0x{0:X08})", hr), "Visual Studio"); throw new WizardBackoutException(); } // Cookiecutter is installed by default, but can be deselected/uninstalled separately from Python component hr = EnsureCookiecutterPackageLoaded(serviceProvider); if (ErrorHandler.Failed(hr)) { var dlg = new TaskDialog(serviceProvider) { Title = Strings.ProductTitle, MainInstruction = Strings.CookiecutterComponentRequired, Content = Strings.CookiecutterComponentInstallInstructions, AllowCancellation = true }; dlg.Buttons.Add(TaskDialogButton.Cancel); var download = new TaskDialogButton(Strings.DownloadAndInstall); dlg.Buttons.Insert(0, download); if (dlg.ShowModal() == download) { InstallTools(serviceProvider); throw new WizardCancelledException(); } } var uiShell = (IVsUIShell)serviceProvider.GetService(typeof(SVsUIShell)); string projName = replacementsDictionary["$projectname$"]; string directory = Path.GetDirectoryName(replacementsDictionary["$destinationdirectory$"]); var wizardData = replacementsDictionary["$wizarddata$"]; var templateUri = Resolve(new Uri(wizardData)); object inObj = projName + "|" + directory + "|" + templateUri.ToString(); var guid = GuidList.guidCookiecutterCmdSet; uiShell.PostExecCommand(ref guid, cmdidNewProjectFromTemplate, 0, ref inObj); } throw new WizardCancelledException(); }
public GetAllOwnedTokensTests(TestFixture aTestFixture) { ServiceProvider = aTestFixture.ServiceProvider; Mediator = ServiceProvider.GetService <IMediator>(); Herc1155 = ServiceProvider.GetService <Herc1155Instance>(); }
public void MyTestInitialize() { this.target = new LawEnforcementProviderQueryLogics(); this.contact = new Contact { Email = "*****@*****.**", ID = 1, Website = "www.test.org", Phone = "9373608284", HelpLine = "9373608888" }; this.state = new State { Abbreviation = "OH", CountryID = 1, FullName = "Ohio", ID = 1 }; this.location1 = new Location { City = "testville 1", ContactID = 1, Contact = this.contact, ContactPersonID = 1, ID = 1, Display = true, Zip = "45344", Street = "Test way 1", State = this.state, StateID = this.state.ID, ProviderCoverages = new List <ProviderCoverage> { new ProviderCoverage { AreaID = 1, LocationID = 1 } } }; this.location2 = new Location { City = "testville 2", ContactID = 2, Contact = this.contact, ContactPersonID = 2, ID = 2, Display = true, Zip = "45344", Street = "Test way 2", State = this.state, StateID = this.state.ID, ProviderCoverages = new List <ProviderCoverage> { new ProviderCoverage { AreaID = 2, LocationID = 2 } } }; this.locations = new List <Location> { this.location1, this.location2 }; this.websiteAddress1 = string.Format( "{0}, {1}, {2}, {3}", this.location1.Street, this.location1.City, this.location1.State.Abbreviation, this.location1.Zip); this.websiteAddress2 = string.Format( "{0}, {1}, {2}, {3}", this.location2.Street, this.location2.City, this.location2.State.Abbreviation, this.location2.Zip); var providerService11 = new ProviderService { ID = 1, ProviderID = 1, ServiceID = 1 }; var providerService12 = new ProviderService { ID = 2, ProviderID = 1, ServiceID = 2 }; var providerService13 = new ProviderService { ID = 3, ProviderID = 1, ServiceID = 3 }; var providerService21 = new ProviderService { ID = 1, ProviderID = 2, ServiceID = 1 }; var providerService22 = new ProviderService { ID = 2, ProviderID = 2, ServiceID = 2 }; var providerService23 = new ProviderService { ID = 3, ProviderID = 2, ServiceID = 3 }; this.providerServices1 = new List <ProviderService> { providerService11, providerService12, providerService13, }; this.providerServices2 = new List <ProviderService> { providerService21, providerService22, providerService23 }; this.serviceProvider1 = new ServiceProvider { Description = "Test description for test 1", ID = 1, ServiceTypes = 2, DisplayRank = 1, ProviderName = "Test 1", Locations = this.locations, ProviderServices = this.providerServices1 }; this.serviceProvider2 = new ServiceProvider { Description = "Test description for test 2", ID = 2, ServiceTypes = 2, DisplayRank = 2, ProviderName = "Test 2", Locations = this.locations, ProviderServices = this.providerServices2 }; this.serviceProviderList = new List <ServiceProvider> { this.serviceProvider1, this.serviceProvider2 }; }
/// <summary> /// 获取指定实体类所属的上下文类型 /// </summary> /// <param name="entityType">实体类型</param> /// <returns>上下文类型</returns> public Type GetDbContextType(Type entityType) { IEntityManager entityManager = ServiceProvider.GetService <IEntityManager>(); return(entityManager.GetDbContextTypeForEntity(entityType)); }
public LinkMenuBase(IGitHubServiceProvider serviceProvider) : base(serviceProvider) { usageTracker = new Lazy <IUsageTracker>(() => ServiceProvider.TryGetService <IUsageTracker>()); }
/// <summary> /// Creates the object instances for the types contained in the types collection. /// </summary> /// <returns>A list of objects of type <typeparamref name="TResolved"/>.</returns> protected virtual IEnumerable <TResolved> CreateInstances() { return(ServiceProvider.CreateInstances <TResolved>(InstanceTypes, Logger)); }
private void OnValidEvaluate(object sender, EvaluateInternalEventArgs evaluateInternalEventArgs) { var loadCarrierReceiptRepo = ServiceProvider.GetService <IRepository <Olma.LoadCarrierReceipt> >(); Context.LoadCarrierReceipt = loadCarrierReceiptRepo.GetById <Olma.LoadCarrierReceipt, Contracts.Models.LoadCarrierReceipt>(Context.LoadCarrierReceiptId); }
/// <summary> /// Locate and return service type /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T GetService <T>() => ServiceProvider.GetService <T>();
private ParentObserver(Element view) { _view = ServiceProvider.WeakReferenceFactory(view); _parent = ToolkitExtensions.GetWeakReferenceOrDefault(FindParent(view), Empty.WeakReference, false); view.PropertyChanged += OnPropertyChanged; }
/// <summary> /// Managed objects /// </summary> public void Dispose() { ServiceProvider.Dispose(); ServiceCollection.Clear(); }
public OAuthHandler() { m_Provider = new ServiceProvider(); }
/// <summary> /// Used for initialization of the editor in the environment /// </summary> /// <param name="psp"> /// pointer to the service provider. Can be used to obtain instances of other interfaces /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> public int SetSite(IOleServiceProvider psp) { this.vsServiceProvider = new ServiceProvider(psp); return(VSConstants.S_OK); }
public App() { serviceProvider = ConfigureServices(new ServiceCollection()).BuildServiceProvider(); SetupExceptionHandling(); }
public CurrentTenant_Tests() { _currentTenant = ServiceProvider.GetRequiredService <ICurrentTenant>(); }
private ParentObserver(Element view) { _view = ServiceProvider.WeakReferenceFactory(view, true); _parent = ServiceProvider.WeakReferenceFactory(FindParent(view), true); view.PropertyChanged += OnPropertyChanged; }
public StartupFixture() { services = CreateContainer(); Provider = services.BuildServiceProvider(); Provider.GetRequiredService <IHostedService>().StartAsync(default).Wait();
internal void SetProvider(ServiceProvider provider) { base.Provider = provider; }
public ComplexTypeJsonIntegrationTest(StartupFixture fix) { fixture = fix; provider = fixture.Provider; }
/// <summary> /// Find the OSLC Creation Factory URL for a given OSLC resource type. If no resource type is given, returns /// the default Creation Factory, if it exists. /// </summary> /// <param name="serviceProviderUrl"></param> /// <param name="oslcDomain"></param> /// <param name="oslcResourceType">the resource type of the desired query capability. This may differ from the OSLC artifact type.</param> /// <returns>URL of requested Creation Factory or null if not found.</returns> public string LookupCreationFactory(string serviceProviderUrl, string oslcDomain, string oslcResourceType) { CreationFactory defaultCreationFactory = null; CreationFactory firstCreationFactory = null; HttpResponseMessage response = GetResource(serviceProviderUrl, OSLCConstants.CT_RDF); if (response.StatusCode != HttpStatusCode.OK) { throw new ResourceNotFoundException(serviceProviderUrl, "CreationFactory"); } ServiceProvider serviceProvider = response.Content.ReadAsAsync <ServiceProvider>(formatters).Result; if (serviceProvider != null) { foreach (Service service in serviceProvider.GetServices()) { Uri domain = service.GetDomain(); if (domain != null && domain.ToString().Equals(oslcDomain)) { CreationFactory [] creationFactories = service.GetCreationFactories(); if (creationFactories != null && creationFactories.Length > 0) { firstCreationFactory = creationFactories[0]; foreach (CreationFactory creationFactory in creationFactories) { foreach (Uri resourceType in creationFactory.GetResourceTypes()) { //return as soon as domain + resource type are matched if (resourceType.ToString() != null && resourceType.ToString().Equals(oslcResourceType)) { return(creationFactory.GetCreation().ToString()); } } //Check if this is the default factory foreach (Uri usage in creationFactory.GetUsages()) { if (usage.ToString() != null && usage.ToString().Equals(OSLCConstants.USAGE_DEFAULT_URI)) { defaultCreationFactory = creationFactory; } } } } } } } //If we reached this point, there was no resource type match if (defaultCreationFactory != null) { //return default, if present return(defaultCreationFactory.GetCreation().ToString()); } else if (firstCreationFactory != null && firstCreationFactory.GetResourceTypes().Length == 0) { //return the first for the domain, if present return(firstCreationFactory.GetCreation().ToString()); } throw new ResourceNotFoundException(serviceProviderUrl, "CreationFactory"); }
public virtual async Task InitializeAsync() { var startupRunner = ServiceProvider.GetRequiredService <IStartupRunner>(); await startupRunner.StartupAsync(); }
internal SqlServerFhirStorageTestsFixture(int maximumSupportedSchemaVersion, string databaseName) { var initialConnectionString = Environment.GetEnvironmentVariable("SqlServer:ConnectionString") ?? LocalConnectionString; _maximumSupportedSchemaVersion = maximumSupportedSchemaVersion; _databaseName = databaseName; TestConnectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = _databaseName }.ToString(); var schemaOptions = new SqlServerSchemaOptions { AutomaticUpdatesEnabled = true }; var config = new SqlServerDataStoreConfiguration { ConnectionString = TestConnectionString, Initialize = true, SchemaOptions = schemaOptions }; var schemaInformation = new SchemaInformation(SchemaVersionConstants.Min, maximumSupportedSchemaVersion); var scriptProvider = new ScriptProvider <SchemaVersion>(); var baseScriptProvider = new BaseScriptProvider(); var mediator = Substitute.For <IMediator>(); var sqlConnectionFactory = new DefaultSqlConnectionFactory(config); var schemaUpgradeRunner = new SchemaUpgradeRunner(scriptProvider, baseScriptProvider, mediator, NullLogger <SchemaUpgradeRunner> .Instance, sqlConnectionFactory); _schemaInitializer = new SchemaInitializer(config, schemaUpgradeRunner, schemaInformation, sqlConnectionFactory, NullLogger <SchemaInitializer> .Instance); var searchParameterDefinitionManager = new SearchParameterDefinitionManager(ModelInfoProvider.Instance); _filebasedSearchParameterStatusDataStore = new FilebasedSearchParameterStatusDataStore(searchParameterDefinitionManager, ModelInfoProvider.Instance); var securityConfiguration = new SecurityConfiguration { PrincipalClaims = { "oid" } }; var sqlServerFhirModel = new SqlServerFhirModel( config, schemaInformation, searchParameterDefinitionManager, () => _filebasedSearchParameterStatusDataStore, Options.Create(securityConfiguration), NullLogger <SqlServerFhirModel> .Instance); var serviceCollection = new ServiceCollection(); serviceCollection.AddSqlServerTableRowParameterGenerators(); serviceCollection.AddSingleton(sqlServerFhirModel); ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); var upsertResourceTvpGeneratorV6 = serviceProvider.GetRequiredService <V6.UpsertResourceTvpGenerator <ResourceMetadata> >(); var upsertResourceTvpGeneratorVLatest = serviceProvider.GetRequiredService <VLatest.UpsertResourceTvpGenerator <ResourceMetadata> >(); var upsertSearchParamsTvpGenerator = serviceProvider.GetRequiredService <VLatest.UpsertSearchParamsTvpGenerator <List <ResourceSearchParameterStatus> > >(); var searchParameterToSearchValueTypeMap = new SearchParameterToSearchValueTypeMap(); SqlTransactionHandler = new SqlTransactionHandler(); SqlConnectionWrapperFactory = new SqlConnectionWrapperFactory(SqlTransactionHandler, new SqlCommandWrapperFactory(), sqlConnectionFactory); SqlServerSearchParameterStatusDataStore = new SqlServerSearchParameterStatusDataStore( () => SqlConnectionWrapperFactory.CreateMockScope(), upsertSearchParamsTvpGenerator, () => _filebasedSearchParameterStatusDataStore, schemaInformation); FhirDataStore = new SqlServerFhirDataStore(config, sqlServerFhirModel, searchParameterToSearchValueTypeMap, upsertResourceTvpGeneratorV6, upsertResourceTvpGeneratorVLatest, Options.Create(new CoreFeatureConfiguration()), SqlConnectionWrapperFactory, NullLogger <SqlServerFhirDataStore> .Instance, schemaInformation); _fhirOperationDataStore = new SqlServerFhirOperationDataStore(SqlConnectionWrapperFactory, NullLogger <SqlServerFhirOperationDataStore> .Instance); _testHelper = new SqlServerFhirStorageTestHelper(initialConnectionString, MasterDatabaseName, searchParameterDefinitionManager, sqlServerFhirModel, sqlConnectionFactory); }
protected CoinbaseClientTestsBase(CoinbaseApiFixture apiFixture, ITestOutputHelper output) { Logger = new LoggerConfiguration().WriteTo.TestOutput(output).CreateLogger(); ServiceProvider = apiFixture.ServiceProvider; }