public MappingRootBinder(Mappings mappings, XmlNamespaceManager namespaceManager, Dialect.Dialect dialect) : base(mappings) { this.namespaceManager = namespaceManager; this.dialect = dialect; }
protected Binder(Mappings mappings) { if (mappings == null) throw new ArgumentNullException("mappings"); this.mappings = mappings; }
/// <summary> /// Converts a partial class name into a fully one /// </summary> /// <param name="className"></param> /// <param name="mappings"></param> /// <returns>The class FullName (without the assembly)</returns> /// <remarks> /// The FullName is equivalent to the default entity-name /// </remarks> protected static string FullClassName(string className, Mappings mappings) { if (className == null) return null; return TypeNameParser.Parse(className, mappings.DefaultNamespace, mappings.DefaultAssembly).Type; }
private static IAuxiliaryDatabaseObject CreateCustomObject(Mappings mappings, HbmDatabaseObject databaseObjectSchema) { HbmDefinition definitionSchema = databaseObjectSchema.FindDefinition(); string customTypeName = definitionSchema.@class; try { string className = TypeNameParser.Parse(customTypeName, mappings.DefaultNamespace, mappings.DefaultAssembly).ToString(); System.Type customType = ReflectHelper.ClassForName(className); IAuxiliaryDatabaseObject customObject = (IAuxiliaryDatabaseObject)Activator.CreateInstance(customType); Dictionary<string, string> parameters = definitionSchema.FindParameters(); customObject.SetParameterValues(parameters); foreach (string dialectName in databaseObjectSchema.FindDialectScopeNames()) { customObject.AddDialectScope(dialectName); } return customObject; } catch (TypeLoadException exception) { throw new MappingException(string.Format("Could not locate custom database object class [{0}].", customTypeName), exception); } catch (Exception exception) { throw new MappingException( string.Format("Could not instantiate custom database object class [{0}].", customTypeName), exception); } }
public TypeBinder(SimpleValue value, Mappings mappings) : base(mappings) { if (value == null) { throw new ArgumentNullException("value"); } this.value = value; }
public PropertiesBinder(Mappings mappings, PersistentClass persistentClass, Dialect.Dialect dialect) : base(mappings, dialect) { this.persistentClass = persistentClass; entityName = persistentClass.EntityName; propertyBasePath = entityName; className = persistentClass.ClassName; mappedClass = persistentClass.MappedClass; componetDefaultNullable = true; component = null; }
public PropertiesBinder(Mappings mappings, Component component, string className, string path, bool isNullable, Dialect.Dialect dialect) : base(mappings, dialect) { persistentClass = component.Owner; this.component = component; entityName = className; this.className = component.ComponentClassName; mappedClass = component.ComponentClass; propertyBasePath = path; componetDefaultNullable = isNullable; }
public static FluentConfig Scan(Action<IConventionScanner> scanner) { var scannerSettings = ProcessSettings(scanner); if (scannerSettings.Lazy) { var lazyPocoMappings = new Mappings(); return SetFactory(lazyPocoMappings, scanner); } return Configure(CreateMappings(scannerSettings, null)); }
public static Mappings Scan(Action<IConventionScanner> scanner) { var scannerSettings = ProcessSettings(scanner); if (scannerSettings.Lazy) { var lazyPocoMappings = new Mappings(); SetFactory(lazyPocoMappings, scanner); return lazyPocoMappings; } return CreateMappings(scannerSettings, null); }
public PostgresBulkInserter(string nameOrConnectionString, Type type, Mappings columnMappings = null) { _type = type; try { _connectionString = ConfigUtilities.GetConnectionString(nameOrConnectionString); } catch (ConfigurationErrorsException configException) { _connectionString = nameOrConnectionString; } ColumnMappings = columnMappings ?? new Mappings(type).MapDirectly(); }
public void GetMappings() { string folder = @"../../Framework/TestData/Mappings"; Mappings mapping = new Mappings(folder); Assert.IsNotNull(mapping); Assert.AreEqual(8, mapping.Count); IList specials = GetSpecialMaps(mapping.Keys); Assert.AreEqual(1, specials.Count); Assert.IsNotNull(mapping["java.lang.StringBuffer"]); IDictionary ressField = mapping["java.lang.StringBuffer"].Members; Assert.AreEqual(4, ressField.Count); }
public void CanBulkInsertIntoPostgres() { var mappings = new Mappings<Db>().MapAsLowercaseUnderscore(); Chronos.PostgreSQL.PostgresBulkInserter<Db> bcp = new Chronos.PostgreSQL.PostgresBulkInserter<Db>("Server=127.0.0.1;Port=5432;Database=jinx;User Id=postgres;Password=postgres", mappings); var itemsToInsert = new List<Db> { new Db {DatabaseId = Guid.NewGuid(), Name = "Random1"}, new Db {DatabaseId = Guid.NewGuid(), Name = "Random2"}, new Db {DatabaseId = Guid.NewGuid(), Name = "Random4"}, new Db {DatabaseId = Guid.NewGuid(), Name = "Random3"}, new Db {DatabaseId = Guid.NewGuid(), Name = "Random5"}, new Db {DatabaseId = Guid.NewGuid(), Name = "Random6"}, new Db {DatabaseId = Guid.NewGuid(), Name = "Random7"}, }; bcp.Insert(itemsToInsert, "databases"); }
public void CanBulkInsertToPostgresNonGenericly() { var mappings = new Mappings(typeof(Db)).MapAsLowercaseUnderscore(); var bcp = new Chronos.PostgreSQL.PostgresBulkInserter("Server=127.0.0.1;Port=5432;Database=jinx;User Id=postgres;Password=postgres", typeof(Db),mappings); var itemsToInsert = new List<Db> { new Db {DatabaseId = Guid.NewGuid(), Name = "NonGeneric"}, new Db {DatabaseId = Guid.NewGuid(), Name = "RNonGenericandom2"}, new Db {DatabaseId = Guid.NewGuid(), Name = "RNonGenericandom4"}, new Db {DatabaseId = Guid.NewGuid(), Name = "RNonGenericandom3"}, new Db {DatabaseId = Guid.NewGuid(), Name = "NonGenericRandom5"}, new Db {DatabaseId = Guid.NewGuid(), Name = "RNonGenericandom6"}, new Db {DatabaseId = Guid.NewGuid(), Name = "RNonGenericandom7"}, }; bcp.Insert(itemsToInsert, "databases"); }
private static Mappings CreateMappings(ConventionScannerSettings scannerSettings, Type[] typesOverride) { var types = typesOverride ?? FindTypes(scannerSettings); var config = new Dictionary<Type, TypeDefinition>(); foreach (var type in types) { var pocoDefn = new TypeDefinition(type) { AutoIncrement = scannerSettings.PrimaryKeysAutoIncremented(type), PrimaryKey = scannerSettings.PrimaryKeysNamed(type), TableName = scannerSettings.TablesNamed(type), SequenceName = scannerSettings.SequencesNamed(type), ExplicitColumns = true }; foreach (var prop in ReflectionUtils.GetFieldsAndPropertiesForClasses(type)) { var column = new ColumnDefinition(); column.MemberInfo = prop; column.DbColumnName = scannerSettings.PropertiesNamed(prop); column.DbColumnAlias = scannerSettings.AliasNamed(prop); column.IgnoreColumn = scannerSettings.IgnorePropertiesWhere.Any(x => x.Invoke(prop)); column.DbColumnType = scannerSettings.DbColumnTypesAs(prop); column.ResultColumn = scannerSettings.ResultPropertiesWhere(prop); column.ComputedColumn = scannerSettings.ComputedPropertiesWhere(prop); column.VersionColumn = scannerSettings.VersionPropertiesWhere(prop); column.ForceUtc = scannerSettings.ForceDateTimesToUtcWhere(prop); pocoDefn.ColumnConfiguration.Add(prop.Name, column); } config.Add(type, pocoDefn); } MergeOverrides(config, scannerSettings.MappingOverrides); //if (scannerSettings.OverrideWithAttributes) //{ // MergeAttributeOverrides(config); //} var pocoMappings = new Mappings {Config = config}; return pocoMappings; }
public override DifferenceType Diff(IDifferences differences, Mappings.MemberMapping mapping) { ITypeDefinitionMember impl = mapping[0]; ITypeDefinitionMember contract = mapping[1]; if (impl == null) return DifferenceType.Unknown; if (contract == null && impl.IsAbstract()) { // If the type is effectively sealed then it is ok to remove abstract members ITypeDefinition contractType = mapping.ContainingType[1]; // We check that interfaces have the same number of members in another rule so there is no need to check that here. if (contractType != null && (contractType.IsEffectivelySealed() || (contractType.IsInterface && mapping.ContainingType[0].IsInterface))) return DifferenceType.Unknown; differences.AddIncompatibleDifference(this, "Member '{0}' is abstract in the implementation but is missing in the contract.", impl.FullName()); return DifferenceType.Changed; } return DifferenceType.Unknown; }
private static Mappings CreateMappings(ConventionScannerSettings scannerSettings, Type[] typesOverride) { var types = typesOverride ?? FindTypes(scannerSettings); var config = new Dictionary<Type, TypeDefinition>(); foreach (var type in types) { var pocoDefn = new TypeDefinition(type) { AutoIncrement = scannerSettings.PrimaryKeysAutoIncremented(type), PrimaryKey = scannerSettings.PrimaryKeysNamed(type), TableName = scannerSettings.TablesNamed(type), SequenceName = scannerSettings.SequencesNamed(type), }; foreach (var prop in type.GetProperties()) { var column = new ColumnDefinition(); column.PropertyInfo = prop; column.DbColumnName = scannerSettings.PropertiesNamed(prop); column.IgnoreColumn = scannerSettings.IgnorePropertiesWhere.Any(x => x.Invoke(prop)); column.ResultColumn = scannerSettings.ResultPropertiesWhere(prop); column.VersionColumn = scannerSettings.VersionPropertiesWhere(prop); pocoDefn.ColumnConfiguration.Add(prop.Name, column); } config.Add(type, pocoDefn); } MergeOverrides(config, scannerSettings.MappingOverrides); var pocoMappings = new Mappings {Config = config}; SetFactory(pocoMappings, null); return pocoMappings; }
protected static string GetEntityName(IRelationship relationship, Mappings mappings) { string entityName = string.IsNullOrEmpty(relationship.EntityName) ? null : relationship.EntityName; string className = string.IsNullOrEmpty(relationship.Class) ? null : relationship.Class; entityName = entityName ?? (className == null ? null : StringHelper.GetFullClassname(FullQualifiedClassName(className, mappings))); return entityName; }
public static void SaveMappings(Mappings whichMappings = Mappings.CurrentBootMappings, MapLocation whereToSave = MapLocation.LocalMachineKeyboardLayout) { Collection<KeyMapping> maps; switch (whichMappings) { case Mappings.CurrentBootMappings: maps = mappings; break; case Mappings.SavedBootMappings: maps = savedBootMappings; break; default: return; } RegistryHive hive = 0; string keyname = "", valuename = ""; RegistryProvider.GetRegistryLocation(whereToSave, ref hive, ref keyname, ref valuename); RegistryKey registry = null; // Need write access so prepare to fail try { if (hive == RegistryHive.LocalMachine) { registry = Registry.LocalMachine.OpenSubKey(keyname, true); } else if (hive == RegistryHive.CurrentUser) { registry = Registry.CurrentUser.OpenSubKey(keyname, true); } } catch (SecurityException ex) { if (hive == RegistryHive.CurrentUser) { // Would expect to be able to write to HKCU Console.WriteLine("Unexpected failure {2} opening {0} on {1} for write access", keyname, Enum.GetNames(typeof(Mappings))[(int)whichMappings], ex.Message); } return; } if (registry == null) { // Key doesn't exist. TODO Shouldn't this be logged? return; } if (maps.Count == 0) { registry.SetValue(valuename, new byte[0]); } else { registry.SetValue(valuename, GetMappingsAsByteArray(maps)); } }
public CustomContentTypeProvider() { Mappings.Add(".svclog", "text/xml"); }
/// <summary> /// Query if this is a mapped type /// </summary> /// <param name="sourceType"></param> /// <returns></returns> protected bool WillExpandDirect(Type sourceType) { return(Mappings.ContainsKey(sourceType) && Mappings[sourceType] != null); }
public void AddFluentMapping(Type mapping) { Mappings.Add(mapping); }
public RootClassBinder(Mappings mappings, Dialect.Dialect dialect) : base(mappings, dialect) { }
private extern void orig_Remap(Mappings mapping);
private bool CanEditOrDeleteMapping(int mappingId) { var system = Mappings.Where(x => x.MappingId == mappingId).Select(x => x.SystemName).FirstOrDefault(); return(AuthorisationHelpers.HasMappingRights("Location", system)); }
private void drop(IDataObject dataObject) { if (dataObject == null) { return; } var data = dataObject.GetData(typeof(DraggableRowsBehavior.Data)) as DraggableRowsBehavior.Data; if (data == null) { return; } if (data.TargetIndex < 0 && Mappings.Any()) // // don't allow invalid targets, but allow drop on an empty grid { return; } DeviceViewModel srcDevice = data.SenderDataContext as DeviceViewModel; if (srcDevice == null) { return; } // copy and sort selected items List <RowItemViewModel> selected = new List <RowItemViewModel>( data.SelectedItems .Cast <RowItemViewModel>() .OrderBy(s => srcDevice._mappings.IndexOf(s)) ); int newIndex = Math.Max(0, data.TargetIndex); if (srcDevice != this || !data.IsMove) { if (data.IsMove) { srcDevice.removeMappings(selected); } SelectedMappings.Clear(); foreach (var row in selected) { var rawMapping = (row.Item as MappingViewModel).Copy(true); insertMapping(newIndex++, rawMapping); } } else { var movingAction = new Action <int, int>((oi, ni) => { _device.MoveMapping(oi, ni); _mappings.Move(oi, ni); }); MovingLogicHelper.Move <RowItemViewModel>(_mappings, selected, newIndex, movingAction); } if (selected.Any()) { selected.Last().BringIntoView(); } }
public ClassCompositeIdBinder(Mappings mappings) : base(mappings) { }
bool TryGetMapping(PostgresType pgType, [MaybeNullWhen(false)] out NpgsqlTypeMapping?mapping) => Mappings.TryGetValue(pgType.Name, out mapping) || Mappings.TryGetValue(pgType.FullName, out mapping) || pgType is PostgresDomainType domain && (
public IHttpActionResult PutScenario([FromUri] Guid id, [FromBody] ScenarioModel command) { // Check empty name if (string.IsNullOrWhiteSpace(command.Name)) { return(this.Error().InvalidParameters("No name was entered")); } if (!ModelState.IsValid) { return(this.Error().InvalidParameters("Invalid scenario parameters")); } var scenario = _scenarioRepository.Get(id); if (scenario == null) { return(NotFound()); } var scenario2 = _scenarioRepository.FindByName(command.Name, command.IsLibraried); if (scenario2 != null && scenario.Id != scenario2.Id) { return(this.Error().InvalidParameters("Scenario with such name already exists")); } var salesAreas = _salesAreaRepository.GetAll(); foreach (var pass in command.Passes) { if (_passInspectorService.InspectPassSalesAreaPriorities( pass.PassSalesAreaPriorities, out string errorMessage)) { return(this.Error().InvalidParameters(errorMessage)); } List <string> errorMessages = new List <string>(); if (!BreakExclusionsValidations.DateTimeRangeIsValid(pass.BreakExclusions, salesAreas, out errorMessages)) { return(this.Error().InvalidParameters(errorMessages)); } } var oldPassIds = scenario.Passes.Select(p => p.Id).ToList(); // Get PassIds to delete var deletedPassIds = oldPassIds.Except(command.Passes.Select(p => p.Id)).Distinct().ToList(); ValidateCampaignPriorityRounds(command.CampaignPriorityRounds); Mappings.ApplyToScenario(scenario, command, _mapper); IdUpdater.SetIds(scenario, _identityGeneratorResolver); // Update Pass repository UpdatePassRepository(scenario, command, deletedPassIds); _passRepository.SaveChanges(); // update scenario with any changes to passes in that scenario.campaignpasspriorities UpdateScenarioWithEditedPassList(scenario, oldPassIds, deletedPassIds); // Validate, update and save scenario ValidateForSave(scenario); scenario.DateUserModified = DateTime.UtcNow; _scenarioRepository.Update(new List <Scenario> { scenario }); // Used bulk update method as a temporary solution as it is optimized to update nested collections // Will be changed in scope of performance optimizations phase 2 _scenarioRepository.SaveChanges(); // Do not remove this, need to persist changes now so that we can return ScenarioModel return(Ok(Mappings.MapToScenarioModel(scenario, _scenarioRepository, _passRepository, _tenantSettingsRepository, _mapper))); }
public IHttpActionResult PostScenario([FromBody] CreateScenarioModel command) { // Check empty name if (string.IsNullOrWhiteSpace(command.Name)) { return(this.Error().InvalidParameters("No name was entered")); } if (!ModelState.IsValid) { return(this.Error().InvalidParameters("Invalid scenario parameters")); } // Check that scenario doesn't exist Scenario scenario = _scenarioRepository.Get(command.Id); if (scenario != null) { return(this.Error().InvalidParameters("Scenario already exists")); } // Check that scenario with such name doesn't exist scenario = _scenarioRepository.FindByName(command.Name, command.IsLibraried); if (scenario != null) { return(this.Error().InvalidParameters("Scenario with such name already exists")); } foreach (var pass in command.Passes) { if (_passInspectorService.InspectPassSalesAreaPriorities( pass.PassSalesAreaPriorities, out string errorMessage)) { return(this.Error().InvalidParameters(errorMessage)); } List <string> errorMessages = new List <string>(); if (!BreakExclusionsValidations.DateTimeRangeIsValid(pass.BreakExclusions, _salesAreaRepository.GetAll(), out errorMessages)) { return(this.Error().InvalidParameters(errorMessages)); } } ValidateCampaignPriorityRounds(command.CampaignPriorityRounds); // Add scenario scenario = _mapper.Map <Scenario>(command); IdUpdater.SetIds(scenario, _identityGeneratorResolver); // Update Pass repository UpdatePassRepository(scenario, command, null); _passRepository.SaveChanges(); // Add Campaign Pass Priorities to Scenario var campaignsResult = _campaignRepository.GetWithProduct(null); var usingAllCampaigns = campaignsResult.Items?.Any() == true?campaignsResult.Items.ToList() : null; var forScenarioPasses = _passRepository.FindByIds(scenario.Passes.Select(p => p.Id)).ToList(); var allCampaigns = usingAllCampaigns?.ToDictionary(x => x.ExternalId, x => x); CampaignPassPrioritiesServiceMapper.AmendCampaignPassPrioritiesForNewCampaigns( scenario, forScenarioPasses, allCampaigns, _passRepository, _mapper); // Validate ValidateForSave(scenario); scenario.DateUserModified = DateTime.UtcNow; // Add scenario _scenarioRepository.Add(scenario); _scenarioRepository.SaveChanges(); // Do not remove this, need to persist changes now so that we can return ScenarioModel return(Ok(Mappings.MapToScenarioModel(scenario, _scenarioRepository, _passRepository, _tenantSettingsRepository, _mapper))); }
public NamedQueryBinder(Mappings mappings) : base(mappings) { }
private static void MergeOverrides(Dictionary<Type, TypeDefinition> config, Mappings overrideMappings) { if (overrideMappings == null) return; foreach (var overrideTypeDefinition in overrideMappings.Config) { if (!config.ContainsKey(overrideTypeDefinition.Key)) continue; var convTableDefinition = config[overrideTypeDefinition.Key]; convTableDefinition.PrimaryKey = overrideTypeDefinition.Value.PrimaryKey ?? convTableDefinition.PrimaryKey; convTableDefinition.SequenceName = overrideTypeDefinition.Value.SequenceName ?? convTableDefinition.SequenceName; convTableDefinition.TableName = overrideTypeDefinition.Value.TableName ?? convTableDefinition.TableName; convTableDefinition.AutoIncrement = overrideTypeDefinition.Value.AutoIncrement ?? convTableDefinition.AutoIncrement; convTableDefinition.ExplicitColumns = overrideTypeDefinition.Value.ExplicitColumns ?? convTableDefinition.ExplicitColumns; foreach (var overrideColumnDefinition in overrideMappings.Config[overrideTypeDefinition.Key].ColumnConfiguration) { var convColDefinition = convTableDefinition.ColumnConfiguration[overrideColumnDefinition.Key]; convColDefinition.DbColumnName = overrideColumnDefinition.Value.DbColumnName ?? convColDefinition.DbColumnName; convColDefinition.DbColumnAlias = overrideColumnDefinition.Value.DbColumnAlias ?? convColDefinition.DbColumnAlias; convColDefinition.DbColumnType = overrideColumnDefinition.Value.DbColumnType ?? convColDefinition.DbColumnType; convColDefinition.IgnoreColumn = overrideColumnDefinition.Value.IgnoreColumn ?? convColDefinition.IgnoreColumn; convColDefinition.ResultColumn = overrideColumnDefinition.Value.ResultColumn ?? convColDefinition.ResultColumn; convColDefinition.ComputedColumn = overrideColumnDefinition.Value.ComputedColumn ?? convColDefinition.ComputedColumn; convColDefinition.VersionColumn = overrideColumnDefinition.Value.VersionColumn ?? convColDefinition.VersionColumn; convColDefinition.MemberInfo = overrideColumnDefinition.Value.MemberInfo ?? convColDefinition.MemberInfo; convColDefinition.ForceUtc = overrideColumnDefinition.Value.ForceUtc ?? convColDefinition.ForceUtc; } } }
private void updateMapsChanged() { IsChanged = Mappings.Any(m => (m.Item as MappingViewModel).IsChanged); }
/// <summary> /// Clears all type-mappings and instances. /// </summary> public void Clear() { Instances.Clear(); Mappings.Clear(); RelationshipMappings.Clear(); }
public PostOfficeClient() { this.DataStore = new InMemoryDataStore(); this.Mappings = new Dictionary <Type, DataStoreMapping>(); var mAccount = new DataStoreMapping(); mAccount.Table = new DBTable("Accounts"); mAccount.Table.AddColumn(new DBColumn("UserName", true, null, 255, DBColumnType.String)); mAccount.Table.AddColumn(new DBColumn("PublicName", false, null, 1024, DBColumnType.String)); mAccount.Create = () => new Account(); mAccount.Load = (obj, values, omap) => { ((Account)obj).SetKey((string)values[0]); ((Account)obj).PublicName = (string)values[1]; }; mAccount.Save = (obj, values) => { values[0] = ((Account)obj).UserName; values[1] = ((Account)obj).PublicName; }; mAccount.GetKey = (obj) => ((Account)obj).UserName; mAccount.RefColumns = Enumerable.Empty <DataStoreMapping.Column>(); Mappings.Add(typeof(Account), mAccount); var mMessage = new DataStoreMapping(); mMessage.Table = new DBTable("Messages"); var mMessageKey = new DBColumn("ID", true, null, 0, DBColumnType.Int32); mMessageKey.IsIdentity = true; mMessage.Table.AddColumn(mMessageKey); mMessage.Table.AddColumn(new DBColumn("Subject", false, null, 1024, DBColumnType.String)); mMessage.Table.AddColumn(new DBColumn("Body", false, null, -1, DBColumnType.String)); mMessage.Table.AddColumn(new DBColumn("Sender", false, null, 255, DBColumnType.String)); mMessage.Table.AddColumn(new DBColumn("Recepient", false, null, 255, DBColumnType.String)); mMessage.Table.PrimaryKey = new DBPrimaryKey(new object[] { mMessageKey }); mMessage.Create = () => new Message(); mMessage.SetKey = (obj, key) => { ((Message)obj).SetKey((int)key); }; mMessage.GetKey = (obj) => ((Message)obj).ID; mMessage.Load = (obj, values, omap) => { var o = (Message)obj; o.SetKey((int)values[0]); o.Subject = (string)values[1]; o.Body = (string)values[2]; o.Sender = GetReference <Account>(omap, values[3]); o.Recepient = GetReference <Account>(omap, values[4]); }; mMessage.Save = (obj, values) => { var o = (Message)obj; values[0] = o.ID; values[1] = o.Subject; values[2] = o.Body; values[3] = o.Sender?.UserName; values[4] = o.Recepient?.UserName; }; mMessage.RefColumns = new DataStoreMapping.Column[] { new DataStoreMapping.Column() { Index = 3, Type = typeof(Account) }, new DataStoreMapping.Column() { Index = 4, Type = typeof(Account) } }; Mappings.Add(typeof(Message), mMessage); DataStore.UpdateSchema(false, mAccount.Table, mMessage.Table); CreateDemoData(); }
private void addKeyConfigLine(Mappings key, List <Keys> list) { Add(new Setting(Label(key), list).Pressed(delegate { Remap(key); })); }
public static void Apply(this Mappings current, Mappings mappings, Func <string, Mappings> findMappingsFunc) { foreach (var id in mappings.DependsOn) { current.Apply(findMappingsFunc(id), findMappingsFunc); }
public UnionSubclassBinder(Mappings mappings, Dialect.Dialect dialect) : base(mappings, dialect) { }
private IEnumerable <MappingModel> ToMappingModels() { return(Mappings.Where(m => !m.IsAdminInterface).Select(_mappingConverter.ToMappingModel)); }
public void DoSetup() { Mappings.CreateMappings(); }
/** * Creates a set of mappings that operations can be applied to, such as * saving to a DOM or Agent.cfg. The results can be asserted by calling * {@see #assertMappings(Mappings)}. * * NOTE: This method returns an AgentConfig instance instead of a mappings * instance because there is no way set the Mappings instance on * AgentConfig. This might change in the future * * @return */ private AgentConfig createMappings() { Mappings root = fCfg.Mappings; // Remove the mappings being used root.RemoveChild(root.GetMappings("Default")); root.RemoveChild(root.GetMappings("TestID")); Mappings newMappings = root.CreateChild("Test"); // Add an object mapping ObjectMapping objMap = new ObjectMapping("StudentPersonal"); // Currently, the Adk code requires that an Object Mapping be added // to it's parent before fields are added. // We should re-examine this and perhaps fix it, if possible newMappings.AddRules(objMap); objMap.AddRule(new FieldMapping("FIELD1", "Name/FirstName")); // Field 2 FieldMapping field2 = new FieldMapping("FIELD2", "Name/LastName"); field2.ValueSetID = "VS1"; field2.Alias = "ALIAS1"; field2.DefaultValue = "DEFAULT1"; MappingsFilter mf = new MappingsFilter(); mf.Direction = MappingDirection.Inbound; mf.SifVersion = SifVersion.SIF11.ToString(); field2.Filter = mf; objMap.AddRule(field2); // Field 3 test setting the XML values after it's been added to the // parent object (the code paths are different) FieldMapping field3 = new FieldMapping("FIELD3", "Name/MiddleName"); objMap.AddRule(field3); field3.ValueSetID = "VS2"; field3.Alias = "ALIAS2"; field3.DefaultValue = "DEFAULT2"; MappingsFilter mf2 = new MappingsFilter(); mf2.Direction = MappingDirection.Outbound; mf2.SifVersion = SifVersion.SIF15r1.ToString(); field3.Filter = mf2; field3.NullBehavior = MappingBehavior.IfNullDefault; OtherIdMapping oim = new OtherIdMapping("ZZ", "BUSROUTE"); FieldMapping field4 = new FieldMapping("FIELD4", oim); objMap.AddRule(field4); field4.DefaultValue = "Default"; field4.ValueSetID = "vs"; field4.Alias = "alias"; field4.DefaultValue = null; field4.ValueSetID = null; field4.Alias = null; field4.NullBehavior = MappingBehavior.IfNullSuppress; // Field4 tests the new datatype attribute FieldMapping field5 = new FieldMapping("FIELD5", "Demographics/BirthDate"); objMap.AddRule(field5); field5.DataType = SifDataType.Date; // Add a valueset translation ValueSet vs = new ValueSet("VS1"); newMappings.AddValueSet(vs); // Add a few definitions for (int a = 0; a < 10; a++) { vs.Define("Value" + a, "SifValue" + a, "Title" + a); } vs.Define("AppDefault", "0000", "Default App Value"); vs.SetAppDefault("AppDefault", true); vs.Define("0000", "SifDefault", "Default Sif Value"); vs.SetSifDefault("SifDefault", false); // Add a valueset translation vs = new ValueSet("VS2"); newMappings.AddValueSet(vs); // Add a few definitions for (int a = 0; a < 3; a++) { vs.Define("q" + a, "w" + a, "t" + a); } vs.Define("AppDefault", "0000", "Default Value"); vs.SetAppDefault("AppDefault", true); vs.SetSifDefault("0000", true); return(fCfg); }
public CollectionBinder(Mappings mappings, Dialect.Dialect dialect) : base(mappings, dialect) { }
public static FluentConfig Configure(Mappings mappings) { return SetFactory(mappings, null); }
/// <summary> /// Take a complex object, and transfer properties requested into a dictionary /// </summary> /// <param name="source"></param> /// <param name="context"></param> /// <param name="includes"></param> /// <param name="visited"></param> /// <returns></returns> protected Dictionary <string, object> ExpandBlindObject(object source, ContextType context, IEnumerable <PropertyReference> includes, HashSet <int> visited) { visited = UniqueVisit(source, visited); Type sourceType = source.GetType(); includes = ValidateIncludes(includes, sourceType); // Attempt to create a projection object we'll map the data into var destinationObject = new Dictionary <string, object>(); MappingDefinition mappingDefinition = null; // Allow any actions to run ahead of mapping if (Mappings.ContainsKey(sourceType)) { foreach (var action in Mappings[sourceType]._BeforeExpansion) { action(destinationObject, source, context); } mappingDefinition = Mappings[source.GetType()]; } // Iterate over only the requested properties foreach (var propertyReference in includes) { string propertyName = propertyReference.PropertyName; if (mappingDefinition != null) { var preparers = mappingDefinition.PrepareProperties; // See if there's a propertyPreparer if (preparers.ContainsKey(propertyName)) { preparers[propertyName](destinationObject, null, source, context); } } // Transform the input value as needed object valueToAssign = GetSourceValue(source, context, propertyName, mappingDefinition?.Translators); /// If authorization indicates this should not in fact be authorized, skip it if (!AuthorizeValue(source, context, valueToAssign)) { continue; } if (WillExpand(valueToAssign)) { valueToAssign = Expand(valueToAssign, context, propertyReference.Children, visited); } destinationObject[propertyName] = valueToAssign; } // Allow any actions to run after the mapping /// @Todo should this be in reverse order so we have a nested stack style FILO? if (Mappings.ContainsKey(sourceType)) { foreach (var action in Mappings[sourceType]._AfterExpansion) { action(destinationObject, source, context); } } return(destinationObject); }
public IdGeneratorBinder(Mappings mappings) : base(mappings) {}
protected ClassBinder(Mappings mappings, Dialect.Dialect dialect) : base(mappings) { this.dialect = dialect; }
protected static string GetClassName(string unqualifiedName, Mappings mappings) { return ClassForNameChecked(unqualifiedName, mappings, "unknown class {0}").FullName; //return TypeNameParser.Parse(unqualifiedName, mappings.DefaultNamespace, mappings.DefaultAssembly).ToString(); }
public NamedSQLQueryBinder(Mappings mappings) : base(mappings) { }
protected override MappingContainer GetFromMappings(Mappings mappings) { return(null); }
private static FluentConfig SetFactory(Mappings mappings, Action<IConventionScanner> scanner) { var maps = mappings; var scana = scanner; return new FluentConfig(mapper => new PocoDataFactory(t => { if (maps != null) { if (maps.Config.ContainsKey(t)) { return new FluentMappingsPocoData(t, mappings.Config[t], mapper); } if (scana != null) { var settings = ProcessSettings(scana); var typeMapping = CreateMappings(settings, new[] { t }); return new FluentMappingsPocoData(t, typeMapping.Config[t], mapper); } } return new PocoData(t, mapper); })); }
public override void Update() { if (!connected) { return; } #if MouseMode if (InMouseMode) { UpdateMouseMode(); return; } #endif byte[] rumble = new byte[8]; byte[] report = new byte[28]; byte[] parsed = new byte[28]; #region Populate Report Revised report[0] = (byte)ID; report[1] = 0x02; report[10] = 0; report[11] = 0; report[12] = 0; report[13] = 0; float LX = 0f; float LY = 0f; float RX = 0f; float RY = 0f; float LT = 0f; float RT = 0f; ResetReport(); //foreach (KeyValuePair<string, string> map in Mappings) for (int i = 0; i < Mappings.Count; i++) { var map = Mappings.ElementAt(i); if (!Values.ContainsKey(map.Key)) { continue; } if (writeReport.ContainsKey(map.Value)) { try { writeReport[map.Value] += Values[map.Key]; } catch (KeyNotFoundException) { } } else if (Values.ContainsKey(map.Key)) { switch (map.Value) { case Inputs.Xbox360.LLEFT: try { LX -= Values[map.Key]; } catch { } break; case Inputs.Xbox360.LRIGHT: try { LX += Values[map.Key]; } catch { } break; case Inputs.Xbox360.LUP: try { LY += Values[map.Key]; } catch { } break; case Inputs.Xbox360.LDOWN: try { LY -= Values[map.Key]; } catch { } break; case Inputs.Xbox360.RLEFT: try { RX -= Values[map.Key]; } catch { } break; case Inputs.Xbox360.RRIGHT: try { RX += Values[map.Key]; } catch { } break; case Inputs.Xbox360.RUP: try { RY += Values[map.Key]; } catch { } break; case Inputs.Xbox360.RDOWN: try { RY -= Values[map.Key]; } catch { } break; case Inputs.Xbox360.LT: try { LT += Values[map.Key]; } catch { } break; case Inputs.Xbox360.RT: try { RT += Values[map.Key]; } catch { } break; #if MouseMode case "MouseMode": if (Values[map.Key] > 0f && DateTime.Now.Subtract(_mmLastTime).TotalSeconds > 3) { _mmLastTime = DateTime.Now; InMouseMode = true; } break; #endif } } } report[10] |= (byte)(writeReport[Inputs.Xbox360.BACK] > 0f ? 1 << 0 : 0); report[10] |= (byte)(writeReport[Inputs.Xbox360.LS] > 0f ? 1 << 1 : 0); report[10] |= (byte)(writeReport[Inputs.Xbox360.RS] > 0f ? 1 << 2 : 0); report[10] |= (byte)(writeReport[Inputs.Xbox360.START] > 0f ? 1 << 3 : 0); report[10] |= (byte)(writeReport[Inputs.Xbox360.UP] > 0f ? 1 << 4 : 0); report[10] |= (byte)(writeReport[Inputs.Xbox360.DOWN] > 0f ? 1 << 5 : 0); report[10] |= (byte)(writeReport[Inputs.Xbox360.RIGHT] > 0f ? 1 << 6 : 0); report[10] |= (byte)(writeReport[Inputs.Xbox360.LEFT] > 0f ? 1 << 7 : 0); report[11] |= (byte)(writeReport[Inputs.Xbox360.LB] > 0f ? 1 << 2 : 0); report[11] |= (byte)(writeReport[Inputs.Xbox360.RB] > 0f ? 1 << 3 : 0); report[11] |= (byte)(writeReport[Inputs.Xbox360.Y] > 0f ? 1 << 4 : 0); report[11] |= (byte)(writeReport[Inputs.Xbox360.B] > 0f ? 1 << 5 : 0); report[11] |= (byte)(writeReport[Inputs.Xbox360.A] > 0f ? 1 << 6 : 0); report[11] |= (byte)(writeReport[Inputs.Xbox360.X] > 0f ? 1 << 7 : 0); report[12] |= (byte)(writeReport[Inputs.Xbox360.GUIDE] > 0f ? 1 << 0 : 0); report[14] = (byte)((GetRawAxis(LX) >> 0) & 0xFF); report[15] = (byte)((GetRawAxis(LX) >> 8) & 0xFF); report[16] = (byte)((GetRawAxis(LY) >> 0) & 0xFF); report[17] = (byte)((GetRawAxis(LY) >> 8) & 0xFF); report[18] = (byte)((GetRawAxis(RX) >> 0) & 0xFF); report[19] = (byte)((GetRawAxis(RX) >> 8) & 0xFF); report[20] = (byte)((GetRawAxis(RY) >> 0) & 0xFF); report[21] = (byte)((GetRawAxis(RY) >> 8) & 0xFF); report[26] = GetRawTrigger(LT); report[27] = GetRawTrigger(RT); #endregion bus.Parse(report, parsed); if (bus.Report(parsed, rumble)) { // This is set on a rumble state change if (rumble[1] == 0x08) { // Check if it's strong enough to rumble int strength = BitConverter.ToInt32(new byte[] { rumble[4], rumble[3], 0x00, 0x00 }, 0); //System.Diagnostics.Debug.WriteLine(strength); Flags[Inputs.Flags.RUMBLE] = (strength > minRumble); //Values[Inputs.Flags.RUMBLE] = strength > minRumble ? strength : 0; RumbleAmount = strength > minRumble ? strength : 0; } } }
/// <summary> /// Returns the list used to remap keys during a remap operation. /// This should be the a List<Keys> field in your settings class /// </summary> /// <param name="remapping">The int value of the mapping being remapped</param> /// <param name="newKey">The new key that the user is attempting to set.</param> /// <returns>the field to set keys with, otherwise return null to cancel the operation</returns> protected virtual List <Keys> GetRemapList(int remapping, Keys newKey) { Mappings mappedKey = (Mappings)remapping; if (newKey == Keys.None || (newKey == Keys.Left && mappedKey != Mappings.Left) || (newKey == Keys.Right && mappedKey != Mappings.Right) || (newKey == Keys.Up && mappedKey != Mappings.Up) || (newKey == Keys.Down && mappedKey != Mappings.Down) || (newKey == Keys.Enter && mappedKey != Mappings.Confirm) || (newKey == Keys.Back && mappedKey != Mappings.Cancel)) { return(null); } switch (mappedKey) { case Mappings.Left: Settings.Instance.Left = ((newKey != Keys.Left) ? newKey : Keys.None); return(null); case Mappings.Right: Settings.Instance.Right = ((newKey != Keys.Right) ? newKey : Keys.None); return(null); case Mappings.Up: Settings.Instance.Up = ((newKey != Keys.Up) ? newKey : Keys.None); return(null); case Mappings.Down: Settings.Instance.Down = ((newKey != Keys.Down) ? newKey : Keys.None); return(null); case Mappings.Jump: return(Settings.Instance.Jump); case Mappings.Dash: return(Settings.Instance.Dash); case Mappings.Grab: return(Settings.Instance.Grab); case Mappings.Talk: return(Settings.Instance.Talk); case Mappings.Confirm: if (!Settings.Instance.Cancel.Contains(newKey) && !Settings.Instance.Pause.Contains(newKey)) { if (newKey != Keys.Enter) { return(Settings.Instance.Confirm); } } return(null); case Mappings.Cancel: if (!Settings.Instance.Confirm.Contains(newKey) && !Settings.Instance.Pause.Contains(newKey)) { if (newKey != Keys.Back) { return(Settings.Instance.Cancel); } } return(null); case Mappings.Pause: if (!Settings.Instance.Confirm.Contains(newKey) && !Settings.Instance.Cancel.Contains(newKey)) { return(Settings.Instance.Pause); } return(null); case Mappings.Journal: return(Settings.Instance.Journal); case Mappings.QuickRestart: return(Settings.Instance.QuickRestart); default: return(null); } }
private void ShowMappingWindow(MappingModel mappingModel) { XmlElement newMapping = mConfiguration.ConfigXml.CreateElement(MappingName); IElementConfiguration elementConfiguration = new ElementConfiguration(mConfiguration, mappingModel.Node, newMapping); ElementWindow elementWindow = new ElementWindow(elementConfiguration, DefinitionFactory.Create(MappingDescriptor.Mapping, elementConfiguration), WindowSizeLocationFactory.Create(MappingDescriptor.Mapping), new AddSaveStrategy <MappingModel>(mappingModel, model => Mappings.Add(model), newMapping)); mMessageBoxService.ShowWindow(elementWindow); }
/// <summary> /// Similar to <see cref="ClassForFullNameChecked" />, but handles short class names /// by calling <see cref="FullQualifiedClassName" />. /// </summary> /// <param name="name"></param> /// <param name="mappings"></param> /// <param name="errorMessage"></param> /// <returns></returns> protected static System.Type ClassForNameChecked(string name, Mappings mappings, string errorMessage) { return ClassForFullNameChecked(FullQualifiedClassName(name, mappings), errorMessage); }
private void OnRemove(MappingModel mappingModel) { Mappings.Remove(mappingModel); }
protected static string GetQualifiedClassName(string unqualifiedName, Mappings mappings) { return ClassForNameChecked(unqualifiedName, mappings, "unknown class {0}").AssemblyQualifiedName; }
public MyContentTypeProvider() { Mappings.Add(".image", "image/pngn"); Mappings.Remove(".json"); }
public IEnumerable <RuleTypeModel> GetAll() { var ruleTypes = _ruleTypeRepository.GetAll().OrderBy(p => p.Id).ToList(); return(Mappings.MapToRuleTypeModel(ruleTypes, _ruleRepository, _mapper)); }
public IHttpActionResult Put([FromUri] int id, [FromBody] RuleTypeModel command) { if (command == null) { return(BadRequest("Entity can not be null")); } if (command.Id != id) { return(BadRequest("Model id does not match")); } if (!ModelState.IsValid || command.Rules == null || !command.Rules.Any()) { return(this.Error().InvalidParameters("Invalid rule type parameters")); } var targetRuleType = _ruleTypeRepository.Get(id); if (targetRuleType is null) { return(NotFound()); } // Update rule type targetRuleType.Name = command.Name; _ruleTypeRepository.Update(targetRuleType); _ruleTypeRepository.SaveChanges(); var rules = _ruleRepository.FindByRuleTypeId(targetRuleType.Id); var deletedRuleIds = rules.Where(r => command.Rules.All(cr => r.Id != cr.Id)) .Select(r => new { r.Id, r.RuleId }) .ToList(); var maxRuleId = command.Rules.Max(r => r.RuleId) + 1; var newRuleIds = new List <int>(); // Upsert rules per rule type foreach (var ruleItem in command.Rules) { var rule = _ruleRepository.Get(ruleItem.Id); if (rule != null) { rule.Description = ruleItem.Description; rule.InternalType = ruleItem.InternalType; rule.Type = ruleItem.Type; _ruleRepository.Update(rule); } else { rule = _mapper.Map <Rule>(ruleItem); rule.Id = 0; rule.RuleTypeId = id; rule.RuleId = maxRuleId++; _ruleRepository.Add(rule); if (targetRuleType.AllowedForAutopilot && !targetRuleType.IsCustom) { newRuleIds.Add(rule.RuleId); } } } _ruleRepository.SaveChanges(); // Delete rules only for custom rule types if (deletedRuleIds.Any()) { deletedRuleIds.ForEach(r => _ruleRepository.Delete(r.Id)); } _ruleRepository.SaveChanges(); if (targetRuleType.AllowedForAutopilot && !targetRuleType.IsCustom) { UpdateAutopilotRulesRepository(targetRuleType.Id, newRuleIds, deletedRuleIds.Select(r => r.RuleId).ToList()); } var ruleType = _ruleTypeRepository.Get(id); return(Ok(Mappings.MapToRuleTypeModel(ruleType, _ruleRepository, _mapper))); }
/** * Asserts that the provided set of Mappings matches the one that was * created in createMappings(); */ private void assertMappings(Mappings m) { Mappings test = m.GetMappings("Test"); Assertion.AssertNotNull("Test mappings is not present", test); Assertion.AssertEquals("Should have a single Object Mapping", 1, test.GetObjectMappings().Length); // TODO: Test the version and sourceId filters more carefully /* * Assertion.AssertEquals( "SifVersion attr should be empty", 0, * test.SifVersionFilter().Length ); Assertion.AssertEquals( "SourceId attr * should be empty", 0, test.SourceIdFilter().Length ); Assertion.AssertEquals( * "Zone attr should be empty", 0, test.ZoneIdFilter().Length ); */ // assert the object mapping ObjectMapping om = test.GetObjectMapping("StudentPersonal", false); Assertion.AssertNotNull("StudentPersonal mappings", om); Assertion.AssertEquals("There should be five rules", 5, om.RuleCount); IList <FieldMapping> rules = om.GetRulesList(false); // Field 1 Assertion.AssertEquals("FIELD1 name", "FIELD1", rules[0].FieldName); Assertion.AssertEquals("FIELD1 rule", "Name/FirstName", rules[0].GetRule().ToString()); Assertion.AssertEquals("FIELD1 ifNull", MappingBehavior.IfNullUnspecified, rules[0].NullBehavior); // Field 2 Assertion.AssertEquals("FIELD2 name", "FIELD2", rules[1].FieldName); Assertion.AssertEquals("FIELD2 rule", "Name/LastName", rules[1].GetRule().ToString()); Assertion.AssertEquals("FIELD2 valueset", "VS1", rules[1].ValueSetID); Assertion.AssertEquals("FIELD2 alias", "ALIAS1", rules[1].Alias); Assertion.AssertEquals("FIELD2 default", "DEFAULT1", rules[1].DefaultValue); MappingsFilter filter = rules[1].Filter; Assertion.AssertNotNull("FIELD2 filter is null", filter); Assertion.AssertEquals("filter direction", MappingDirection.Inbound, filter .Direction); Assertion.AssertEquals("filter sif version", "=" + SifVersion.SIF11.ToString(), filter.SifVersion); // Field 3 Assertion.AssertEquals("FIELD3 name", "FIELD3", rules[2].FieldName); Assertion.AssertEquals("FIELD3 rule", "Name/MiddleName", rules[2].GetRule().ToString()); Assertion.AssertEquals("FIELD3 valueset", "VS2", rules[2].ValueSetID); Assertion.AssertEquals("FIELD3 alias", "ALIAS2", rules[2].Alias); Assertion.AssertEquals("FIELD3 default", "DEFAULT2", rules[2].DefaultValue); Assertion.AssertEquals("FIELD3 ifNull", MappingBehavior.IfNullDefault, rules[2].NullBehavior); MappingsFilter filter2 = rules[2].Filter; Assertion.AssertNotNull("FIELD3 filter is null", filter2); Assertion.AssertEquals("filter2 direction", MappingDirection.Outbound, filter2.Direction); Assertion.AssertEquals("filter2 sif version", "=" + SifVersion.SIF15r1.ToString(), filter2.SifVersion); // Field 4 Assertion.AssertEquals("FIELD4 name", "FIELD4", rules[3].FieldName); Assertion.AssertNull("FIELD4 valueset", rules[3].ValueSetID); Assertion.AssertNull("FIELD4 alias", rules[3].Alias); Assertion.AssertNull("FIELD4 default", rules[3].DefaultValue); Assertion.AssertEquals("FIELD4 ifNull", MappingBehavior.IfNullSuppress, rules[3].NullBehavior); Rule r = rules[3].GetRule(); Assertion.Assert("Rule should be OtherIdRule", r is OtherIdRule); Assertion.AssertEquals("FIELD5 name", "FIELD5", rules[4].FieldName); Assertion.AssertEquals("FIELD5 datatype", SifDataType.Date, rules[4] .DataType); // TODO: The OtherIdRule doesn't have an API to get at the // OtherIdMapping. For now, just // convert it to a string and assert the results String ruleStr = r.ToString(); Assertion.Assert("prefix should be BUSROUTE", ruleStr .IndexOf("prefix='BUSROUTE'") > 1); Assertion.Assert("type should be ZZ", ruleStr.IndexOf("type='ZZ'") > 1); ValueSet vs = test.GetValueSet("VS1", false); Assertion.AssertNotNull("ValueSet VS1 should not be null", vs); Assertion.AssertEquals("VS1 should have 12 entries", 12, vs.Entries.Length); for (int a = 0; a < 10; a++) { Assertion.AssertEquals("Mapping by appvalue", "SifValue" + a, vs.Translate("Value" + a)); Assertion.AssertEquals("Mapping by sifvalue", "Value" + a, vs.TranslateReverse("SifValue" + a)); } // Test the default value entries Assertion.AssertEquals("Expecting app default value", "AppDefault", vs.TranslateReverse("abcdefg")); Assertion.AssertEquals("Expecting app default value", "AppDefault", vs.TranslateReverse(null)); Assertion.AssertEquals("Expecting sif default value", "SifDefault", vs.Translate("abcdefg")); Assertion.AssertNull("Expecting NULL value", vs.Translate(null)); vs = test.GetValueSet("VS2", false); Assertion.AssertNotNull("ValueSet VS2 should not be null", vs); Assertion.AssertEquals("VS2 should have 4 entries", 4, vs.Entries.Length); for (int a = 0; a < 3; a++) { Assertion.AssertEquals("Mapping by appvalue", "w" + a, vs.Translate("q" + a)); Assertion.AssertEquals("Mapping by sifvalue", "q" + a, vs .TranslateReverse("w" + a)); } // Test the default value entries Assertion.AssertEquals("Expecting app default value", "AppDefault", vs .TranslateReverse("abcdefg")); Assertion.AssertEquals("Expecting app default value", "AppDefault", vs .TranslateReverse(null)); Assertion.AssertEquals("Expecting sif default value", "0000", vs .Translate("abcdefg")); Assertion.AssertEquals("Expecting sif default value", "0000", vs.Translate(null)); }
private extern string Label(Mappings mapping);