internal static T GetService <T>(string name) where T : class { if (!serviceCache.Any(x => x.Key.Equals(name))) { lock (lockObj) { if (!serviceCache.Any(x => x.Key.Equals(name))) { //IOC服务比较特殊,其他服务是基于它来创建的,所以不和其他服务放在InitialContext里创建。 //todo:待优化 if (name.Equals("Unity")) { dynamic unityService = new UnityIOCAdapter(); serviceCache.Add(name, unityService); return((T)unityService); } var iocService = serviceCache.Single(x => x.Key == "Unity").Value; var ctx = new InitialContext(iocService); var service = ctx.LookupSerive <T>(name); if (service != null) { serviceCache.Add(name, service); return(service); } } } } return((T)serviceCache.Single(x => x.Key.Equals(name)).Value); }
public static MethodInfo ThenSingleMethodShouldExist(this IDictionary <Type, MethodInfo> input, string withName) { input.Count.Should().Be(1); var method = input.Single().Value; method.Name.Should().Be(withName); return(input.Single().Value); }
public static AzureHDInsightDefaultStorageAccount GetDefaultStorageAccountDetails( string version, IDictionary <string, string> coreSiteConfiguration, IDictionary <string, string> clusterIdentityConfiguration = null) { string key = version.Equals("2.1") ? Constants.ClusterConfiguration.DefaultStorageAccountNameKeyOld : Constants.ClusterConfiguration.DefaultStorageAccountNameKey; string defaultFSUrl; const string AdlPrefix = "adl://"; const string WasbPrefix = "wasb://"; if (coreSiteConfiguration.TryGetValue(key, out defaultFSUrl)) { if (defaultFSUrl.StartsWith(AdlPrefix)) { string appId, tenantId, certContents, certPassword, resourceUri, storageRootPath; clusterIdentityConfiguration = clusterIdentityConfiguration ?? new Dictionary <string, string> { }; clusterIdentityConfiguration.TryGetValue("clusterIdentity.applicationId", out appId); clusterIdentityConfiguration.TryGetValue("clusterIdentity.aadTenantId", out tenantId); clusterIdentityConfiguration.TryGetValue("clusterIdentity.certificate", out certContents); clusterIdentityConfiguration.TryGetValue("clusterIdentity.certificatePassword", out certPassword); clusterIdentityConfiguration.TryGetValue("clusterIdentity.resourceUri", out resourceUri); storageRootPath = coreSiteConfiguration.Single(k => k.Key.StartsWith("dfs.adls.") && k.Key.EndsWith(".mountpoint")).Value; return(new AzureHDInsightDataLakeDefaultStorageAccount ( storageAccountName: coreSiteConfiguration.Single(k => k.Key.StartsWith("dfs.adls.") && k.Key.EndsWith(".hostname")).Value, storageRootPath: storageRootPath, applicationId: appId, tenantId: tenantId, certificateContents: Convert.FromBase64String(certContents ?? ""), certificatePassword: certPassword, resourceUri: resourceUri )); } else if (defaultFSUrl.StartsWith(WasbPrefix)) { string[] accountAndContainer = defaultFSUrl.Substring(WasbPrefix.Length).Split('@'); return(new AzureHDInsightWASBDefaultStorageAccount ( storageContainerName: accountAndContainer[0], storageAccountName: accountAndContainer[1], storageAccountKey: coreSiteConfiguration[Constants.ClusterConfiguration.StorageAccountKeyPrefix + accountAndContainer[1]] )); } else { return(null); } } return(null); }
public GrayscaleStandardImage SvPikeHat(StandardImage image, IDictionary <Point, int> svPikes) { var grayImage = image.ConvertToGrayScaleStandardImage(); var saturationCutoff = 0; var brightnessCutoff = 0; if (svPikes.Count == 1) { saturationCutoff = svPikes.Single().Key.X + 30; brightnessCutoff = svPikes.Single().Key.Y - 30; } else if (svPikes.Count == 2) { saturationCutoff = (svPikes.First().Key.X + svPikes.Last().Key.X) / 2; brightnessCutoff = (svPikes.First().Key.Y + svPikes.Last().Key.Y) / 2; } else { var pikesList = svPikes.ToList(); pikesList.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value)); var pike1 = pikesList[0]; var pike2 = pikesList[1]; saturationCutoff = (pike1.Key.X + pike2.Key.X) / 2; brightnessCutoff = (pike1.Key.Y + pike2.Key.Y) / 2; } for (int i = 0; i < image.Width; i++) { for (int j = 0; j < image.Height; j++) { var myRgb = new Rgb { R = image.R[i, j], G = image.G[i, j], B = image.B[i, j] }; var hsl = myRgb.To <Hsv>(); var saturation = hsl.S * 100; if (saturation > 13 && saturation < 40) { grayImage.C[i, j] = 255; } else { grayImage.C[i, j] = 0; } //var saturation = hsl.S*100; //var brightness = hsl.V*100; //if (saturation < saturationCutoff && brightness > brightnessCutoff) // grayImage.C[i, j] = 255; //else // grayImage.C[i, j] = 0; } } return(grayImage); }
public Document(DocumentTable table, string document, IDictionary <string, object> projections) { Table = table; DocumentAsString = document; idColumn = projections.Single(x => x.Key == table.IdColumn.Name); documentColumn = projections.Single(x => x.Key == table.DocumentColumn.Name); etagColumn = projections.Single(x => x.Key == table.EtagColumn.Name); this.projections = projections.Where(x => !(x.Key is SystemColumn)) .Select(x => new Projection(x.Key, x.Value)) .ToList(); }
public void SelectIdCaseInsensitive() { ISelectExpandWrapper[] result = SimpleClass.CreateQuery().OData().SelectExpand("id").ToArray(); IDictionary <string, object> metadata = result[0].ToDictionary(); Assert.Equal(1, metadata.Count); Assert.Equal("Id", metadata.Single().Key, StringComparer.Ordinal); Assert.IsType <int>(metadata.Single().Value); Assert.Equal(1, metadata.Single().Value); }
public Document(DocumentTable table, string document, IDictionary<string, object> projections) { Table = table; DocumentAsString = document; idColumn = projections.Single(x => x.Key == table.IdColumn.Name); documentColumn = projections.Single(x => x.Key == table.DocumentColumn.Name); etagColumn = projections.Single(x => x.Key == table.EtagColumn.Name); this.projections = projections.Where(x => !(x.Key is SystemColumn)) .Select(x => new Projection(x.Key, x.Value)) .ToList(); }
public void SelectDataMember() { ISelectExpandWrapper[] result = SimpleClassDataContract.CreateQuery().OData().SelectExpand("nameChanged").ToArray(); IDictionary <string, object> metadata = result[0].ToDictionary(); // Expect Name to be selected Assert.Equal(1, metadata.Count); Assert.Equal("nameChanged", metadata.Single().Key); Assert.Equal("n1", metadata.Single().Value); Assert.IsType <string>(metadata.Single().Value); }
private void Toast_Failed(Windows.UI.Notifications.ToastNotification sender, ToastFailedEventArgs args) { #if WINDOWS_UWP var id = sender.Tag; #else var id = _toasts.Single(x => x.Value == sender).Key; #endif _eventResult.Add(id, new NotificationResult() { Action = NotificationAction.Failed }); _resetEvents[id].Set(); }
/// <inheritdoc /> public virtual ISerializer GetSerializer(uint?version = null) { if (!serializers.Any()) { throw new SchemaDefinitionException($"This protocol instance (message protocol version `{Name}`) is not configured with contract assembly."); } if (!ProtocolDefinition.SupportedVersions.Any()) { return(serializers.Single().Value); } if (!version.HasValue) { throw new SchemaDefinitionException($"This protocol instance (message protocol version `{Name}`) requires specific version value."); } var serializerVersion = version.Value > 0u ? version.Value : ProtocolDefinition.SupportedVersions.Max(); if (serializers.TryGetValue(serializerVersion, out var versionSerializer)) { return(versionSerializer); } throw new SchemaDefinitionException($"This protocol instance (message protocol version `{Name}`) does not support `v{version.Value}`."); }
public void Part2() { Console.WriteLine("Recursive Circus P.2"); var leger = GetLeger(_input).ToList(); var programsWithChildren = leger.Where(l => l.Children.Any()); string bottomProgram = GetBottomProgramName( programsWithChildren, new List <string> { programsWithChildren.First().Name }, new List <string>() ); IDictionary <string, int> towers = leger.First(l => l.Name == bottomProgram).Children .ToDictionary( child => child, child => GetTowerTotalWeight(leger, child) ); var wrongTower = towers.Single(t => towers.Count(s => t.Value == s.Value) == 1); int rightWeight = towers.First(t => t.Key != wrongTower.Key).Value; int correctionAmount = rightWeight - wrongTower.Value; // Scan tower for wrong node and correct with correctionAmount var wrongProgram = FindWrongProgram(leger, wrongTower.Key); Console.WriteLine($"Node {wrongProgram.Name} is {wrongProgram.Weight} but should be {wrongProgram.Weight + correctionAmount}"); }
/// <summary> /// Get runtime types lookup object. /// </summary> public ISerializerCache GetSerializerCache(uint?version = null) { if (!serializerCaches.Any()) { throw new Exception($"This protocol instance (message protocol version `{Name}`) is not configured with contract assembly."); } if (!ProtocolDefinition.SupportedVersions.Any()) { return(serializerCaches.Single().Value); } if (!version.HasValue) { throw new Exception($"This protocol instance (message protocol version `{Name}`) requires specific version value."); } var serializerVersion = version.Value > 0u ? version.Value : ProtocolDefinition.SupportedVersions.Max(); ISerializerCache versioningSerializerCache; if (serializerCaches.TryGetValue(serializerVersion, out versioningSerializerCache)) { return(versioningSerializerCache); } throw new ArgumentException($"This protocol instance (message protocol version `{Name}`) does not support `v{version.Value}`.", nameof(version)); }
protected void CalculateAndAddToHistory() { var selectedOperator = _operatorMapping.Single(o => o.Key == CurrentCalculation.Operator).Value; try { var result = Calculator.Calculate(CurrentCalculation.FirstNumber, CurrentCalculation.SecondNumber, selectedOperator); CurrentCalculation.Result = result; CurrentCalculation.CalculationProcess = $"{CurrentCalculation.FirstNumber} {CurrentCalculation.Operator} {CurrentCalculation.SecondNumber} = {CurrentCalculation.Result}"; } catch (DivideByZeroException exception) { AddError(exception); } catch (ArgumentOutOfRangeException exception) { AddError(exception); } CalculationItems.Add(CurrentCalculation); CurrentCalculation = new Calculation { Operator = _operatorMapping.Keys.First(), CalculationID = CalculationID++ }; StateHasChanged(); }
private static void CalculateAndApplyExpiredFundsToFundsOut( IDictionary <CalendarPeriod, decimal> fundsOut, IDictionary <CalendarPeriod, decimal> expired, IDictionary <CalendarPeriod, decimal> fundsIn, int expiryPeriod) { if (expired == null) { return; } foreach (var expiredAmount in expired) { var levyPeriodForExpiry = new DateTime(expiredAmount.Key.Year, expiredAmount.Key.Month, 1).AddMonths(expiryPeriod * -1); var amount = fundsIn.Single(c => c.Key.Equals(new CalendarPeriod(levyPeriodForExpiry.Year, levyPeriodForExpiry.Month))).Value - expiredAmount.Value; var fundsOutAvailable = fundsOut .Where(c => c.Value > 0 && c.Key <= expiredAmount.Key) .ToList(); foreach (var fundOut in fundsOutAvailable) { if (fundOut.Value >= amount) { fundsOut[fundOut.Key] = fundOut.Value - amount; break; } amount = amount - fundOut.Value; fundsOut[fundOut.Key] = 0; } } }
/// <summary> /// PTV metrics. /// </summary> private static void CreatePTVMetrics(XmlWriter writer, PlanSetup plan, IDictionary <string, ModelStructure> structureMatches) { var structure = plan.StructureSet.Structures.Single(st => st.Id == structureMatches.Single(x => x.Value.ModelId == "PTV").Key); writer.WriteStartElement("Structure"); writer.WriteAttributeString("Id", structure.Id); writer.WriteAttributeString("Model_Id", structureMatches[structure.Id].ModelId); // Volume at dose metrics var metrics = new List <VolumeAtDoseMetric> { new VolumeAtDoseMetric(new DoseValue(95.0, DoseValue.DoseUnit.Percent), 99.0, MetricType.Lower), new VolumeAtDoseMetric(new DoseValue(100.0, DoseValue.DoseUnit.Percent), 98.0, MetricType.Lower), new VolumeAtDoseMetric(new DoseValue(105.0, DoseValue.DoseUnit.Percent), 15.0, MetricType.Upper), new VolumeAtDoseMetric(new DoseValue(110.0, DoseValue.DoseUnit.Percent), 2.0, MetricType.Upper) }; CreateVolumeAtDoseMetrics(writer, plan, structure, metrics); // Dose at volume metrics var metrics2 = new List <DoseAtVolumeMetric> { new DoseAtVolumeMetric(99.0, 95.0, MetricType.Lower) }; CreateDoseAtVolumeMetrics(writer, plan, structure, metrics2); writer.WriteEndElement(); }
public static ICommandLineOptions ParseCommandLineOptions(string[] args) { if (args.Length == 0) { return(ShowHelp()); } var inputCommand = args[0]; try { var option = s_possibleCommands.Single(c => c.Key.StartsWith(inputCommand, StringComparison.OrdinalIgnoreCase)); var output = option.Value.Parse(args.Skip(1)); if (output.Command == AppCommands.Help) { ShowHelp(inputCommand); return(CommonCommands.Exit); } return(output); } catch (FormatException) { return(ShowHelp(inputCommand, true)); } catch (InvalidOperationException) { return(ShowHelp(inputCommand, true)); } }
private void AxLEDeviceAdvertised(object sender, IDevice device) { Console.WriteLine($"ADVERTISED: {device.Name} <{device.MacAddress}> {device.Rssi} ({RssiFilter})"); if (RssiFilter != 0 && device.Rssi < RssiFilter) { return; } if (!_lastSeen.ContainsKey(device.Id)) { Console.WriteLine($"...New!"); if (_devices.Any(d => d.Value.Id == device.Id)) { Console.WriteLine($"...Found"); var devicePair = _devices.Single(d => d.Value.Id == device.Id); DeviceFound?.Invoke(this, devicePair.Key); } else { Console.WriteLine($"...Discovered"); ProcessDeviceDiscovered(device); } } _lastSeen[device.Id] = DateTime.Now; }
internal XLPicture(IXLWorksheet worksheet, Stream stream) : this(worksheet) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } this.ImageStream = new MemoryStream(); { stream.Position = 0; stream.CopyTo(ImageStream); ImageStream.Seek(0, SeekOrigin.Begin); using (var bitmap = new Bitmap(ImageStream)) { if (FormatMap.Values.Select(f => f.Guid).Contains(bitmap.RawFormat.Guid)) { this.Format = FormatMap.Single(f => f.Value.Guid.Equals(bitmap.RawFormat.Guid)).Key; } DeduceDimensionsFromBitmap(bitmap); } ImageStream.Seek(0, SeekOrigin.Begin); } }
public void Set(TimingTypes type) { var keyValue = timingStrategyTypes.Single(k => k.Key.Type == type); timing = timingFactory(keyValue.Value); timing.ThreadExecutionInterval = 1; }
static void WriteNext(Stream stream, object obj) { Type type = obj.GetType(); int field = typeLookup.Single(pair => pair.Value == type).Key; Serializer.NonGeneric.SerializeWithLengthPrefix(stream, obj, PrefixStyle.Base128, field); }
public void Should_use_the_supplied_extension_name_as_the_key_for_the_entry() { Assert.That( _actualExtensionEntities.Single() .Key, Is.EqualTo(TestExtension)); }
private void MoveTetrominosDownIfNeeded() { _timeToNextTetrominoDropInSeconds -= Time.deltaTime; if (_timeToNextTetrominoDropInSeconds > 0.00f) { return; } var results = _field.TryMoveMultipleTetrominos(ActiveTetrominos(), Direction.Down); // Each result with a value "false" indicates a tetromino that could not drop down. This means that the tetromino has landed on the bottom. // Time to destroy these tetromino (removing palyer control). foreach (var result in results.Where(x => x.Value == false)) { var landedTetromino = result.Key; foreach (var block in landedTetromino.Blocks) { block.IsSettled = true; } var playerControllingTetromino = _activeTetrominoByPlayer.Single(x => x.Value == landedTetromino).Key; _activeTetrominoByPlayer[playerControllingTetromino] = null; Destroy(landedTetromino); } ResetTetrominoDropCounter(); }
public async Task <UserInfo> Login(User user, string password) { //判断用户名与密码 var loginUser = _databaseService.Login(user.UserName, password); if (loginUser != null) { if (_users.Any(x => x.Value.UserName == user.UserName))//如果重复登录的话,触发"掉线" { var connectionId = _users.Single(x => x.Value.UserName == user.UserName).Value.ConnectionId; //await Container.Resolve<IHubContext<GwentHub>>().Clients.Client(connectionId).SendAsync("RepeatLogin"); await _hub.Clients.Client(connectionId).SendAsync("RepeatLogin"); await Disconnect(connectionId); } if (_users.ContainsKey(user.ConnectionId)) { await Disconnect(user.ConnectionId); } user.PlayerName = loginUser.PlayerName; user.Decks = loginUser.Decks; _users.Add(user.ConnectionId, user); InovkeUserChanged(); } return(loginUser); }
public void Import(IDictionary <string, IDatabaseTableProcessor> processors = null) { foreach (var shapefile in _files.Value) { var tableName = shapefile.Name; using (var processor = GetPostProcessor(processors, tableName)) { processor.PreProcess(); var geometryImporter = _shapefileImportStrategies.Single(i => i.Key == shapefile.Extension).Value; // HACK: trying to convert to something i like var needsConversion = shapefile.Name.IndexOf("STREETS_LOAD", StringComparison.OrdinalIgnoreCase) >= 0; if (false) { geometryImporter.ImportShape(shapefile, _connection, "26915"); } else { geometryImporter.ImportShape(shapefile, _connection, Srid); } processor.Process(); processor.PostProcess(); } } }
/// <summary> /// Internal. Parses Object Replication Policy ID from Rule ID and sets the Policy ID for source blobs. /// </summary> /// <param name="OrIds"> /// Unparsed Object Replication headers. /// For source blobs, the dictionary will contain keys that contain the policy id and rule id separated /// by a underscore (e.g. policyId_ruleId). The value of these keys will be the replication status (e.g. Complete, Failed). /// For destination blobs, the dictionary will contain one entry where the key will be "policy-id" /// and the value will be the destination policy id. No parsing will be required for this. /// </param> /// <returns> /// If the blob has object replication policy(s) applied and is the source blob, this method will return a /// List of <see cref="ObjectReplicationPolicy"/>, which contains the Policy ID and the respective /// rule(s) and replication status(s) for each policy. /// If the blob has object replication policy applied and is the destination blob, /// this method will return default as the policy id should be set in ObjectReplicationDestinationPolicyId /// (e.g. <see cref="BlobProperties.ObjectReplicationDestinationPolicyId"/>,<see cref="BlobDownloadDetails.ObjectReplicationDestinationPolicyId"/>). /// </returns> internal static IList <ObjectReplicationPolicy> ParseObjectReplicationIds(this IDictionary <string, string> OrIds) { try { // If the dictionary contains a key with policy id, we are not required to do any parsing since // the policy id should already be stored in the ObjectReplicationDestinationPolicyId. KeyValuePair <string, string> destPolicy = OrIds.Single(id => (id.Key == "policy-id")); return(default);
public static ISimpleTree <T> ToSimpleTree <T>(this IDictionary <T, T> pairs) where T : class { var top = pairs.Single(x => x.Value == null).Key; var topNode = new SimpleTree <T>(top); Add(topNode, pairs); return(topNode); }
public async Task VerifyQueryIsCorrectlyParsed() { var values = new Dictionary <string, string> { { "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI", Environment.GetEnvironmentVariable("VSTSTESTACCESSOR2015_TEAMPROJECTCOLLECTIONURI") }, { "SYSTEM_TEAMPROJECT", Environment.GetEnvironmentVariable("VSTSTESTACCESSOR2015_TEAMPROJECT") } }; VstsEnvironmentVariables variables = VstsEnvironmentVariables.Create(values); IDictionary <string, string> configValues = await this.sut.GetTestConfigurationPropertiesAsync(variables, "Windows 8"); Assert.AreNotEqual(configValues, "The configuration values dictionary must not be null"); Assert.AreEqual(1, configValues.Count, "Unexpected number of configuration values"); Assert.AreEqual("Operating System", configValues.Single().Key, "Unexpected value key"); Assert.AreEqual("Windows 8", configValues.Single().Value, "Unexpected configuration value"); }
public void MarkVacant(VehicleBase vehicle) { var matched = _vehicleToSlotMap.Single(x => x.Value == vehicle); if (_vehicleToSlotMap.ContainsKey(matched.Key)) { _vehicleToSlotMap.Remove(matched.Key); } }
private static void WriteNext(Stream stream, object obj) { Type type = obj.GetType(); int field = typeLookup.Single(pair => pair.Value == type).Key; #pragma warning disable CS0618 Serializer.NonGeneric.SerializeWithLengthPrefix(stream, obj, PrefixStyle.Base128, field); #pragma warning restore CS0618 }
public async Task WriteAsync(IDictionary <string, object> changes, CancellationToken cancellationToken = default) { var(id, entry) = changes.Single(); var filter = CreateIdListFilter(new string[] { id }); UpdateDefinition <StoredState> update = CreateUpdateDefinition(entry); await Collection.UpdateOneAsync(filter, update, new UpdateOptions { IsUpsert = true }); }
private ISuiteProvider Load( Type suiteType, IDictionary <Type, ITypeLoader> loaderDictionary, ICollection <TypedLazy <ILazyBootstrap> > assemblySetups, IIdentity assemblyIdentity) { var suiteTypeLoader = loaderDictionary.Single(x => x.Key.IsAssignableFrom(suiteType)).Value; return(suiteTypeLoader.Load(suiteType, assemblySetups, assemblyIdentity)); }
public async Task Invoke(IDictionary<string, object> environment) { //IOwinContext owinContext = new OwinContext(environment); HttpContextBase httpContext = (HttpContextBase)environment.Single(context => context.Key == "System.Web.HttpContextBase").Value; var url = httpContext.Request.Url; if (url.AbsoluteUri.Contains("/Contact")) { httpContext.Response.Redirect("/"); } else { await this._next.Invoke(environment); } }
private static object CheckForExistingProperty(object item2, PropertyInfo fi, IDictionary<string, object> result) { var newValue = fi.GetValue(item2, null); if (result.All(x => x.Key != fi.Name)) { return newValue; } var foundProperty = result.Single(x => x.Key == fi.Name); if (!foundProperty.Value.Equals(newValue)) { throw new Exception("Merging Property with different values - " + fi.Name); } return newValue; }
public override Task<object> ExecuteAsync(HttpControllerContext controllerContext, IDictionary<string, object> arguments, CancellationToken cancellationToken) { return TaskHelpers.RunSynchronously<object>(() => { // create the changeset object entity = arguments.Single().Value; // there is only a single parameter - the entity being submitted ChangeSetEntry[] changeSetEntries = new ChangeSetEntry[] { new ChangeSetEntry { Id = 1, ActionDescriptor = _updateAction, Entity = entity, Operation = _updateAction.ChangeOperation } }; ChangeSet changeSet = new ChangeSet(changeSetEntries); changeSet.SetEntityAssociations(); DataController controller = (DataController)controllerContext.Controller; if (!controller.Submit(changeSet) && controller.ActionContext.Response != null) { // If the submit failed due to an authorization failure, // return the authorization response directly return controller.ActionContext.Response; } // return the entity entity = changeSet.ChangeSetEntries[0].Entity; // REVIEW does JSON make sense here? return new HttpResponseMessage() { Content = new ObjectContent(_updateAction.EntityType, entity, new JsonMediaTypeFormatter()) }; }, cancellationToken); }
/// <summary> /// Builds the response. /// </summary> /// <param name="content">The content.</param> /// <returns></returns> protected IDictionary<string, object> BuildResponse(object serializableObject, IDictionary<string, object> serializedContent) { // create body of the response IDictionary<string, object> response = new Dictionary<string, object>(); response.Add("timestamp", DateTime.UtcNow); // add serialization headers to the response foreach (var header in SerializedHeader) response.Add(header.Key, header.Value); // check for regular collection if (serializableObject is ICollection) response.Add("count", ((ICollection)serializableObject).Count); // check if only one object was returned, if it was then we can rename the root if (serializedContent.Count == 1) { var rootObj = serializedContent.Single(); var rootName = rootObj.Key; if (!String.IsNullOrWhiteSpace(SerializedRootName)) rootName = SerializedRootName; response.Add(rootName, rootObj.Value); } else foreach (var item in serializedContent) response.Add(item); return response; }
private ISuiteProvider Load( Type suiteType, IDictionary<Type, ITypeLoader> loaderDictionary, ICollection<TypedLazy<ILazyBootstrap>> assemblySetups, IIdentity assemblyIdentity) { var suiteTypeLoader = loaderDictionary.Single(x => x.Key.IsAssignableFrom(suiteType)).Value; return suiteTypeLoader.Load(suiteType, assemblySetups, assemblyIdentity); }
private ISuiteProvider Load( Type suiteType, IDictionary<Type, ITypeLoader> loaderDictionary, IDictionary<Type, Lazy<IAssemblySetup>> assemblySetups, IIdentity assemblyIdentity) { // TODO: Move selection to AssemblyExplorer var suiteTypeLoader = loaderDictionary.Single(x => x.Key == suiteType.GetAttribute<SuiteAttributeBase>().AssertNotNull().GetType()).Value; return suiteTypeLoader.Load(suiteType, assemblySetups, assemblyIdentity); }
private void RegisterInParents(DeviceInfo device, IDictionary<string, IPeripheral> parents) { foreach(var parentName in device.Connections.Keys) { //TODO: nongeneric version var parent = parents.Single(x => x.Key == parentName).Value; var connections = device.Connections[parentName]; var ifaces = parent.GetType().GetInterfaces().Where(x => IsSpecializationOfRawGeneric(typeof(IPeripheralRegister<,>), x)).ToList(); var ifaceCandidates = ifaces.Where(x => x.GetGenericArguments()[0].IsAssignableFrom(device.Peripheral.GetType())).ToList(); foreach(var connection in connections) { IRegistrationPoint regPoint = null; Type formalType = null; if(connection.ContainsKey(TYPE_NODE)) { var name = (string)connection[TYPE_NODE]; formalType = GetDeviceTypeFromName(name); } Type foundIface = null; foreach(var iface in ifaceCandidates) { var iRegPoint = iface.GetGenericArguments()[1]; Type objType; if(formalType != null && iRegPoint.IsAssignableFrom(formalType)) { objType = formalType; } else { objType = iRegPoint; } object regPointObject; if(!TryInitializeCtor(objType, connection, out regPointObject)) { if(connection.Keys.Any() || !TryHandleSingleton(objType, out regPointObject)) { continue; } } regPoint = (IRegistrationPoint)regPointObject; foundIface = iface; break; //is a construable type } if(foundIface == null) { // let's try attachment through the AttachTo mechanism FailDevice(device.Name, "connection to " + parentName); } else { Dynamic.InvokeMemberAction(parent, "Register", new object[] { device.Peripheral, regPoint } ); } } } }