public void ShouldUseUnregisteredConstructorArgument() { locator.Register(Given<ITestInterface>.Then<DependsOnInterface>()); var argument = new ConstructorArgument(); var instance = locator.GetInstance<ITestInterface>(new ConstructorParameter {Name = "argument", Value = argument}); Assert.AreSame(argument, ((DependsOnInterface) instance).Argument); }
public void ShouldResolveWithArgsInAnyOrder() { locator.Register(Given<ITestInterface>.Then<DependsOnMultipleInterfaceTypes>()); var argument = new ConstructorArgument(); var instance = locator.GetInstance<ITestInterface>(new ConstructorParameter { Name = "arg", Value = argument }); Assert.AreSame(argument, ((DependsOnMultipleInterfaceTypes)instance).Arg); Assert.AreSame(locator, ((DependsOnMultipleInterfaceTypes)instance).Locator); }
/// <inheritdoc /> public IEsnCenter CreateEsnCenter(UserConnection userConnection) { var userConnectionArgument = new ConstructorArgument("userConnection", userConnection); var likeRepository = ClassFactory.Get <IEsnLikeRepository>(userConnectionArgument); var esnMessageReader = ClassFactory.Get <IEsnMessageReader>(userConnectionArgument); var esnMessageRedactor = ClassFactory.Get <IEsnMessageRedactor>(userConnectionArgument); var esnSecurityEngine = ClassFactory.Get <IEsnSecurityEngine>(userConnectionArgument); return(ClassFactory.Get <IEsnCenter>( new ConstructorArgument("esnLikeRepository", likeRepository), new ConstructorArgument("esnMessageReader", esnMessageReader), new ConstructorArgument("esnMessageRedactor", esnMessageRedactor), new ConstructorArgument("esnSecurityEngine", esnSecurityEngine))); }
private void EditJobButton_Click(object sender, RoutedEventArgs e) { var reposArgument = new ConstructorArgument("repository", kernel.Get <IExperienceRepository>()); var id = ((IExperienceEntity)JobsDataGrid.SelectedItem).ID; var idArgument = new ConstructorArgument("jobId", id); var ejVM = kernel.Get <IEditJobViewModel>(reposArgument, idArgument); ejVM.JobEdited += JobDialog_Closing; ucHost.Content = new EditJobView(ejVM); ucHost.Visibility = Visibility.Visible; }
/// <summary> /// Converts a set of filters to process format. /// </summary> /// <param name="userConnection">User connection.</param> /// <param name="entitySchema">Entity schema.</param> /// <param name="processActivity">Process activity.</param> /// <param name="dataSourceFilters">Serialized filters.</param> /// <returns>Set of filters in the process format.</returns> public static string ConvertToProcessDataSourceFilters(UserConnection userConnection, EntitySchema entitySchema, ProcessActivity processActivity, string dataSourceFilters) { userConnection.CheckArgumentNull("userConnection"); entitySchema.CheckArgumentNull("entitySchema"); processActivity.CheckArgumentNull("processActivity"); dataSourceFilters.CheckArgumentNullOrEmpty("dataSourceFilters"); var userConnectionArgument = new ConstructorArgument("userConnection", userConnection); var processDataSourceFiltersConverter = ClassFactory .Get <IProcessDataSourceFiltersConverter>(userConnectionArgument); return(processDataSourceFiltersConverter.ConvertToProcessDataSourceFilters(processActivity, entitySchema.UId, dataSourceFilters)); }
public void CtorIsUsedWhenParameterIsSupplied() { using (IKernel kernel = new StandardKernel()) { kernel.Bind <Barracks>().ToSelf(); var constructorArgument = new ConstructorArgument("warrior", new Samurai(new Sword())); var barracks = kernel.Get <Barracks>(constructorArgument); barracks.Should().NotBeNull(); barracks.Warrior.Should().NotBeNull(); barracks.Warrior.Weapon.Should().NotBeNull(); barracks.Weapon.Should().BeNull(); } }
protected internal virtual string WriteConstructorArgument(ConstructorArgument argument) { if (argument == null) { return(string.Empty); } if (!argument.AfterOptions) { return(WriteArgument(argument)); } return($"_{argument.Parameter.ParameterName} = {argument.Parameter.ParameterName};"); }
/// <summary> /// Initializes a new instance of the <see cref="MLModelTrainer"/> class. /// </summary> /// <param name="userConnection">The user connection.</param> /// <param name="modelConfig">The model configuration.</param> public MLModelTrainer(UserConnection userConnection, MLModelConfig modelConfig) { userConnection.CheckArgumentNull("userConnection"); modelConfig.CheckArgumentNull("modelConfig"); modelConfig.Id.CheckArgumentEmpty("MLModelConfig.Id"); _userConnection = userConnection; _modelConfig = modelConfig; _proxy = InitServiceProxy(); ConstructorArgument userConnectionArg = new ConstructorArgument("userConnection", _userConnection); _modelEventsNotifier = ClassFactory.Get <MLModelEventsNotifier>(userConnectionArg); _metadataGenerator = ClassFactory.Get <IMLMetadataGenerator>(); _queryBuilder = ClassFactory.Get <IMLModelQueryBuilder>(userConnectionArg); }
static void Main(string[] args) { var resolver = DependencyFactory.GetResolver(new FlightModule(), new BaseCQRSBindingModule()); var handlerItems = resolver.GetAll <IHandlerItem>().ToList(); foreach (var item in handlerItems) { var commandParams = new ConstructorArgument[] { new ConstructorArgument("_handlerItem", item) }; var busContainer = resolver.Get <IBusContainer>(commandParams); busContainer.Subscribe(); } }
public virtual ICmdExecutor CreateForCommand(IInstallCmd command) { foreach (var pair in CommandToExecutorsMap) { if (pair.Key.IsInstanceOfType(command)) { var argument = new ConstructorArgument("command", command); var executorInstance = (ICmdExecutor)kernel.Get(pair.Value, argument); return(executorInstance); } } throw new InvalidOperationException("Cannot create an executor for the provided command"); }
public void LoadNextContacts(int count = 10) { IsLoading = true; var currentMonth = DateTime.Today.Month; var currentDay = DateTime.Today.Day; var all = _allBirthdays.OrderBy(it => it.Date.Month == currentMonth ? (it.Date.Day < currentDay ? it.DaysUntil - 365 : it.DaysUntil) : it.DaysUntil).ThenBy(it => it.Age).Skip(_allContacts.Count).Take(count); foreach (var u in all) { ConstructorArgument arg = new ConstructorArgument("contact", u); var contactModel = KernelService.Kernel.Get <ContactViewModel>(arg); _allContacts.Add(contactModel); } IsLoading = false; }
public void Send(IEnumerable <ICommand> commands) { using (var context = Context()) { var contextParameter = new ConstructorArgument("context", context); foreach (var command in commands.Distinct()) { var handlerType = typeof(IHandler <>).MakeGenericType(command.GetType()); var handler = (dynamic)Resolver.Get(handlerType, contextParameter); handler.Handle((dynamic)command); } context.Save(); } }
internal static T GetCommand <T>(CommonCmdletBase cmdlet) { try { T newCommand = default(T); var cmdletParam = new ConstructorArgument("cmdlet", cmdlet); newCommand = Kernel.Get <T>(cmdletParam); return(ConvertToProxiedCommand <T>(newCommand, cmdlet)); } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Command 01"); // Console.WriteLine(eCommand.Message); return(default(T)); } }
private List <ClassificationResult> QueryPrediction(Dictionary <string, object> classifyData) { var apiKey = BpmonlineCloudEngine.GetAPIKey(_userConnection); var serviceUrlArg = new ConstructorArgument("serviceUrl", ServiceUrl); var apiKeyArg = new ConstructorArgument("apiKey", apiKey); IMLServiceProxy proxy = ClassFactory.Get <IMLServiceProxy>(serviceUrlArg, apiKeyArg); List <ClassificationResult> classificationResults = null; try { classificationResults = proxy.Classify(ModelInstanceUId, classifyData); } catch (Exception e) { _log.ErrorFormat("Classification failed with error: {0}", e, e.Message); } return(classificationResults); }
/// <summary> /// Initializes and returns kit by iterator name (<paramref name="iteratorTagName"/>) /// and storage name (<paramref name="storeTagName"/>). /// </summary> /// <param name="iteratorTagName">Tag for getting language iterator.</param> /// <param name="storeTagName">Tag for getting content store.</param> /// <returns>Kit for working with multilanguage content.</returns> /// <remarks>(<paramref name="iteratorTagName"/>) has to be named, like schema (Case, Contact, etc.)</remarks> public virtual IContentKit GetContentKit(string iteratorTagName, string storeTagName) { var userConnectionArgument = new ConstructorArgument("userConnection", UserConnection); ClassFactory.TryGet(iteratorTagName, out ILanguageIterator languageIterator, userConnectionArgument); languageIterator = languageIterator ?? GetDefaultIterator(iteratorTagName); IContentStore contentStore = ClassFactory.Get <IContentStore>(storeTagName, userConnectionArgument); IContentKit contentKit = ClassFactory.Get <IContentKit>( new ConstructorArgument("contentStore", contentStore), new ConstructorArgument("languageIterator", languageIterator)); return(contentKit); }
/// <summary> /// Inintialize new instance of <see cref="EmailMiner"/> /// </summary> /// <param name="userConnection">User connection for data operations (search contacts, accounts).</param> public EmailMiner(UserConnection userConnection) { _userConnection = userConnection; var userConnectionConstructorArgument = new ConstructorArgument("userConnection", userConnection); _emailMinerService = ClassFactory.Get <IEmailMiningServiceProxy>(userConnectionConstructorArgument); _contactSearcher = ClassFactory.Get <IContactSearcher>(userConnectionConstructorArgument); _deduplicator = ClassFactory.Get <IDeduplicator>(userConnectionConstructorArgument); int actualDaysPeriod = Core.Configuration.SysSettings.GetValue(userConnection, IdentificationActualPeriodSysSettingsName, 1); _actualMinDate = _userConnection.CurrentUser.GetCurrentDateTime().AddDays(-actualDaysPeriod); _enrchTextEntitySchema = _userConnection.EntitySchemaManager.GetInstanceByName("EnrchTextEntity"); _enrichEntitySearchHelper = new EnrichEntitySearchHelper(_userConnection); }
public BulkDeduplicationManager(UserConnection userConnection, IAppSchedulerWraper appSchedulerWraper) : base(userConnection) { if (string.IsNullOrEmpty(DeduplicationWebApiUrl)) { Log.Error("DeduplicationWebApiUrl is empty."); } var userConnectionConstructorArgument = new ConstructorArgument("userConnection", userConnection); _startDeduplicationRequestFactory = ClassFactory.Get <IStartDeduplicationRequestFactory>( userConnectionConstructorArgument); _bulkDeduplicationTaskClient = ClassFactory.Get <IBulkDeduplicationTaskClient>( userConnectionConstructorArgument); _appSchedulerWraper = appSchedulerWraper; }
/// <summary> /// Start calculation reaction time and a solution time to Case. /// </summary> /// <param name="arguments">Dictionary with params for strategies.</param> /// <param name="startDate">Start date for calculation.</param> /// <returns></returns> public ServiceTermResponse ForceCalculateTerms(Dictionary <string, object> arguments, DateTime startDate) { var response = new ServiceTermResponse(); var userConnectionArg = new ConstructorArgument("userConnection", UserConnection); var argumentsArg = new ConstructorArgument("arguments", arguments); var selector = ClassFactory.Get <CaseTermIntervalSelector>(userConnectionArg); var termInterval = selector.Get(arguments) as CaseTermInterval; var mask = termInterval.GetMask(); if (mask != CaseTermStates.None) { var userTimeZone = UserConnection.CurrentUser.TimeZone; response = ExecuteCalculateTerms(startDate, termInterval, userTimeZone, mask); } return(response); }
internal static IUiEltCollection GetUiEltCollection() { try { var boolArgument = new ConstructorArgument("fake", true); // IUiEltCollection adapterCollection = Kernel.Get<IUiEltCollection>("Empty", boolArgument); IUiEltCollection adapterCollection = ChildKernel.Get <IUiEltCollection>("Empty", boolArgument); return(adapterCollection); } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Collection 04"); // Console.WriteLine(eFailedToIssueCollection.Message); return(null); } }
public override IController CreateController(RequestContext requestContext, string controllerName) { //You can improve this later if you want -> you'll need to figure out if your controller will fit into this case //You can use marker interfaces, common supertype, etc... that's up to you if (controllerName.Equals("home", StringComparison.InvariantCultureIgnoreCase)) { var controllerType = typeof(HomeController); var isChild = requestContext.RouteData.DataTokens.ContainsKey(ParentActionViewContextToken); var constructorArgument = new ConstructorArgument("someName", (isChild) ? "Child" : "Nope"); var requestForDependency = _resolutionRoot.CreateRequest(typeof(IServiceClient), null, new Parameter[] { constructorArgument }, true, true); var dependency = _resolutionRoot.Resolve(requestForDependency).SingleOrDefault(); return((IController)_resolutionRoot.Get(controllerType, new ConstructorArgument("service", dependency))); } //Will go through the default pipeline (IDependencyResolver will be called, not affecting DI of other controllers) return(base.CreateController(requestContext, controllerName)); }
public void ShouldUseMultipleUnregisteredConstructorArgument() { locator.Register(Given <ITestInterface> .Then <DependsOnMultipleInterface>()); var argument = new ConstructorArgument(); var argument2 = new ConstructorArgument(); var instance = locator.GetInstance <ITestInterface>(new ConstructorParameter { Name = "argument1", Value = argument }, new ConstructorParameter { Name = "argument2", Value = argument2 }); Assert.AreSame(argument, ((DependsOnMultipleInterface)instance).Argument); Assert.AreSame(argument2, ((DependsOnMultipleInterface)instance).Argument2); }
/// <summary> /// Creates EmailMessageData instance for <paramref name="activity"/>. /// </summary> /// <param name="activity">Activity entity instance.</param> /// <param name="email">Email model instance.</param> /// <param name="mailboxId">Mailbox identifier.</param> /// <param name="syncSessionId">Synchronization session identifier.</param> private void CreateEmailMessageData(Entity activity, EmailModel email, Guid mailboxId, string syncSessionId) { var ticks = _activityUtils.GetSendDateTicks(_userConnection, activity); var userConnectionParam = new ConstructorArgument("userConnection", _userConnection); var helper = ClassFactory.Get <IEmailMessageHelper>(userConnectionParam); Dictionary <string, string> headers = new Dictionary <string, string>() { { "MessageId", email.MessageId }, { "InReplyTo", email.InReplyTo }, { "SyncSessionId", syncSessionId }, { "References", email.References }, { "SendDateTicks", ticks.ToString() } }; helper.CreateEmailMessage(activity, mailboxId, headers); }
GetConstructorArguments(MethodInfo methodInfo, object[] arguments) { var parameters = methodInfo.GetParameters(); var constructorArguments = new ConstructorArgument[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { constructorArguments[i] = new ConstructorArgument (parameters[i].Name, arguments[i], true); } var resArray = constructorArguments.Skip(1).ToArray(); return(resArray); }
// to prevent from threading lock internal static IUiElement GetUiElement(IUiElement element) { if (null == element) { return(null); } try { var singleElement = new ConstructorArgument("element", element); // 20140122 IUiElement adapterElement; // = Kernel.Get<IUiElement>("UiElement", singleElement); // var childKernel = GetChildKernel(); // adapterElement = childKernel.Get<IUiElement>("UiElement", singleElement); adapterElement = ChildKernel.Get <IUiElement>("UiElement", singleElement); // childKernel.Dispose(); // (adapterElement as UiElement).ChildKernel = childKernel; // 20140313 // if (Preferences.UseElementsPatternObjectModel) { // if (Preferences.UseElementsPatternObjectModel || Preferences.UseElementsSearchObjectModel || Preferences.UseElementsCached || Preferences.UseElementsCurrent) { // if (Preferences.UseElementsPatternObjectModel || Preferences.UseElementsCached || Preferences.UseElementsCurrent) { if (Preferences.UseProxy) { IUiElement proxiedTypedUiElement = ConvertToProxiedElement( adapterElement); proxiedTypedUiElement.SetSourceElement <IUiElement>(element); return((IUiElement)proxiedTypedUiElement); } else { adapterElement.SetSourceElement <IUiElement>(element); return(adapterElement); } } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Element 02"); // Console.WriteLine(eFailedToIssueElement.Message); return(null); } }
public ILoggerBlock Block() { // create dependencies var indentation = Injector.Get <IIndentation>(); // get the calling method name var frame = new StackTrace().GetFrame(1); var methodName = $"{frame.GetMethod().DeclaringType}.{frame.GetMethod().Name}"; // now log the entry _logger.Trace($"{indentation}Entering {methodName}"); // create a new block var nameParameter = new ConstructorArgument("name", methodName); return(Injector.Get <ILoggerBlock>(nameParameter)); }
/// <summary> /// Gets the specified title. /// </summary> /// <param name="title">The title.</param> /// <param name="inputs">The inputs.</param> /// <returns> /// An input result /// </returns> public InputResult Get(string title, IList <IGenericInput> inputs) { var arguments = new ConstructorArgument[] { new ConstructorArgument("title", title), new ConstructorArgument("inputs", inputs) }; var view = this.viewFactory.Create <GenericInput>(); var viewModel = this.viewModelFactory.Create <GenericInputViewModel>(() => { view.Close(); }, arguments); view.DataContext = viewModel; // Hack to get the first element focused. if (view is Window w) { w.ContentRendered += (sender, e) => { viewModel.FocusFirstInput(); }; w.Activated += (sender, e) => { viewModel.FocusFirstInput(); }; } view.ShowDialog(); if (viewModel.UserAccepted) { return(new InputResult { UserAccepted = true, Output = viewModel.GetData() }); } else { return(new InputResult { UserAccepted = false, Output = null, }); } }
public List <Guid> FindRecordsSimilarLead(string schemaName, Guid leadId) { var deduplicationSearchArgs = new ConstructorArgument[] { new ConstructorArgument("userConnection", UserConnection) }; DeduplicationSearch deduplicationSearch = ClassFactory.Get <DeduplicationSearch>(deduplicationSearchArgs); var similarLeadSearchHelperArgs = new ConstructorArgument[] { new ConstructorArgument("userConnection", UserConnection), new ConstructorArgument("deduplicationSearch", deduplicationSearch) }; SimilarLeadSearchHelper similarLeadSearchHelper = ClassFactory.Get <SimilarLeadSearchHelper>(similarLeadSearchHelperArgs); List <Guid> similarRecords = similarLeadSearchHelper.FindLeadSimilarRecords(schemaName, leadId); return(similarRecords); }
/// <summary> /// Executes current flow element. /// </summary> /// <returns><c>true</c>, if element was successfully executed and conditions for moving to the next step were /// satisfied. Otherwise - <c>false</c>.</returns> protected override bool InternalExecute(ProcessExecutingContext context) { if (IsBatchPrediction) { var batchPredictionJob = ClassFactory.Get <IMLBatchPredictionJob>(); var converter = new FilterEditConverter(UserConnection); var filterEditData = converter.Convert(Owner, PredictionFilterData); batchPredictionJob.ProcessModel(UserConnection, MLModelId, filterEditData); } else { var constructorArgument = new ConstructorArgument("userConnection", UserConnection); var predictor = ClassFactory.Get <MLEntityPredictor>(constructorArgument); predictor.UseAdminRights = GlobalAppSettings.FeatureUseAdminRightsInEmbeddedLogic; predictor.PredictEntityValueAndSaveResult(MLModelId, RecordId); } return(true); }
private void DisplayProducts() { //Resolving dependency in Ninject var viewModel = App.Container.Get <ProductViewModel>(); var productsList = new List <Product>(); if (viewModel != null) { productsList = viewModel.ProductList.ToList(); } //passing constructor arguments in Ninject var contextArg = new ConstructorArgument("context", this); var productsArg = new ConstructorArgument("products", productsList); var productListAdapter = App.Container.Get <ProductListAdapter>(contextArg, productsArg); _productsListView.Adapter = productListAdapter; }
public RootCommand(CommandLineApplication app) { var configurationBuilder = _kernel.Get <IConfigurationBuilder>(); var protocolInfo = _kernel.Get <IProtocolInfo>(); var hostFileName = new ConstructorArgument("hostFileName", HostFileName); var sectionName = new ConstructorArgument("sectionFormat", SectionName); var builder = new ConstructorArgument("_builder", configurationBuilder); var info = new ConstructorArgument("protocolInfo", protocolInfo); _reader = _kernel.Get <Configuration.IConfigurationReader>(hostFileName, sectionName, builder); var read = new ConstructorArgument("reader", _reader); _writer = _kernel.Get <Configuration.IConfigurationWriter>(hostFileName, builder, info, read); _processor = _kernel.Get <IPingerProcessor>(new ConstructorArgument("confWorker", _reader), new ConstructorArgument("log", _kernel.Get <ILogger>())); _app = app; _app.HelpOption("-?|-h|--help"); }
private List <double> Predict(MLModelConfig model, IList <Dictionary <string, object> > dataForPrediction) { var apiKey = BpmonlineCloudEngine.GetAPIKey(_userConnection); var serviceUrlArg = new ConstructorArgument("serviceUrl", model.ServiceUrl); var apiKeyArg = new ConstructorArgument("apiKey", apiKey); IMLServiceProxy proxy; try { proxy = ClassFactory.Get <IMLServiceProxy>(serviceUrlArg, apiKeyArg); } catch (IncorrectConfigurationException ex) { _log.WarnFormat($"Can't predict value for model {model.Id}", ex); throw; } var predictionResults = Predict(model, dataForPrediction, proxy); return(predictionResults); }
public DuplicatesMergeResponse MergeEntityDuplicatesAsync(string schemaName, int groupId, List <Guid> deduplicateRecordIds, string mergeConfig) { Dictionary <string, string> config = null; if (!string.IsNullOrEmpty(mergeConfig)) { config = JsonConvert.DeserializeObject <Dictionary <string, string> >(mergeConfig); } var args = new ConstructorArgument[] { new ConstructorArgument("userConnection", UserConnection) }; DeduplicationProcessing deduplicationProcessing = ClassFactory.Get <DeduplicationProcessing>(args); DuplicatesMergeResponse response = deduplicationProcessing.MergeEntityDuplicatesAsync(schemaName, groupId, deduplicateRecordIds, config); return(response); }
public void ShouldBeAbleToSpecifyArgumentsUsedDuringLazyResolution() { var argument = new ConstructorArgument(); var argument2 = new ConstructorArgument(); var arguments = new List<IResolutionArgument> { new ConstructorParameter {Name = "argument1", Value = argument}, new ConstructorParameter {Name = "argument2", Value = argument2} }; locator.Register(Given<ITestInterface>.Then<DependsOnMultipleInterface>()); locator.Register(Given<DependsOnMultipleInterface>.ConstructWith(arguments)); var instance = locator.GetInstance<Func<ITestInterface>>(); Assert.AreSame(argument, ((DependsOnMultipleInterface)instance()).Argument); Assert.AreSame(argument2, ((DependsOnMultipleInterface)instance()).Argument2); }
public void Should_Resolve_If_Dependency_Is_Registered_As_Instance() { var arg = new ConstructorArgument(); locator .Register(Given<ITestInterface>.Then<DependsOnInterface>()) .Register(Given<IConstructorArgument>.Then(arg)); var resolution = locator.GetInstance<ITestInterface>(); Assert.IsTrue(resolution is DependsOnInterface); Assert.AreSame(arg, ((DependsOnInterface)resolution).Argument); }
public static int test() { var obj = new ConstructorArgument(1); return obj.field; }