public int Execute() { var outputs = new List<StreamWriter>(); try { settings .Files .Select(f => new Output(f, settings.FileMode).Open()) .Select(o => new StreamWriter(o)) .Each(outputs.Add); string line; while ((line = Console.In.ReadLine()) != null) { Console.Out.WriteLine(line); outputs.Each(o => o.WriteLine(line)); } return 0; } catch (Exception ex) { Console.Error.WriteLine(ex.Message); return 1; } finally { outputs.Each(o => o.Dispose()); } }
public void TakeABreak() { breakTimer.Enabled = false; currentOverlays = Screen.AllScreens.Select(screen => new Overlay(screen)).ToList(); currentOverlays.Each(overlay => overlay.Closing += (_, __) => TheBreakIsOver()); currentOverlays.Each(overlay => overlay.Show()); closeTimer.Enabled = true; }
public JObject[] find(JObject query) { var parms = query.ToTuple(); var result = new List<JObject>(); List<queryToken> tokens = new List<queryToken>(); int c = 0; parms.Each(x => { if (x.Item1.Contains(".$")) { string[] pair = x.Item1.Split(new string[1] { ".$" }, StringSplitOptions.None); var q = new queryToken(c++); q.key = pair[0]; q.val = x.Item2; switch (pair[1]) { case "eq": { q.op = "="; break; } case "lt": { q.op = "<"; break; } case "gt": { q.op = ">"; break; } case "lte": { q.op = "=<"; break; } case "gte": { q.op = ">="; break; } } tokens.Add(q); } }); if (tokens.Count > 0) { var sb = new StringBuilder(String.Format("SELECT [_docid] FROM [keys] WHERE [tablename] = '{0}' ", _name)); tokens.Each(x => { sb.Append(String.Format(" AND (([key] = {0}) AND ([val] {1} {2}))", x.keyParm, x.op, x.valParm)); }); using (SqlConnection conn = new SqlConnection(_d.cs)) { using (SqlCommand cmd = new SqlCommand(sb.ToString(), conn)) { tokens.Each(x => { cmd.Parameters.Add(new SqlParameter(x.keyParm, x.key)); cmd.Parameters.Add(new SqlParameter(x.valParm, x.val)); }); conn.Open(); List<string> ids = new List<string>(); using (SqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { ids.Add(rdr["_docid"].ToString()); } } ids.Each(x => result.Add(read(x, conn))); } } } return (result.ToArray()); }
public ParticleConfiguratior(List<Sprite> particles) { Particles = particles; ParticleProperties = new Dictionary<Sprite, IParticle>(); particles.Each(x => ParticleProperties.Add(x, LoadParticleProperties(x.name))); _cachedTotalWeight = particles.Sum(x => LoadParticleProperties(x.name).Weight); }
public FileChangePollingWatcher() { _timer.Elapsed += (sender, args) => { var actionList = new List<Action>(); lock (_locker) { _files.Each(file => file.Update(actionList.Add)); } actionList.Each(x => { try { x(); } catch (Exception) { // TODO do something here, or at least get visibility } }); if (_pollingCallback != null) _pollingCallback(); }; }
protected override void AwardBadges() { var badges = _mongoDb.GetCollection<Badge>(CollectionName).ToList(); var groupBy = _mongoDb.GetCollection<Purchase>("Purchases").ToList().GroupBy(x => x.Buyer); var purchaseDates = groupBy.Select(x => new { Dates = x.Where(y => y.Time != null).OrderBy(y => y.Time).Select(y => y.Time.Value.Date).Distinct(), x.First().Buyer }).ToList(); var purchases = new List<int>(); foreach (var t in purchaseDates) { var dateTimes = t.Dates.ToList(); var allDates = new List<DateTime>(); for (var date = dateTimes.First(); date <= dateTimes.Last(); date = date.AddDays(1)) allDates.Add(date); var buyArray = new bool[allDates.Count]; allDates.Each((d, i) => buyArray[i] = dateTimes.Contains(d)); var longest = 0; var temp = 0; foreach (var boughtThisDay in buyArray.Select(x => x ? 1 : 0)) { temp = (temp + boughtThisDay)*boughtThisDay; longest = Math.Max(temp, longest); } if(longest >= 3) purchases.Add(t.Buyer); } BadgeRepository.AddBadges(purchases, badges, _mongoDb, BadgeName); }
public void RunConfigurations() { var scanning = new List<Task<Registry>>(); // Recursive scanning while (_graph.QueuedRegistries.Any()) { var registry = _graph.QueuedRegistries.Dequeue(); _graph.Registries.Add(registry); scanning.AddRange(registry.Scanners.Where(x => x.HasAssemblies()).Select(x => x.ScanForTypes())); registry.Configure(_graph); } if (scanning.Any()) { Task.WaitAll(scanning.ToArray()); scanning.Each(x => _graph.ImportRegistry(x.Result)); } if (_graph.QueuedRegistries.Any()) { RunConfigurations(); } }
public IEnumerable<IPackageInfo> Load(IPackageLog log) { var list = new List<string> { AppDomain.CurrentDomain.SetupInformation.ApplicationBase }; string binPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; if (binPath.IsNotEmpty()) { if (Path.IsPathRooted(binPath)) { list.Add(binPath); } else { list.Add(AppDomain.CurrentDomain.SetupInformation.ApplicationBase.AppendPath(binPath)); } } list.Each(x => { log.Trace("Looking for assemblies marked with the [FubuModule] attribute in " + x); }); return list.SelectMany( x => AssembliesFromPath(x, assem => assem.GetCustomAttributes(typeof (FubuModuleAttribute), false).Any())) .Select(assem => new AssemblyPackageInfo(assem)); }
public static IEnumerable<Assembly> FindAssemblies(Func<Assembly, bool> filter, Action<string> onDirectoryFound = null) { if (onDirectoryFound == null) { onDirectoryFound = dir => { }; } var list = new List<string> {AppDomain.CurrentDomain.SetupInformation.ApplicationBase}; var binPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; if (binPath.IsNotEmpty()) { if (Path.IsPathRooted(binPath)) { list.Add(binPath); } else { list.Add(AppDomain.CurrentDomain.SetupInformation.ApplicationBase.AppendPath(binPath)); } } list.Each(x => onDirectoryFound(x)); return FindAssemblies(list, filter); }
public void Install(IWindsorContainer container, IConfigurationStore store) { var concreteTypes = BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(assembly => !assembly.GlobalAssemblyCache).ConcreteTypes(); IList<IModelMetadataConfiguration> configurations = new List<IModelMetadataConfiguration>(); concreteTypes.Where(type => typeof (IModelMetadataConfiguration).IsAssignableFrom(type)) .Each(type => { container.Register(Component.For(type).LifestyleTransient()); configurations.Add((IModelMetadataConfiguration) container.Resolve(type)); }); container.Register(Component.For<IModelMetadataRegistry>().ImplementedBy<ModelMetadataRegistry>().LifestyleSingleton()); var registry = container.Resolve<IModelMetadataRegistry>(); configurations.Each(configuration => registry.RegisterModelProperties(configuration.ModelType, configuration.Configurations)); IList<ModelValidatorProvider> validatorProviders = new List<ModelValidatorProvider>(ModelValidatorProviders.Providers); validatorProviders.Insert(0, new ExtendedModelValidatorProvider()); var compositeModelValidatorProvider = new CompositeModelValidatorProvider(validatorProviders.ToArray()); ModelMetadataProviders.Current = new ExtendedModelMetadataProvider(registry); ModelValidatorProviders.Providers.Clear(); ModelValidatorProviders.Providers.Add(compositeModelValidatorProvider); }
public static void DispatchCommands(List<ICommand> commands, HipchatMessage originalMessage) { if (!commands.Any()) BotsoHipchatHelpers.SendError("I don't understand that command<br/>Type <code>Botso commands</code> for a list of commands", originalMessage.RoomId); BotsoHipchatHelpers.SendError("<code><pre>" +originalMessage.Dump() + "<pre></code>", originalMessage.RoomId); commands.Each(x => x.Execute()); }
public void invoke_action_on_each_enumerable_value() { IList<int> list = new List<int>{42,42}; var result = new int[2]; list.Each((item, index) => result[index] = item * index); result[0].ShouldBe(0); result[1].ShouldBe(42); }
public virtual void ResetSlaves(List<RedisEndpoint> newSlaves) { slaves = (newSlaves ?? new List<RedisEndpoint>()).ToArray(); ReadOnlyHostsCount = slaves.Length; newSlaves.Each(x => allHosts.Add(x)); if (log.IsDebugEnabled) log.Debug("New Redis Slaves: " + string.Join(", ", slaves.Map(x => x.GetHostString()))); }
public virtual void Log(IRequest request, object requestDto, object response, TimeSpan requestDuration) { if (ShouldSkip(request, requestDto)) { return; } var requestType = requestDto?.GetType(); var entry = CreateEntry(request, requestDto, response, requestDuration, requestType); RequestLogFilter?.Invoke(request, entry); if (IgnoreFilter != null) { if (entry.RequestDto != null && IgnoreFilter(entry.RequestDto)) { entry.RequestDto = null; } if (entry.ResponseDto != null && IgnoreFilter(entry.ResponseDto)) { entry.ResponseDto = null; } if (entry.Session != null && IgnoreFilter(entry.Session)) { entry.Session = null; } if (entry.ErrorResponse != null && IgnoreFilter(entry.ErrorResponse)) { entry.ErrorResponse = null; } if (entry.ExceptionData != null) { List <object> keysToRemove = null; foreach (var key in entry.ExceptionData.Keys) { var val = entry.ExceptionData[key]; if (val != null && IgnoreFilter(val)) { keysToRemove ??= new List <object>(); keysToRemove.Add(key); } } keysToRemove?.Each(entry.ExceptionData.Remove); } } logEntries.Enqueue(entry); RequestLogEntry dummy; if (logEntries.Count > capacity) { logEntries.TryDequeue(out dummy); } }
public JsonResult SortContent(List<SectionContent> contents) { contents.Each(m => { var g = _sectionContentProviderService.Get(m.ID); g.Order = m.Order; _sectionContentProviderService.Update(g, new DataFilter(new List<string> { "Order" }).Where("ID", OperatorType.Equal, m.ID)); }); return Json(true); }
public JsonResult Sort(List<SectionGroup> groups) { groups.Each(m => { var g = _sectionGroupService.Get(m.ID); g.Order = m.Order; _sectionGroupService.Update(g); }); return Json(true); }
public JsonResult SortContent(List<SectionContent> contents) { var contentService = new SectionContentService(); contents.Each(m => { var g = contentService.Get(m.ID); g.Order = m.Order; contentService.Update(g); }); return Json(true); }
public void Given_Action_And_Strings_When_Calling_Each_Then_Action_Is_Invoked_For_Each_Element() { IEnumerable<int> items = new List<int> { 1, 2, 3 }; var visited = new List<int>(); Action<int> action = visited.Add; items.Each(action); visited.Should().ContainInOrder(items); visited.Should().HaveCount(items.Count()); }
public virtual void ResetMasters(List<RedisEndpoint> newMasters) { if (newMasters == null || newMasters.Count == 0) throw new Exception("Must provide at least 1 master"); masters = newMasters.ToArray(); ReadWriteHostsCount = masters.Length; newMasters.Each(x => allHosts.Add(x)); if (log.IsDebugEnabled) log.Debug("New Redis Masters: " + string.Join(", ", masters.Map(x => x.GetHostString()))); }
public RunStatsCollection CombineWithRunnersHistories(IEnumerable<RunStats> runners, List<string> skippedTests) { var path = _settings.ResultsOrderDataFilepath; if (string.IsNullOrEmpty(path)) return null; var runOrderData = new List<RunStats>(); var runHistoryLookup = new Dictionary<string, RunHistoryStats>(); try { var previousData = LoadPreviousRunOrder().ToList(); //Only copy over data from skippedTests // So if any are deleted they won't remain in there runOrderData.AddRange(previousData.Where(x => skippedTests.Contains(x.Name))); // //Copy over failed tests // runOrderData.AddRange(runners.Where(x => !x.IsSuccess)); //Copy over other cases... TODO This will not work for uncategorized... if (!runners.Any(x => x.Name == "all")) { var testDataForOthers = previousData.FirstOrDefault(x => x.Name == "all"); if (testDataForOthers != null) runOrderData.Add(testDataForOthers); } runOrderData.Each(x => --x.TestRunId); //Keep average stats: runHistoryLookup = previousData.ToDictionary(k => k.Name, v => (RunHistoryStats)v); } catch (Exception) { //Ignore this } //Add all new data runOrderData.AddRange(runners); // runOrderData.AddRange(runners.Where(x => x.IsSuccess)); //Keep average stats: runOrderData.Each(x => { if (runHistoryLookup.ContainsKey(x.Name)) { var history = runHistoryLookup[x.Name]; x.CopyHistoryStatsFrom(history); } if (x.IsCurrentRun) { x.AddDatapoint(x.RunTime, x.IsSuccess); } }); var runStatsCollection = RunStatsCollection.BuildCurrent(runOrderData.OrderBy(x => x.Name)); return runStatsCollection; }
public void ExtractSolutionLevelConfiguration(SolutionConfig config, Solution solution) { var specificDependencies = new List<Dependency>(); solution.Projects.Each(project => specificDependencies.AddRange(project.Dependencies.Where(x => !x.IsFloat()))); specificDependencies.Each(dependency => { solution.AddDependency(new Dependency(dependency.Name, dependency.Version, UpdateMode.Fixed)); dependency.Float(); }); }
public static FubuRegistry Pipelines(this FubuRegistry registry, Action<IPipelineExpression> cfg) { IList<ObjectDef> sources = new List<ObjectDef>(); IList<ObjectDef> policies = new List<ObjectDef>(); IPipelineExpression exp = new PipelineExpression(sources, policies); cfg(exp); sources.Each(source => registry.Services(x => x.AddService(typeof(IHandlerSource), source))); policies.Each(policy => registry.Services(x => x.AddService(typeof(IHandlerPolicy), policy))); return registry; }
public virtual void Dispose() { if (_memoryTarget != null) { LogManager.Flush(); var logs = new List<string>(_memoryTarget.Logs); // must clone otherwise the statement below this one will throw a 'collection modified' exception logs.Each(l => _helper.WriteLine(l)); _memoryTarget = null; } }
public void RegisterBundles(BundleCollection bundles) { var bundleProviderTypes = _typeFinder.FindClassesOfType<IBundleProvider>(ignoreInactivePlugins: true); var bundleProviders = new List<IBundleProvider>(); foreach (var providerType in bundleProviderTypes) { var provider = Activator.CreateInstance(providerType) as IBundleProvider; bundleProviders.Add(provider); } bundleProviders = bundleProviders.OrderByDescending(bp => bp.Priority).ToList(); bundleProviders.Each(bp => bp.RegisterBundles(bundles)); }
public void Configure(WebApiConfigurationBroadcaster configData) { var providerTypes = _typeFinder.FindClassesOfType<IWebApiConfigurationProvider>(ignoreInactivePlugins: true); var providers = new List<IWebApiConfigurationProvider>(); foreach (var providerType in providerTypes) { var provider = Activator.CreateInstance(providerType) as IWebApiConfigurationProvider; providers.Add(provider); } providers = providers.OrderByDescending(x => x.Priority).ToList(); providers.Each(x => x.Configure(configData)); }
public static void Serialize(this IClientSideObjectWriter objectWriter, string propertyName, IEffectContainer effects) { var effectSerialization = new List<string>(); var propertyAnimations = new List<PropertyAnimation>(); effects.Container.Each(e => { if (e is PropertyAnimation) { propertyAnimations.Add(e as PropertyAnimation); } else { effectSerialization.Add(e.Serialize()); } }); if (propertyAnimations.Count > 0) { propertyAnimations.Each(e => effects.Container.Remove(e)); var animatedProperties = new List<string>(); propertyAnimations.Each(e => animatedProperties.Add( e.AnimationType.ToString().ToLower(CultureInfo.InvariantCulture))); effectSerialization.Add( String.Format("{{name:'property',properties:['{0}']}}", String.Join("','", animatedProperties.ToArray()))); } objectWriter.Append("{0}:{{list:[{1}],openDuration:{2},closeDuration:{3}}}".FormatWith(propertyName, String.Join(",", effectSerialization.ToArray()), effects.OpenDuration, effects.CloseDuration)); }
protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) { var filterInfos = new List<FilterInfo> { base.GetFilters(controllerContext, actionDescriptor) }; filterInfos.AddRange(ServiceLocator.Current.GetAllInstances<IConfigureFilter>() .Select(m => m.Registry.GetMatched(controllerContext, actionDescriptor))); var filterInfo = new FilterInfo(); filterInfos.Each(m => { m.ActionFilters.Each(filterInfo.ActionFilters.Add); m.AuthorizationFilters.Each(filterInfo.AuthorizationFilters.Add); m.ExceptionFilters.Each(filterInfo.ExceptionFilters.Add); m.ResultFilters.Each(filterInfo.ResultFilters.Add); }); return filterInfo; }
public void RegisterRoutes(RouteCollection routes) { var routeProviderTypes = _typeFinder.FindClassesOfType<IRouteProvider>(ignoreInactivePlugins: true); var routeProviders = new List<IRouteProvider>(); foreach (var providerType in routeProviderTypes) { var provider = Activator.CreateInstance(providerType) as IRouteProvider; routeProviders.Add(provider); } routeProviders = routeProviders.OrderByDescending(rp => rp.Priority).ToList(); routeProviders.Each(rp => { rp.RegisterRoutes(routes); }); }
public void RegisterBundles(BundleCollection bundles) { var bundleProviderTypes = _typeFinder.FindClassesOfType<IBundleProvider>(); var bundleProviders = new List<IBundleProvider>(); foreach (var providerType in bundleProviderTypes) { if (!PluginManager.IsActivePluginAssembly(providerType.Assembly)) { continue; } var provider = Activator.CreateInstance(providerType) as IBundleProvider; bundleProviders.Add(provider); } bundleProviders = bundleProviders.OrderByDescending(bp => bp.Priority).ToList(); bundleProviders.Each(bp => bp.RegisterBundles(bundles)); }
public void RegisterRoutes(RouteCollection routes) { var routeProviderTypes = _typeFinder.FindClassesOfType<IRouteProvider>(); var routeProviders = new List<IRouteProvider>(); foreach (var providerType in routeProviderTypes) { if (!PluginManager.IsActivePluginAssembly(providerType.Assembly)) { continue; } var provider = Activator.CreateInstance(providerType) as IRouteProvider; routeProviders.Add(provider); } routeProviders = routeProviders.OrderByDescending(rp => rp.Priority).ToList(); routeProviders.Each(rp => rp.RegisterRoutes(routes)); }
public void Configure(WebApiConfigurationBroadcaster configData) { var providerTypes = _typeFinder.FindClassesOfType<IWebApiConfigurationProvider>(); var providers = new List<IWebApiConfigurationProvider>(); foreach (var providerType in providerTypes) { if (!PluginManager.IsActivePluginAssembly(providerType.Assembly)) { continue; } var provider = Activator.CreateInstance(providerType) as IWebApiConfigurationProvider; providers.Add(provider); } providers = providers.OrderByDescending(x => x.Priority).ToList(); providers.Each(x => x.Configure(configData)); }
public List <MetadataType> GetMetadataTypesForOperation(IRequest httpReq, Operation op) { var typeMetadata = HostContext.TryResolve <INativeTypesMetadata>(); var typesConfig = HostContext.AppHost.GetTypesConfigForMetadata(httpReq); var metadataTypes = typeMetadata != null ? typeMetadata.GetMetadataTypes(httpReq, typesConfig) : new MetadataTypesGenerator(this, typesConfig) .GetMetadataTypes(httpReq); var types = new List <MetadataType>(); var reqType = FindMetadataType(metadataTypes, op.RequestType); if (reqType != null) { types.Add(reqType); AddReferencedTypes(reqType, metadataTypes, types); } var resType = FindMetadataType(metadataTypes, op.ResponseType); if (resType != null) { types.Add(resType); AddReferencedTypes(resType, metadataTypes, types); } var generator = new CSharpGenerator(typesConfig); types.Each(x => { x.DisplayType = x.DisplayType ?? generator.Type(x.Name, x.GenericArgs); x.Properties.Each(p => p.DisplayType = p.DisplayType ?? generator.Type(p.Type, p.GenericArgs)); }); return(types); }
/// <summary> /// 递归添加子项 /// </summary> /// <param name="attrId"></param> /// <param name="pid"></param> private void AddSubValues(int attrId, int pid, int createBy, int modifyBy, string subValues) { List <dynamic> lt = ((string)subValues).ToString().Str2List <dynamic>(); var ValueService = HttpContext.RequestServices.GetService <Itattribute_valueRepository>(); if (lt != null && lt.Count != 0) { lt.Each(a => { int attrValId = a.attrValId; string val = a.val; CriticalMass.TagNode.Model.tattribute_value model = attrValId == 0 ? new CriticalMass.TagNode.Model.tattribute_value() : ValueService.GetModel(attrValId); if (model.id > 0 && ValueService.Exists(string.Format("val='{0}' and id<>'{1}' and attrid='{2}'", val, model.id, attrId))) { throw new Exception("属性值重复."); } else if (model.id == 0 && ValueService.Exists(string.Format("val='{0}' and attrid='{1}'", val, attrId))) { throw new Exception("属性值重复."); } model.val = val; model.attrId = attrId; model.Pid = pid; model.status = 1; if (attrValId == 0) { model.createBy = createBy; model.createTime = DateTime.Now; int ValId = ValueService.Insert(model); model.id = ValId; model.code = model.id.IntToHex();//生成值Code } else { model.modifyBy = modifyBy; model.modifyTime = DateTime.Now; } ValueService.Update(model); subValues = a.subValues.ToString(); AddSubValues(attrId, model.id, createBy, modifyBy, subValues); }); } }
private async Task AsyncDownloadWithProgress <TResponse>(IReturn <TResponse> request) { AsyncServiceClient.BufferSize = 100; var client = new JsonServiceClient(Constants.ServiceStackBaseHost); var progress = new List <string>(); //Note: total = -1 when 'Transfer-Encoding: chunked' //Available in ASP.NET or in HttpListener when downloading responses with known lengths: //E.g: Strings, Files, etc. client.OnDownloadProgress = (done, total) => progress.Add("{0}/{1} bytes downloaded".Fmt(done, total)); var response = await client.PostAsync(request); progress.Each(x => x.Print()); Assert.That(progress.Count, Is.GreaterThan(0)); Assert.That(progress.First(), Is.EqualTo("100/1160 bytes downloaded")); Assert.That(progress.Last(), Is.EqualTo("1160/1160 bytes downloaded")); }
public void WriteCommit(SqlStringBuilder sql, Database db = null) { db = db ?? Database; List <T> children = new List <T>(); foreach (T dao in this._values) { if (dao.HasNewValues) { dao.WriteCommit(sql, db); children.Add(dao); } } sql.Executed += (s, d) => { children.Each(dao => dao.OnAfterCommit(d)); AfterCommit?.Invoke(d, this); }; }
public void Dispose() { _trackedObjects.Each((trackedItem) => { //free disposable items _handlerFactory.Release(trackedItem); _logger.Value.DebugFormat("Releasing handler instance {0} of type {1}", trackedItem.GetHashCode(), trackedItem.GetType()); }); _trackedAsyncObjects.Each(trackedItem => { //free disposable items _asyncHandlerFactory.Release(trackedItem); _logger.Value.DebugFormat("Releasing async handler instance {0} of type {1}", trackedItem.GetHashCode(), trackedItem.GetType()); }); //clear our tracking _trackedObjects.Clear(); _trackedAsyncObjects.Clear(); }
private async Task allBuildingBlocksFrom(SnapshotProject snapshot, SnapshotContext snapshotContext) { //Expression profile needs to be added first var expressionProfiles = await mapSnapshotToBuildingBlocks <Model.ExpressionProfile, ExpressionProfile>(snapshot.ExpressionProfiles, snapshotContext); expressionProfiles.Each(snapshotContext.Project.AddBuildingBlock); //other can be loaded independently var buildingBlocks = new List <IPKSimBuildingBlock>(); buildingBlocks.AddRange(await mapSnapshotToBuildingBlocks <Model.Individual, Individual>(snapshot.Individuals, snapshotContext)); buildingBlocks.AddRange(await mapSnapshotToBuildingBlocks <Model.Compound, Compound>(snapshot.Compounds, snapshotContext)); buildingBlocks.AddRange(await mapSnapshotToBuildingBlocks <PKSimEvent, Event>(snapshot.Events, snapshotContext)); buildingBlocks.AddRange(await mapSnapshotToBuildingBlocks <Model.Formulation, Formulation>(snapshot.Formulations, snapshotContext)); buildingBlocks.AddRange(await mapSnapshotToBuildingBlocks <Model.Protocol, Protocol>(snapshot.Protocols, snapshotContext)); buildingBlocks.AddRange(await mapSnapshotToBuildingBlocks <Model.Population, Population>(snapshot.Populations, snapshotContext)); buildingBlocks.AddRange(await mapSnapshotToBuildingBlocks <Model.ObserverSet, ObserverSet>(snapshot.ObserverSets, snapshotContext)); buildingBlocks.Each(snapshotContext.Project.AddBuildingBlock); }
public void Dispose() { _trackedObjects.Each((trackedItem) => { //free disposable items _handlerFactorySync.Release(trackedItem); s_logger.LogDebug("Releasing handler instance {InstanceHashCode} of type {HandlerType}", trackedItem.GetHashCode(), trackedItem.GetType()); }); _trackedAsyncObjects.Each(trackedItem => { //free disposable items _asyncHandlerFactory.Release(trackedItem); s_logger.LogDebug("Releasing async handler instance {InstanceHashCode} of type {HandlerType}", trackedItem.GetHashCode(), trackedItem.GetType()); }); //clear our tracking _trackedObjects.Clear(); _trackedAsyncObjects.Clear(); }
public Session CreateSession(string database) { lock (_sessions) { if (_sessions.ContainsKey(database) && _sessions[database].Count > 0) { var s = _sessions[database][0]; _sessions[database].RemoveAt(0); return(s); } } var sx = new Session(this, database); if (null != _observerFactories && _observerFactories.Count > 0) { _observerFactories.Each(x => sx.Observers.Add(x(this))); } return(sx); }
public override void GlobalContext() { base.GlobalContext(); _savedItems = new List <HistoryItemMetaData> { new HistoryItemMetaData { Id = "1" }, new HistoryItemMetaData { Id = "2" } }; using (var session = _sessionFactory.OpenSession()) using (var transaction = session.BeginTransaction()) { _savedItems.Each(item => session.Save(item)); transaction.Commit(); } }
protected override void Context() { base.Context(); _startValues = new List <IMoleculeStartValue> { new MoleculeStartValue { Name = "M1", NegativeValuesAllowed = true }, new MoleculeStartValue { Name = "M2", NegativeValuesAllowed = false }, new MoleculeStartValue { Name = "M3", NegativeValuesAllowed = true }, new MoleculeStartValue { Name = "M4", NegativeValuesAllowed = false } }; _startValues.Each(_moleculeStartValueBuildingBlock.Add); }
/// <summary> /// Reject the promise with an exception. /// </summary> public void Reject(Exception ex) { Argument.NotNull(() => ex); if (CurState != PromiseState.Pending) { throw new ApplicationException("Attempt to reject a promise that is already in state: " + CurState + ", a promise can only be rejected when it is still in state: " + PromiseState.Pending); } rejectionException = ex; CurState = PromiseState.Rejected; if (errorHandlers != null) { errorHandlers.Each(handler => handler(rejectionException)); } ClearHandlers(); }
public IEnumerable <T> GetParamValues <T>() { var values = new List <T>(); var keys = new List <string>(); _values.Each(pair => { if (!pair.Key.ToLower().StartsWith("param")) { return; } keys.Add(pair.Key); }); keys.Sort(); keys.Each(_ => values.Add((T)GetValue(_, typeof(T)))); return(values); }
public void query_with_custom_parser() { using (var store = DocumentStore.For(_ => { _.Connection(ConnectionSource.ConnectionString); // IsBlue is a custom parser I used for testing this _.Linq.MethodCallParsers.Add(new IsBlue()); _.AutoCreateSchemaObjects = AutoCreate.All; })) { store.Advanced.Clean.CompletelyRemoveAll(); var targets = new List <ColorTarget>(); for (var i = 0; i < 25; i++) { targets.Add(new ColorTarget { Color = "Blue" }); targets.Add(new ColorTarget { Color = "Green" }); targets.Add(new ColorTarget { Color = "Red" }); } var count = targets.Where(x => x.IsBlue()).Count(); targets.Each(x => x.Id = Guid.NewGuid()); store.BulkInsert(targets.ToArray()); using (var session = store.QuerySession()) { session.Query <ColorTarget>().Where(x => x.IsBlue()).Count() .ShouldBe(count); } } }
private void WriteEvents(StringBuilder sb) { if (TypeDefinition.HasEvents) { Indent(sb); Indent(sb); sb.AppendLine("// Events"); Indent(sb); Indent(sb); sb.AppendLine("addEventListener(eventName: string, listener: any): void;"); Indent(sb); Indent(sb); sb.AppendLine("removeEventListener(eventName: string, listener: any): void;"); var distinctListenerSignatures = new List <string>(); TypeDefinition.Events.For((item, i, isLast) => { var eventListenerType = item.EventType.ToTypeScriptType(); var eventName = item.Name.ToLower(); var line = IndentValue + IndentValue + "addEventListener(eventName: \"{0}\", listener: {1}): void;".FormatWith(eventName, eventListenerType); if (!distinctListenerSignatures.Contains(line)) { distinctListenerSignatures.Add(line); } line = IndentValue + IndentValue + "removeEventListener(eventName: \"{0}\", listener: {1}): void;".FormatWith(eventName, eventListenerType); if (!distinctListenerSignatures.Contains(line)) { distinctListenerSignatures.Add(line); } line = IndentValue + IndentValue + "on{0}: (ev: {1}) => void;".FormatWith(eventName, eventListenerType); if (!distinctListenerSignatures.Contains(line)) { distinctListenerSignatures.Add(line); } }); distinctListenerSignatures.Each(item => { sb.AppendLine(item); }); sb.AppendLine(); } }
private void dropFunctions(string dropTargets) { var drops = new List <string>(); _runner.Execute(conn => { var cmd = conn.CreateCommand(dropTargets); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { drops.Add(reader.GetString(0)); } reader.Close(); } }); drops.Each(drop => { _runner.Execute(drop); }); }
/// <summary> /// Default constructor. Creates a model. /// </summary> public UserEditModel() { List <SysGroup> gr = SysGroup.GetFields("sysgroup_id, sysgroup_name", new Params() { OrderBy = "sysgroup_id" }); groups = new List <SysGroup>(); groups.Insert(0, new SysGroup()); gr.Each <SysGroup>((i, g) => { if (HttpContext.Current.User.IsMember(g.Id)) { groups.Add(g); } }); User = new SysUser(); Password = new SysUserPassword(); Groups = new SelectList(groups, "Id", "Name"); }
public BehaviorGraph BuildGraph() { var graph = new BehaviorGraph(_observer); // Service registrations from imports allServiceRegistrations().Each(x => x(graph.Services)); setupServices(graph); _conventions.Configure(graph); // Importing behavior chains from imports _imports.Each(x => x.ImportInto(graph)); _explicits.Configure(graph); _policies.Configure(graph); _systemPolicies.Configure(graph); return(graph); }
public IList <RouteBase> Bootstrap() { if (HttpContext.Current != null) { UrlContext.Live(); } _fubuFacility = new FubuMvcPackageFacility(); // TODO -- would be nice if this little monster also logged PackageRegistry.LoadPackages(x => { x.Facility(_fubuFacility); _packagingDirectives.Each(d => d(x)); x.Bootstrap(log => startApplication()); }); PackageRegistry.AssertNoFailures(); return(buildRoutes()); }
private static void SkrivUtStortingsrepresentanter(List <Stortingsrepresentant> stortingsrepresentanter) { Console.WriteLine("Representanter funnet: {0}", stortingsrepresentanter.Count); if (stortingsrepresentanter.Count > 0) { Console.WriteLine("-------------------------------------------------------------------------------"); Console.WriteLine("Representant:".PadRight(30) + "Fylke:".PadRight(15) + "Parti:".PadRight(25)); Console.WriteLine("-------------------------------------------------------------------------------"); stortingsrepresentanter.Each(r => Console.WriteLine((r.Etternavn + ", " + r.Fornavn).PadRight(30) + r.Fylke.PadRight(15) + r.Parti.PadRight(25)) ); } Console.WriteLine("-------------------------------------------------------------------------------"); }
/// <summary> /// /// </summary> /// <param name="network"></param> /// <param name="connections"></param> public void AddUpdateConnections(Network network, List <DeviceConnection> connections) { Guard.ArgumentNotNull(network, nameof(network)); Guard.ArgumentNotNull(connections, nameof(connections)); if (!connections.Any()) { return; } connections.Each(connection => { connection.NetworkId = network.Id; connection.ScenarioId = network.ScenarioId; }); var existingConnections = _deviceConnectionService.Where(m => m.ScenarioId == network.ScenarioId && m.Id == network.Id); _deviceConnectionService.AddUpdate(existingConnections, connections); }
public void EachWithIndexTest() { IList <Test> tests = new List <Test>() { new Test() { id = 0, name = "test1" }, new Test() { id = 1, name = "test2" } }; tests.Each((p_test, index) => { Assert.AreEqual(p_test.id, index); }); }
private void readCombination(Queue <string> tokens, string verb) { var assets = new List <string>() { verb }; while (tokens.Any() && tokens.Peek() != "as") { assets.Fill(tokens.Dequeue().ToDelimitedArray()); } if (!tokens.Any() || tokens.Dequeue() != "as" || !tokens.Any()) { throw new InvalidSyntaxException("Must supply a combination name"); } var comboName = tokens.Dequeue(); assets.Each(x => _registration.AddToCombination(comboName, x)); }
public static void Trigger(string signal) { lock (SignalRela) { if (SignalRela.ContainsKey(signal)) { lock (StaticCache.Cache) { List <string> cacheKeys = SignalRela[signal]; cacheKeys.Each(m => { if (StaticCache.Cache.ContainsKey(m)) { StaticCache.Cache[m] = null; StaticCache.Cache.Remove(m); } }); } } } }
/// <summary> /// 获取根模块资源,树表格数据 /// </summary> /// <param name="roleId">角色主键</param> /// <returns></returns> public string GetRootModuleAndIsChecked(string roleId) { _rModuleInfoList = GetModulesByRole(roleId); IList <SysModule> hasRoots = new List <SysModule>(); if (_rModuleInfoList.HasElement()) { hasRoots = _rModuleInfoList.Where(c => c.ParentId == "0").OrderBy(c => c.Sort).ToList(); } var rootList = _model.SysModule.Where(c => c.ParentId == "0" && c.IsDel == 0).OrderBy(c => c.Sort).ToList(); IList <TreeGridNode> nodeList = new List <TreeGridNode>(); rootList.Each(c => { TreeGridNode rootNode = new TreeGridNode(); rootNode.DbKey = c.ModuleId.ToString(); rootNode.ModuleName = c.ModuleName; rootNode.ControllerName = c.ControllerName; rootNode.ActionName = c.ActionName; rootNode.Icon = c.Icon; rootNode.BtnClass = c.BtnClass; rootNode.BtnId = c.BtnId; if (HasChildren(c.ModuleId)) { rootNode.state = "closed"; } if (hasRoots.HasElement()) { hasRoots.Each(r => { if (c.ModuleId == r.ModuleId) { rootNode.CheckState = true; } }); } nodeList.Add(rootNode); }); return(nodeList.ToJson()); }
private void RegistAssembly(Assembly assembly) { List <TypeInfo> controllers = new List <TypeInfo>(); Type PluginType = typeof(IPluginStartup); foreach (var typeInfo in assembly.DefinedTypes) { if (typeInfo.IsAbstract || typeInfo.IsInterface) { continue; } if (IsController(typeInfo) && !controllers.Contains(typeInfo)) { controllers.Add(typeInfo); } else if (PluginType.IsAssignableFrom(typeInfo.AsType())) { var plugin = (Activator.CreateInstance(typeInfo.AsType()) as IPluginStartup); plugin.CurrentPluginPath = Path.GetDirectoryName(assembly.Location); var binIndex = plugin.CurrentPluginPath.IndexOf("\\bin\\"); if (binIndex >= 0) { plugin.CurrentPluginPath = plugin.CurrentPluginPath.Substring(0, binIndex); } if (Services != null) { plugin.HostingEnvironment = HostingEnvironment; plugin.ConfigureServices(Services()); } OnLoading?.Invoke(plugin); } } if (controllers.Count > 0 && !ActionDescriptorProvider.PluginControllers.ContainsKey(assembly.FullName) && Services != null) { IServiceCollection services = Services(); controllers.Each(c => services.TryAddTransient(c.AsType())); ActionDescriptorProvider.PluginControllers.Add(assembly.FullName, controllers); } }
public void RunNow() { if (Pause || !buildRunner.Run()) { return; } var listener = GetListener.Invoke(config); var manager = new GilesAppDomainManager(); var runResults = new List <SessionResults>(); var testAssembliesToRun = config.TestAssemblies.ToList(); foreach (var filter in config.Filters.Where(f => f.Type == FilterType.Exclusive)) { testAssembliesToRun.RemoveAll(a => a.Contains(filter.NameDll)); } var watch = new Stopwatch(); watch.Start(); testAssembliesToRun.Each(assm => runResults.AddRange(manager.Run(assm, config.Filters.Where(f => f.Type != FilterType.Exclusive).Select(f => f.Name).ToList()))); watch.Stop(); Console.WriteLine("Test run completed in {0} seconds", watch.Elapsed.TotalSeconds); runResults.Each(result => { result.Messages.Each(m => listener.WriteLine(m, "Output")); result.TestResults.Each(listener.AddTestSummary); }); listener.DisplayResults(); LastRunResults.GilesTestListener = listener; }
public IEnumerable <IPackageInfo> Load(IPackageLog log) { var list = new List <string> { AppDomain.CurrentDomain.SetupInformation.ApplicationBase }; string binPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; if (binPath.IsNotEmpty()) { if (Path.IsPathRooted(binPath)) { list.Add(binPath); } else { list.Add(AppDomain.CurrentDomain.SetupInformation.ApplicationBase.AppendPath(binPath)); } } // This is a workaround for Self Hosted apps where the physical path is different than the AppDomain's original // path if (FubuMvcPackageFacility.PhysicalRootPath.IsNotEmpty()) { var path = FubuMvcPackageFacility.PhysicalRootPath.ToFullPath().AppendPath("bin"); if (Directory.Exists(path) && !list.Select(x => x.ToLower()).Contains(path.ToLower())) { list.Add(path); } } list.Each(x => { Console.WriteLine("Looking for *.Docs assemblies in directory " + x); }); return(LoadPackages(list)); }
public static void RunUnitTestGroupInFile(FileInfo file, string testGroupName, Dictionary <UnitTestMethod, Exception> failed, List <UnitTestMethod> succeeded) { Assembly testAssembly = null; try { testAssembly = Assembly.LoadFile(file.FullName); } catch (Exception ex) { OutLineFormat("Failed to load assembly from file {0}: {1}", ConsoleColor.Yellow, file.FullName, ex.Message); return; } OutLineFormat("Loaded assembly {0}", ConsoleColor.Green, testAssembly.FullName); List <UnitTestMethod> testMethods = UnitTestMethod.FromAssembly(testAssembly).Where(unitTestMethod => { if (unitTestMethod.Method.HasCustomAttributeOfType <TestGroupAttribute>(out TestGroupAttribute testGroupAttribute)) { return(testGroupAttribute.Groups.Contains(testGroupName)); } return(false); }).ToList(); OutLineFormat("Found ({0}) tests in group ({1}) in assembly ({2})", ConsoleColor.Blue, testMethods.Count, testGroupName, testAssembly.FullName); testMethods.Each(testMethod => { if (testMethod.TryInvoke(ex => { OutLineFormat("{0} failed: {1}", testMethod.Description, ex.Message); failed.Add(testMethod, ex); })) { succeeded.Add(testMethod); } ; }); }
public static void RunUnitTestGroupsInFolder(string testDirectoryName, string searchPattern, string testGroupName) { DirectoryInfo directory = new DirectoryInfo(testDirectoryName); FileInfo[] files = directory.GetFiles(searchPattern); if (files.Length > 0) { OutLine($"There are {files.Length} files matching search pattern {searchPattern}", ConsoleColor.Green); Thread.Sleep(3000); List <UnitTestMethod> succeeded = new List <UnitTestMethod>(); Dictionary <UnitTestMethod, Exception> failed = new Dictionary <UnitTestMethod, Exception>(); foreach (FileInfo file in GetDllsAndExes(files)) { RunUnitTestGroupInFile(file, testGroupName, failed, succeeded); } if (succeeded.Count > 0) { OutLineFormat("{0} tests passed", ConsoleColor.Green, succeeded.Count); succeeded.Each(unitTest => OutLineFormat("{0} passed", ConsoleColor.Green, unitTest.Description)); } if (failed.Count > 0) { StringBuilder failures = new StringBuilder(); failed.Keys.Each(unitTest => failures.AppendLine($"{unitTest.Description}: {failed[unitTest].Message}\r\n{failed[unitTest].StackTrace}\r\n")); OutLineFormat("There were {0} failures", failed.Count); OutLine(failures.ToString(), ConsoleColor.Magenta); Exit(1); } else { Exit(0); } } OutLineFormat("No files found in ({0}) for search pattern ({1})", testDirectoryName, searchPattern); Exit(1); }