public Dictionary<string, string> Generate(List<NameNode> idNameNodes, IEnumerable<string> excludedNames) { Generator.Reset(); int varCount = idNameNodes.Count; string[] newNames = new string[varCount]; var newSubstitution = new Dictionary<string, string>(); for (int i = 0; i < varCount; i++) { string newName; do { newName = Generator.Next(); } while (excludedNames.Contains(newName) || NamesGenerator.CSharpKeywords.Contains(newName)); newNames[i] = newName; } int ind = 0; foreach (NameNode v in idNameNodes) if (!newSubstitution.ContainsKey(v.Name)) newSubstitution.Add(v.Name, newNames[ind++]); return newSubstitution; }
public static GameObject[] ResolveTargets(GameObject source, IEnumerable<string> TargetIds, GameObjectCollection parent, GameConsole console, bool DeepProcess) { // If it passed, find all targets and activate them List<GameObject> foundTargets = new List<GameObject>(5); foreach (var item in parent) { if (item.Value != source && TargetIds.Contains(item.Value.GetSetting("id"))) foundTargets.Add(item.Value); } // Process all known collections if (DeepProcess) { for (int i = 0; i < console.LayeredTextSurface.LayerCount; i++) { var objects = console.GetObjectCollection(i); if (objects != parent) { foreach (var item in objects) { if (item.Value != source && TargetIds.Contains(item.Value.GetSetting("id"))) foundTargets.Add(item.Value); } } } } return foundTargets.ToArray(); }
/// <summary> /// Compares 2 userprofile. /// </summary> /// <param name="userProfile"></param> /// <param name="compUserProfile"></param> /// <param name="objectsToCompare"> optional (if not given, all objects will be taken into account)</param> /// <param name="networks"> optional (if not given, all networks will be added to the resulting usercomparison)</param> /// <returns></returns> internal static UserComparison CompareUserProfiles(ProfileData userProfile, ProfileData compUserProfile, IEnumerable<ProfileDataObjects> objectsToCompare = null, IEnumerable<Network> networks = null) { UserComparison userComparison = new UserComparison(); if (userProfile == null) userProfile = new ProfileData(); if (compUserProfile == null) compUserProfile = new ProfileData(); if(objectsToCompare == null) objectsToCompare = ProfileData.GetAllProfileDataObjects(); if (networks == null) networks = Network.GetAllNetworks(); userComparison.Networks = networks.ToList(); if (objectsToCompare.Contains(ProfileDataObjects.EDUCATION)) CompareEducation(ref userComparison, userProfile, compUserProfile); if(objectsToCompare.Contains(ProfileDataObjects.WORK)) CompareWork(ref userComparison, userProfile, compUserProfile); if (objectsToCompare.Contains(ProfileDataObjects.TEAM)) CompareInterests(ref userComparison, userProfile, compUserProfile, InterestType.TEAM); if (objectsToCompare.Contains(ProfileDataObjects.ATHLETE)) CompareInterests(ref userComparison, userProfile, compUserProfile, InterestType.ATHLETE); return userComparison; }
private static void AssertGetSensorsResult(IEnumerable<string> sensors) { Assert.IsNotNull(sensors); Assert.AreEqual(2, sensors.Count()); Assert.IsTrue(sensors.Contains("Temperature Sensor")); Assert.IsTrue(sensors.Contains("Velocity Sensor")); }
public IPagedList<User> GetServiceProvidersPage(int page, int itemsPerPage, IEnumerable<int> locations, IEnumerable<Guid> tags, string searchString) { IQueryable<User> users = _serviceHubEntities.Users .Include("Tags") .Include("Ratings") .Include("Locations") .Where(o => o.IsPublic); if (locations.Count() > 0) locations = _serviceHubEntities.GetLocationsHierarchy(string.Join(",", locations)).Select(o => o.Id); if (locations.Count() > 0 && tags.Count() > 0) users = users.Where(o => o.Locations.Any(i => locations.Contains(i.Id)) || o.Tags.Any(i => tags.Contains(i.Id))); else if (locations.Count() > 0) users = users.Where(o => o.Locations.Any(i => locations.Contains(i.Id))); else if (tags.Count() > 0) users = users.Where(o => o.Tags.Any(i => tags.Contains(i.Id))); if (!string.IsNullOrWhiteSpace(searchString)) { string searchStringUpperCase = searchString.ToUpper(); users = users.Where(o => o.Name.ToUpper().Contains(searchStringUpperCase)); } return users .OrderByDescending(o => o.Ratings.Average(i => i.Score)) .ToPagedList(page, itemsPerPage); }
public EdmDeltaModel(IEdmModel source, IEdmEntityType entityType, IEnumerable<string> propertyNames) { _source = source; _entityType = new EdmEntityType(entityType.Namespace, entityType.Name); foreach (var property in entityType.StructuralProperties()) { if (propertyNames.Contains(property.Name)) _entityType.AddStructuralProperty(property.Name, property.Type, property.DefaultValueString, property.ConcurrencyMode); } foreach (var property in entityType.NavigationProperties()) { if (propertyNames.Contains(property.Name)) { var navInfo = new EdmNavigationPropertyInfo() { ContainsTarget = property.ContainsTarget, DependentProperties = property.DependentProperties(), PrincipalProperties = property.PrincipalProperties(), Name = property.Name, OnDelete = property.OnDelete, Target = property.Partner != null ? property.Partner.DeclaringEntityType() : property.Type.TypeKind() == EdmTypeKind.Collection ? (property.Type.Definition as IEdmCollectionType).ElementType.Definition as IEdmEntityType : property.Type.TypeKind() == EdmTypeKind.Entity ? property.Type.Definition as IEdmEntityType : null, TargetMultiplicity = property.TargetMultiplicity(), }; _entityType.AddUnidirectionalNavigation(navInfo); } } }
internal static IQueryable<Agreement> VisibleTo(this IQueryable<Agreement> agreements, IPrincipal principal, IEnumerable<int> ownedTenantIds) { if (agreements == null) return null; if (principal == null) throw new ArgumentNullException("principal"); if (ownedTenantIds == null) throw new ArgumentNullException("ownedTenantIds"); // when user is not an agreement admin, filter out private agreements // and protected agreements that the user does not own if (!principal.IsInAnyRole(RoleName.AgreementManagers)) { return agreements.Where(x => Public.Equals(x.VisibilityText, StringComparison.OrdinalIgnoreCase) || ( Protected.Equals(x.VisibilityText, StringComparison.OrdinalIgnoreCase) && x.Participants.Any(y => y.IsOwner && ownedTenantIds.Contains(y.EstablishmentId)) ) ); } // when user is an agreement admin, include all agreements they own return agreements.Where(x => Public.Equals(x.VisibilityText, StringComparison.OrdinalIgnoreCase) || ( x.Participants.Any(y => y.IsOwner && ownedTenantIds.Contains(y.EstablishmentId)) ) ); }
public void String(IEnumerable<string> source, IEqualityComparer<string> comparer, string value, bool expected) { if (comparer == null) { Assert.Equal(expected, source.Contains(value)); } Assert.Equal(expected, source.Contains(value, comparer)); }
public void DeleteDataFor(IEnumerable<string> usersToDelete) { var postsToDelete = _container.Posts.Where(x => usersToDelete.Contains(x.CreatedBy)); DeletePosts(postsToDelete.ToList()); var questionsToDelete = _container.Questions.Where(x => usersToDelete.Contains(x.CreatedBy)); DeleteQuestions(questionsToDelete.ToList()); }
/// <summary> /// ขอข้อมูล User profile จากรหัส class room ที่ใช้งานล่าสุด /// </summary> /// <param name="classRoomId">รหัส class room ที่จะทำการขอข้อมูล</param> public IEnumerable<UserProfile> GetUserProfilesByLastActivateOnClassRoomId(IEnumerable<string> classRoomIds) { var qry = _mongoUtil.GetCollection<UserProfile>(TableName) .Find(it => !it.DeletedDate.HasValue && it.Subscriptions.Any(s => classRoomIds.Contains(s.ClassRoomId))) .ToEnumerable() .Where(it => classRoomIds.Contains(it.Subscriptions.Where(s => !s.DeletedDate.HasValue && s.LastActiveDate.HasValue).OrderBy(s => s.LastActiveDate).LastOrDefault().ClassRoomId)); return qry; }
protected void RemoveProperties(IEnumerable<string> paramNames, bool exclude) { var propNamesMappingsToRemove = new List<string>(PropertyMappings.Count); propNamesMappingsToRemove.AddRange(from propMapping in this.PropertyMappings where (exclude && !paramNames.Contains(propMapping.Value.PropertyName)) || (!exclude && paramNames.Contains(propMapping.Value.PropertyName)) select propMapping.Key); foreach (var propName in propNamesMappingsToRemove) { this.RemoveProperty(propName); } }
public IEnumerable<DealerManpower> FindAllDealerManpowers(IEnumerable<int> dealerIds, string dse) { IEnumerable<DealerManpower> manpowers; if (string.IsNullOrEmpty(dse)) manpowers = manpowerRepo.Fetch().Where(x => dealerIds.Contains(x.DealerId) && (x.ObjectInfo.DeletedDate == null || x.Profile.DateOfLeaving != null)).ToList(); else { manpowers = manpowerRepo.Fetch().Where(x => dealerIds.Contains(x.DealerId) && x.Type == dse && (x.ObjectInfo.DeletedDate == null || x.Profile.DateOfLeaving != null)).ToList(); } return manpowers; }
public IEnumerable<Package> GetUnfinishedPackages(string userKey, IEnumerable<string> userPackageIds) { if (userPackageIds == null || !userPackageIds.Any()) { return new Package[0]; } _packageAuthenticator.EnsureKeyCanAccessPackages(userPackageIds, userKey); IEnumerable<Package> existingPublishedPackages = _publishedPackageRepository.Collection.Where(pp => userPackageIds.Contains(pp.Id)).ToList() .Select(pp => new Package { Id = pp.Id, Version = pp.Version}); return _packageRepository.Collection.Where(p => userPackageIds.Contains(p.Id)) .Except(existingPublishedPackages, (x, y) => x.Id == y.Id && x.Version == y.Version); }
public async Task<bool> AllRequiredTagsArePresent(IEnumerable<int> tagsIds) { var exactlyOneSeasonTagIsPresent = await this.tags .All() .CountAsync(t => t.Type == TagType.Season && tagsIds.Contains(t.Id)) == 1; var languageOrTechnologyTagIsPresent = await this.tags .All() .AnyAsync(t => (t.Type == TagType.Technology || t.Type == TagType.Language) && tagsIds.Contains(t.Id)); return exactlyOneSeasonTagIsPresent && languageOrTechnologyTagIsPresent; }
public IEnumerable<Profile> FindProfilesByManPowerLevel(IEnumerable<int> dseIds, string value) { List<Profile> profiles; if (string.IsNullOrEmpty(value)) profiles = profileRepo.Fetch().Where(x => dseIds.Contains(x.DealerManpower.Id) && x.ObjectInfo.DeletedDate == null).ToList(); else { profiles = profileRepo.Fetch().Where(x => dseIds.Contains(x.DealerManpower.Id) && x.ObjectInfo.DeletedDate == null && x.TrainingLevel == value).ToList(); } return profiles; }
public ActionResult Search(string search, IEnumerable<int> selected, int? page = null) { if (page.HasValue) { const int pageSize = 6; var src = repo.GetAll().Where(o => (selected == null || !selected.Contains(o.Id)) && o.Name.Containz(search)); var rows = this.RenderView(@"Awesome\LookupList", src.Skip((page.Value - 1) * pageSize).Take(pageSize)); return Json(new { rows, more = src.Count() > page * pageSize }); } return View(@"Awesome\LookupList", repo.GetAll().Where(o => (selected == null || !selected.Contains(o.Id)) && o.Name.Containz(search))); }
protected void PrintBumps(IEnumerable<Bumped> _bumps) { if (_bumps.Contains(Bumped.Left)) Console.Write(">"); if (_bumps.Contains(Bumped.Right)) Console.Write("<"); if (_bumps.Contains(Bumped.Top)) Console.Write(@"\/"); if (_bumps.Contains(Bumped.Bottom)) Console.Write(@"/\"); Console.WriteLine(); }
public CommandLineArguments(IEnumerable<string> args) { Verbose = args.Contains("--verbose"); TerminateOnDisconnect = args.Contains("--terminateOnDisconnect"); if (args.Contains("--port")) { // TODO: Cleanup? var arglist = (IList<string>) args; var indexOfPortParam = arglist.IndexOf("--port") + 1; Port = int.Parse(arglist[indexOfPortParam]); } else Port = DefaultPort; }
public static List<EditorCrossSceneReference> GetCrossSceneReferencesForScenes( IEnumerable<Scene> scenes ) { // Start by logging out the cross-scene references out var crossSubSceneRefs = ComputeAllCrossSceneReferences(); // Remove all of the cross-scene references that do not pertain to our input SubScenes list crossSubSceneRefs.RemoveAll( x => { return !scenes.Contains( x.fromScene ) && !scenes.Contains( x.toScene ); } ); return crossSubSceneRefs; }
private static BindableCollection<ButtonModel> ConvertToButtons(IEnumerable<Answer> possibleAnswers) { if(possibleAnswers.Contains(Answer.Yes)) { return possibleAnswers.Contains(Answer.Cancel) ? new BindableCollection<ButtonModel>{new ButtonModel("Yes"), new ButtonModel("No"), new ButtonModel("Cancel")} : new BindableCollection<ButtonModel> {new ButtonModel("Yes"), new ButtonModel("No")}; } return possibleAnswers.Contains(Answer.Cancel) ? new BindableCollection<ButtonModel> {new ButtonModel("Ok"), new ButtonModel("Cancel")} : new BindableCollection<ButtonModel> {new ButtonModel("Ok")}; }
public byte[] ExtractDefaultTranslation(string sitePath, IEnumerable<string> extensionNames) { if (extensionNames == null || extensionNames.Count() == 0) { return ExtractDefaultTranslation(sitePath); } var site = Path.Get(sitePath); var zipFiles = new Dictionary<Path, StringBuilder>(); // Extract resources for module manifests site.Files("module.txt", true) .Where(p => extensionNames.Contains(p.Parent().FileName)) .Read((content, path) => { var moduleName = path.Parent().FileName; var poPath = GetModuleLocalizationPath(site, moduleName); ExtractPoFromManifest(zipFiles, poPath, content, path, site); }); // Extract resources for theme manifests site.Files("theme.txt", true) .Where(p => extensionNames.Contains(p.Parent().FileName)) .Read((content, path) => { var themeName = path.Parent().FileName; var poPath = GetThemeLocalizationPath(site, themeName); ExtractPoFromManifest(zipFiles, poPath, content, path, site); }); // Extract resources from views and cs files site.Files("*", true) .WhereExtensionIs(".cshtml", ".aspx", ".ascx", ".cs") .Where(p => { var tokens = p.MakeRelativeTo(site).Tokens; return new[] {"themes", "modules"}.Contains(tokens[0]) && extensionNames.Contains(tokens[1]); }) .Grep( ResourceStringExpression, (path, match, contents) => { var str = match.Groups[1].ToString(); DispatchResourceString(zipFiles, null, null, site, path, site, contents, str); } ) .Grep( PluralStringExpression, (path, match, contents) => { var str = match.Groups[1].ToString(); DispatchResourceString(zipFiles, null, null, site, path, site, contents, str); str = match.Groups[6].ToString(); DispatchResourceString(zipFiles, null, null, site, path, site, contents, str); } ); return ZipExtensions.Zip( new Path(zipFiles.Keys.Select(p => p.MakeRelativeTo(site))), p => Encoding.UTF8.GetBytes(zipFiles[site.Combine(p)].ToString())); }
public static string GetDays(IEnumerable<string> days) { string result = days.FirstOrDefault(); if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday || DateTime.Today.DayOfWeek == DayOfWeek.Sunday) { if(days.Contains("Выходные")) result = "Выходные"; } else if (DateTime.Today.DayOfWeek != DayOfWeek.Saturday && DateTime.Today.DayOfWeek != DayOfWeek.Sunday) { if (days.Contains("Рабочие")) result = "Рабочие"; } return result; }
public static string CopyName(string name, IEnumerable<string> names) { if (!names.Contains(name)) return name; int index = 1; while (true) { var newName = string.Format(CopyFormat, name, index); if (!names.Contains(newName)) return newName; index++; } }
public byte[] PackageTranslations(string cultureCode, string sitePath, IEnumerable<string> extensionNames) { var site = Path.Get(sitePath); var translationFiles = site .Files("orchard.*.po", true) .Where(p => extensionNames != null && (p.Parent().FileName.Equals(cultureCode, StringComparison.OrdinalIgnoreCase) && (extensionNames.Contains(p.MakeRelativeTo(site.Combine("Modules")).Tokens[0], StringComparer.OrdinalIgnoreCase) || extensionNames.Contains(p.MakeRelativeTo(site.Combine("Themes")).Tokens[0], StringComparer.OrdinalIgnoreCase)))) .MakeRelativeTo(site); return ZipExtensions.Zip( translationFiles, p => site.Combine(p).ReadBytes()); }
public static string CopyFileName(string name, IEnumerable<string> names) { if (!names.Contains(name)) return name; int index = 1; while (true) { var shortName = Path.GetFileNameWithoutExtension(name); var ext = Path.GetExtension(name); var newName = string.Format(CopyFormat, shortName, index) + ext; if (!names.Contains(newName)) return newName; index++; } }
public void DropColumns(string tableName, IEnumerable<string> columns) { using (var transaction = _sqLiteMigrationHelper.BeginTransaction()) { var originalColumns = _sqLiteMigrationHelper.GetColumns(tableName); var originalIndexes = _sqLiteMigrationHelper.GetIndexes(tableName); var newColumns = originalColumns.Where(c => !columns.Contains(c.Key)).Select(c => c.Value).ToList(); var newIndexes = originalIndexes.Where(c => !columns.Contains(c.Column)); CreateTable(tableName, newColumns, newIndexes); transaction.Commit(); } }
public static void SetLayer(this Transform transform, int layer, IEnumerable<int> excludeLayers = null) { if (excludeLayers == null || !excludeLayers.Contains(transform.gameObject.layer)) transform.gameObject.layer = layer; for (int i = 0; i < transform.GetChildCount(); ++i) { Transform child = transform.GetChild(i); if (excludeLayers == null || !excludeLayers.Contains(child.gameObject.layer)) child.gameObject.layer = layer; SetLayer(child, layer, excludeLayers); } }
public GetDepartamentosViewModel(IEnumerable<string> codigoEmpresas, IEnumerable<string> codigoDepartamentos) : this() { AufenPortalReportesDataContext db = new AufenPortalReportesDataContext() .WithConnectionStringFromConfiguration(); if (codigoEmpresas != null && codigoEmpresas.Any(x => !String.IsNullOrEmpty(x))) { Empresas = db.EMPRESAs.Where(x => codigoEmpresas.Contains(x.Codigo)); Vw_Ubicaciones = db.vw_Ubicaciones.Where(x => codigoEmpresas.Contains(x.IdEmpresa)); } if (codigoDepartamentos != null && codigoDepartamentos.Any(x => !String.IsNullOrEmpty(x))) { CodigoDepartamentos = codigoDepartamentos; } }
private static string[] CreateStringArrayFromCard(Card card, IEnumerable<List> lists, IEnumerable<string> fieldsToInclude) { var list = new List<string>(); if(fieldsToInclude.Contains("Name")) list.Add(card.Name); if (fieldsToInclude.Contains("Description")) list.Add(card.Desc); if (fieldsToInclude.Contains("Due Date")) list.Add(card.Due.ToString()); if (fieldsToInclude.Contains("List")) list.Add(lists.FirstOrDefault() != null ? lists.FirstOrDefault().Name : null); return list.ToArray(); }
public IEnumerable<PropertyInfo> GetProperties( Type type, bool declaredOnly, IEnumerable<PropertyInfo> explicitlyMappedProperties = null, IEnumerable<Type> knownTypes = null, bool includePrivate = false) { DebugCheck.NotNull(type); explicitlyMappedProperties = explicitlyMappedProperties ?? Enumerable.Empty<PropertyInfo>(); knownTypes = knownTypes ?? Enumerable.Empty<Type>(); ValidatePropertiesForModelVersion(type, explicitlyMappedProperties); var propertyInfos = from p in declaredOnly ? type.GetDeclaredProperties() : type.GetNonHiddenProperties() where !p.IsStatic() && p.IsValidStructuralProperty() let m = p.Getter() where (includePrivate || (m.IsPublic || explicitlyMappedProperties.Contains(p) || knownTypes.Contains(p.PropertyType))) && (!declaredOnly || type.BaseType().GetInstanceProperties().All(bp => bp.Name != p.Name)) && (EdmV3FeaturesSupported || (!IsEnumType(p.PropertyType) && !IsSpatialType(p.PropertyType))) && (Ef6FeaturesSupported || !p.PropertyType.IsNested) select p; return propertyInfos; }
private static bool HasSolutionFolderProject(SolutionFile solutionFile, string solutionFolderName, IEnumerable <Guid> solutionFolderGUIDs, out SolutionFileProjectReference solutionFolderProject) { solutionFolderProject = solutionFile.SolutionFileProjectReferences.Where(x => solutionFolderGUIDs.Contains(x.ProjectGUID) && x.ProjectName == solutionFolderName).SingleOrDefault(); var solutionFolderExists = solutionFolderProject != default; return(solutionFolderExists); }
private static void Prefix(IDifficultyBeatmap difficultyBeatmap, ref OverrideEnvironmentSettings overrideEnvironmentSettings) { if (difficultyBeatmap.beatmapData is CustomBeatmapData customBeatmapData) { IEnumerable <string> requirements = ((List <object>)Trees.at(customBeatmapData.beatmapCustomData, "_requirements"))?.Cast <string>(); IEnumerable <string> suggestions = ((List <object>)Trees.at(customBeatmapData.beatmapCustomData, "_suggestions"))?.Cast <string>(); bool chromaRequirement = (requirements?.Contains(Chroma.Plugin.REQUIREMENTNAME) ?? false) || (suggestions?.Contains(Chroma.Plugin.REQUIREMENTNAME) ?? false); // please let me remove this shit bool legacyOverride = difficultyBeatmap.beatmapData.beatmapEventsData.Any(n => n.value >= LegacyLightHelper.RGB_INT_OFFSET); if (legacyOverride) { ChromaLogger.Log("Legacy Chroma Detected...", IPA.Logging.Logger.Level.Warning); ChromaLogger.Log("Please do not use Legacy Chroma for new maps as it is deprecated and its functionality in future versions of Chroma cannot be guaranteed", IPA.Logging.Logger.Level.Warning); } ChromaController.ToggleChromaPatches((chromaRequirement || legacyOverride) && ChromaConfig.Instance.CustomColorEventsEnabled); ChromaController.DoColorizerSabers = chromaRequirement && ChromaConfig.Instance.CustomColorEventsEnabled; if (chromaRequirement && ChromaConfig.Instance.EnvironmentEnhancementsEnabled && Trees.at(customBeatmapData.beatmapCustomData, "_environmentRemoval") != null) { overrideEnvironmentSettings = null; } } }
/// <summary> /// Creates a parameter from object by mapping the property from the target entity type. /// </summary> /// <param name="command">The command object to be used.</param> /// <param name="param">The object to be used when creating the parameters.</param> /// <param name="propertiesToSkip">The list of the properties to be skipped.</param> /// <param name="dbSetting">The database setting that is currently in used.</param> internal static void CreateParameters(this IDbCommand command, object param, IEnumerable <string> propertiesToSkip, IDbSetting dbSetting) { // Check for presence if (param == null) { return; } // Supporting the IDictionary<string, object> if (param is ExpandoObject || param is IDictionary <string, object> ) { CreateParameters(command, (IDictionary <string, object>)param, propertiesToSkip, dbSetting); } // Supporting the QueryField else if (param is QueryField) { CreateParameters(command, (QueryField)param, propertiesToSkip, dbSetting); } // Supporting the IEnumerable<QueryField> else if (param is IEnumerable <QueryField> ) { CreateParameters(command, (IEnumerable <QueryField>)param, propertiesToSkip, dbSetting); } // Supporting the QueryGroup else if (param is QueryGroup) { CreateParameters(command, (QueryGroup)param, propertiesToSkip, dbSetting); } // Otherwise, iterate the properties else { var type = param.GetType(); // Check the validity of the type if (type.IsGenericType && type.GetGenericTypeDefinition() == m_dictionaryType) { throw new InvalidOperationException("Invalid parameters passed. The supported type of dictionary object must be typeof(IDictionary<string, object>)."); } // Variables for properties var properties = (IEnumerable <ClassProperty>)null; // Add this check for performance if (propertiesToSkip == null) { properties = PropertyCache.Get(type, dbSetting); } else { properties = PropertyCache.Get(type, dbSetting) .Where(p => propertiesToSkip?.Contains(p.PropertyInfo.Name, StringComparer.OrdinalIgnoreCase) == false); } // Iterate the properties foreach (var property in properties) { // Get the property vaues var name = property.GetUnquotedMappedName(); var value = property.PropertyInfo.GetValue(param); // Get property db type var dbType = property.GetDbType(); // Ensure mapping based on the value type if (dbType == null) { dbType = TypeMapper.Get(value?.GetType().GetUnderlyingType()); } // Check for specialized if (dbType == null) { var propertyType = property.PropertyInfo.PropertyType.GetUnderlyingType(); if (propertyType?.IsEnum == true) { dbType = DbType.String; } else if (propertyType == m_bytesType) { dbType = DbType.Binary; } } // Add the new parameter command.Parameters.Add(command.CreateParameter(name, value, dbType, dbSetting)); } } }
public static bool IsAnyOf(this Guid @this, IEnumerable <Guid> items) => items?.Contains(@this) ?? false;
public static bool ContainsIgnoreCase(this IEnumerable <string> items, string subString) { return(items?.Contains(subString, StringComparer.OrdinalIgnoreCase) == true); }
public async Task <ILookup <int, ChainOfTitleSearch> > GetChainOfTitleSearchesByChainOfTitleIdAsync(IEnumerable <int> keys) { return((await _context.ChainOfTitleSearch.Where(entity => keys.Contains(entity.ChainOfTitleId)).ToListAsync()).ToLookup(entity => entity.ChainOfTitleId)); }
/// <summary> /// Should return exchange rates among the specified currencies that are defined by the source. But only those defined /// by the source, do not return calculated exchange rates. E.g. if the source contains "CZK/USD" but not "USD/CZK", /// do not return exchange rate "USD/CZK" with value calculated as 1 / "CZK/USD". If the source does not provide /// some of the currencies, ignore them. /// </summary> public IEnumerable <ExchangeRate> GetExchangeRates(IEnumerable <Currency> currencies) { return(this.provider.GetAllRates() .Where(rate => currencies?.Contains(rate.TargetCurrency) == true) .ToArray() ?? new ExchangeRate[0]); }
/// <summary> /// Create the command parameters from the list of <see cref="QueryField"/> objects. /// </summary> /// <param name="command">The command object to be used.</param> /// <param name="queryFields">The list of <see cref="QueryField"/> objects.</param> /// <param name="propertiesToSkip">The list of the properties to be skipped.</param> /// <param name="resetOthers">True to reset the other parameter object. This will ignore the skipped properties.</param> /// <param name="dbSetting">The database setting that is currently in used.</param> internal static void SetParameters(this IDbCommand command, IEnumerable <QueryField> queryFields, IEnumerable <string> propertiesToSkip, bool resetOthers, IDbSetting dbSetting) { // Variables needed var dbType = (DbType?)null; var others = (IList <DbParameter>)null; var filtered = queryFields .Where(qf => propertiesToSkip?.Contains(qf.Field.UnquotedName, StringComparer.OrdinalIgnoreCase) != true); // Iterate the parameter instead foreach (var parameter in command.Parameters.OfType <DbParameter>()) { var queryField = filtered.FirstOrDefault(qf => string.Equals(qf.Field.UnquotedName, parameter.ParameterName, StringComparison.OrdinalIgnoreCase)); // Skip and add to missing if null if (queryField == null) { // Add to missing properties if allowed to if (resetOthers == true) { if (others == null) { others = new List <DbParameter>(); } others.Add(parameter); } // Continue to next continue; } // Get the value var value = queryField.Parameter.Value; // Get the DB Type dbType = TypeMapper.Get(value?.GetType()?.GetUnderlyingType()); // Set the parameter parameter.Value = value; if (dbType != null) { parameter.DbType = dbType.Value; } else { parameter.ResetDbType(); } } // If there is any (then set to null) if (resetOthers == true && others?.Any() == true) { foreach (var parameter in others) { parameter.Value = DBNull.Value; parameter.ResetDbType(); } } }
/// <summary> /// Create the command parameters from the <see cref="IDictionary{TKey, TValue}"/> object. /// </summary> /// <param name="command">The command object to be used.</param> /// <param name="dictionary">The parameters from the <see cref="Dictionary{TKey, TValue}"/> object.</param> /// <param name="propertiesToSkip">The list of the properties to be skipped.</param> /// <param name="resetOthers">True to reset the other parameter object. This will ignore the skipped properties.</param> /// <param name="dbSetting">The database setting that is currently in used.</param> internal static void SetParameters(this IDbCommand command, IDictionary <string, object> dictionary, IEnumerable <string> propertiesToSkip, bool resetOthers, IDbSetting dbSetting) { // Variables needed var dbType = (DbType?)null; var others = (IList <DbParameter>)null; var fitered = dictionary .Where(kvp => propertiesToSkip?.Contains(kvp.Key, StringComparer.OrdinalIgnoreCase) != true); // Iterate the parameter instead foreach (var parameter in command.Parameters.OfType <DbParameter>()) { var kvp = fitered.FirstOrDefault(item => string.Equals(item.Key, parameter.ParameterName, StringComparison.OrdinalIgnoreCase)); // Skip and add to missing if null if (ReferenceEquals(null, kvp)) { // Add to missing properties if allowed to if (resetOthers == true) { if (others == null) { others = new List <DbParameter>(); } others.Add(parameter); } // Continue to next continue; } // Get the value var value = kvp.Value; // Cast the proper object and identify the properties if (kvp.Value is CommandParameter) { var commandParameter = (CommandParameter)kvp.Value; var property = commandParameter.MappedToType.GetProperty(kvp.Key); // Get the value value = commandParameter.Value; // Get the DB Type dbType = property?.GetCustomAttribute <TypeMapAttribute>()?.DbType ?? TypeMapper.Get(property?.PropertyType.GetUnderlyingType()); } else { // Get the DB Type dbType = TypeMapper.Get(kvp.Value?.GetType()?.GetUnderlyingType()); } // Set the parameter parameter.Value = value; if (dbType != null) { parameter.DbType = dbType.Value; } else { parameter.ResetDbType(); } } // If there is any (then set to null) if (resetOthers == true && others?.Any() == true) { foreach (var parameter in others) { parameter.Value = DBNull.Value; parameter.ResetDbType(); } } }
public AlphaSelectUserPage(Action <string> aReciever, IEnumerable <string> ExistUsers = null) { Reciever = aReciever; Title = L["Select a user"]; List = new ListView { ItemTemplate = new DataTemplateEx(AlphaFactory.GetGitHubUserCellType()) .SetBindingList("ImageSourceUrl", "Text"), }; List.ItemTapped += (sender, e) => { var User = e.Item.GetValue <string>("Text"); if (null != User) { Debug.WriteLine($"Select User: {User}"); Reciever(User); Domain.AddRecentUser(User); } AlphaFactory.MakeSureApp().Navigation.PopAsync(); }; List.ItemsSource = Domain.GetRecentUsers() .Where(i => !(ExistUsers?.Contains(i) ?? false)) .Select(i => ListItem.Make(i)); Search = new SearchBar { Placeholder = L["User's name etc."], SearchCommand = new Command ( async() => { List.IsVisible = false; Indicator.IsVisible = true; Indicator.IsRunning = true; List.ItemsSource = new object[] { }; try { var Json = await Domain.GetStringFromUrlAsync ( GitHub.GetSearchUsersUrl(Search.Text) ); Device.BeginInvokeOnMainThread ( () => { try { List.ItemsSource = GitHub.SearchResult <GitHub.SearchUser> .Parse(Json) .Items .Select(i => ListItem.Make(i)); } catch (Exception Err) { Debug.WriteLine(Err); if (!string.IsNullOrWhiteSpace(Search.Text)) { List.ItemsSource = new[] { Search.Text.Trim() } .Select(i => ListItem.Make(i)); } } Indicator.IsRunning = false; Indicator.IsVisible = false; List.IsVisible = true; } ); } catch (Exception Err) { Debug.WriteLine(Err); if (!string.IsNullOrWhiteSpace(Search.Text)) { List.ItemsSource = new[] { Search.Text.Trim() } .Select(i => ListItem.Make(i)); } Indicator.IsRunning = false; Indicator.IsVisible = false; List.IsVisible = true; } } ), }; Indicator = new ActivityIndicator { VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand, IsVisible = false, }; Content = new StackLayout { Orientation = StackOrientation.Vertical, //Spacing = 1.0, //BackgroundColor = Color.Gray, Children = { Search, List, Indicator, } }; }
/// <summary> /// Create the command parameters from the <see cref="IDictionary{TKey, TValue}"/> object. /// </summary> /// <param name="command">The command object to be used.</param> /// <param name="dictionary">The parameters from the <see cref="Dictionary{TKey, TValue}"/> object.</param> /// <param name="propertiesToSkip">The list of the properties to be skipped.</param> /// <param name="dbSetting">The database setting that is currently in used.</param> internal static void CreateParameters(this IDbCommand command, IDictionary <string, object> dictionary, IEnumerable <string> propertiesToSkip, IDbSetting dbSetting) { // Variables needed var dbType = (DbType?)null; var kvps = dictionary.Where(kvp => propertiesToSkip?.Contains(kvp.Key, StringComparer.OrdinalIgnoreCase) != true); // Iterate the key value pairs foreach (var kvp in kvps) { var value = kvp.Value; var valueType = (Type)null; // Cast the proper object and identify the properties if (kvp.Value is CommandParameter) { var commandParameter = (CommandParameter)kvp.Value; var property = commandParameter.MappedToType.GetProperty(kvp.Key); // Get the value value = commandParameter.Value; // Get the DB Type dbType = property?.GetCustomAttribute <TypeMapAttribute>()?.DbType; // Get the property-level mapping if (property != null) { dbType = TypeMapper.Get(property.PropertyType.GetUnderlyingType()); } // Set the value type if the DB Type is not found if (dbType == null) { valueType = value?.GetType()?.GetUnderlyingType(); } } else { valueType = kvp.Value?.GetType()?.GetUnderlyingType(); } // Check for the specialized types if (dbType == null) { if (valueType?.IsEnum == true) { dbType = DbType.String; } else if (valueType == m_bytesType) { dbType = DbType.Binary; } } // Add the parameter command.Parameters.Add(command.CreateParameter(kvp.Key, value, dbType, dbSetting)); } }
public async Task <IEnumerable <PokemonData> > GetDuplicatePokemonToTransfer( bool keepPokemonsThatCanEvolve = false, bool prioritizeIVoverCp = false, IEnumerable <PokemonId> filter = null) { var myPokemon = await GetPokemons(); var pokemonList = myPokemon.Where( p => p.DeployedFortId == string.Empty && p.Favorite == 0 && (p.Cp < GetPokemonTransferFilter(p.PokemonId).KeepMinCp || PokemonInfo.CalculatePokemonPerfection(p) < GetPokemonTransferFilter(p.PokemonId).KeepMinIvPercentage)) .ToList(); if (filter != null) { pokemonList = pokemonList.Where(p => !filter.Contains(p.PokemonId)).ToList(); } if (keepPokemonsThatCanEvolve) { var results = new List <PokemonData>(); var pokemonsThatCanBeTransfered = pokemonList.GroupBy(p => p.PokemonId) .Where(x => x.Count() > GetPokemonTransferFilter(x.Key).KeepMinDuplicatePokemon).ToList(); var myPokemonSettings = await GetPokemonSettings(); var pokemonSettings = myPokemonSettings.ToList(); var myPokemonFamilies = await GetPokemonFamilies(); var pokemonFamilies = myPokemonFamilies.ToArray(); foreach (var pokemon in pokemonsThatCanBeTransfered) { var settings = pokemonSettings.Single(x => x.PokemonId == pokemon.Key); var familyCandy = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId); var amountToSkip = GetPokemonTransferFilter(pokemon.Key).KeepMinDuplicatePokemon; if (settings.CandyToEvolve > 0 && _logicSettings.PokemonsToEvolve.Contains(pokemon.Key)) { var amountPossible = (familyCandy.Candy_ - 1) / (settings.CandyToEvolve - 1); if (amountPossible > amountToSkip) { amountToSkip = amountPossible; } } if (prioritizeIVoverCp) { results.AddRange(pokemonList.Where(x => x.PokemonId == pokemon.Key) .OrderByDescending(PokemonInfo.CalculatePokemonPerfection) .ThenBy(n => n.StaminaMax) .Skip(amountToSkip) .ToList()); } else { results.AddRange(pokemonList.Where(x => x.PokemonId == pokemon.Key) .OrderByDescending(x => x.Cp) .ThenBy(n => n.StaminaMax) .Skip(amountToSkip) .ToList()); } } return(results); } if (prioritizeIVoverCp) { return(pokemonList .GroupBy(p => p.PokemonId) .Where(x => x.Any()) .SelectMany( p => p.OrderByDescending(PokemonInfo.CalculatePokemonPerfection) .ThenBy(n => n.StaminaMax) .Skip(GetPokemonTransferFilter(p.Key).KeepMinDuplicatePokemon) .ToList())); } return(pokemonList .GroupBy(p => p.PokemonId) .Where(x => x.Any()) .SelectMany( p => p.OrderByDescending(x => x.Cp) .ThenBy(n => n.StaminaMax) .Skip(GetPokemonTransferFilter(p.Key).KeepMinDuplicatePokemon) .ToList())); }
public virtual bool IsFailed(HashSet <GuildWars2.ArenaNet.Model.V1.EventState> events) { IEnumerable <Guid> eventIds = EventStates.Select(es => es.Event).Distinct(); return(events.Where(es => eventIds.Contains(es.EventId) && es.StateEnum == EventStateType.Fail).Count() > 0); }
/// <summary> /// Detects if a value is in a given set. /// </summary> /// <typeparam name="T">The type of item to check.</typeparam> /// <param name="value">the value to look for in the given enumeration.</param> /// <param name="items">The enumeration of values to compare to the given value.</param> /// <returns>True if the value given is in the enumeration of comparison items.</returns> public static bool In <T>(this T value, IEnumerable <T> items) { return(items.Contains(value)); }
public override bool ContainsAny(IEnumerable <string> identifiers) { return(identifiers.Contains(name)); }
/// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="dictionary"></param> /// <param name="propertiesToSkip"></param> /// <param name="dbFields"></param> private static void CreateParameters(IDbCommand command, IDictionary <string, object> dictionary, IEnumerable <string> propertiesToSkip, IEnumerable <DbField> dbFields = null) { var kvps = dictionary.Where(kvp => propertiesToSkip?.Contains(kvp.Key, StringComparer.OrdinalIgnoreCase) != true); // Iterate the key value pairs foreach (var kvp in kvps) { var dbField = GetDbField(kvp.Key, dbFields); var value = kvp.Value; var classProperty = (ClassProperty)null; var valueType = (Type)null; // CommandParameter if (kvp.Value is CommandParameter) { var commandParameter = (CommandParameter)kvp.Value; classProperty = PropertyCache.Get(commandParameter.MappedToType, kvp.Key); value = commandParameter.Value; valueType = value?.GetType()?.GetUnderlyingType(); } else { valueType = value?.GetType()?.GetUnderlyingType(); } // Variables var isEnum = valueType?.IsEnum; // Propertyhandler var propertyHandler = GetProperyHandler(classProperty, valueType); var definition = InvokePropertyHandlerSetMethod(propertyHandler, value, classProperty); if (definition != null) { valueType = definition.ReturnType.GetUnderlyingType(); value = definition.Value; } // Automatic if (IsAutomaticConversion(dbField)) { var dbFieldType = dbField.Type.GetUnderlyingType(); value = AutomaticConvert(value, valueType, dbFieldType); valueType = dbFieldType; } // DbType var dbType = (valueType != null ? clientTypeToDbTypeResolver.Resolve(valueType) : null) ?? classProperty?.GetDbType() ?? value?.GetType()?.GetDbType(); // Specialized enum if (dbType == null && isEnum.HasValue && isEnum.Value == true) { dbType = DbType.String; } // Add the parameter command.Parameters.Add(command.CreateParameter(kvp.Key, value, dbType)); } }
/// <summary> /// Creates a command parameter from the <see cref="QueryField"/> object. /// </summary> /// <param name="command">The command object to be used.</param> /// <param name="queryField">The value of <see cref="QueryField"/> object.</param> /// <param name="propertiesToSkip">The list of the properties to be skipped.</param> /// <param name="entityType">The type of the data entity.</param> internal static void CreateParameters(this IDbCommand command, QueryField queryField, IEnumerable <string> propertiesToSkip, Type entityType) { // Exclude those to be skipped if (propertiesToSkip?.Contains(queryField.Field.Name, StringComparer.OrdinalIgnoreCase) == true) { return; } //// Validate, make sure to only have the proper operation //if (queryField.Operation != Operation.Equal) //{ // throw new InvalidOperationException($"Operation must only be '{nameof(Operation.Equal)}' when calling the 'Execute' methods."); //} // Get the values var value = queryField.Parameter.Value; var valueType = value?.GetType()?.GetUnderlyingType(); var dbType = (DbType?)null; #region PropertyHandler // Check the property handler var typeHandler = PropertyHandlerCache.Get <object>(valueType); if (typeHandler != null) { var classProperty = (ClassProperty)null; var setMethod = typeHandler.GetType().GetMethod("Set"); var returnType = setMethod.ReturnType; if (entityType != null) { classProperty = PropertyCache.Get(entityType, queryField.Field); } dbType = clientTypeToDbTypeResolver.Resolve(returnType); value = setMethod.Invoke(typeHandler, new[] { value, classProperty }); } #endregion #region DbType else { dbType = TypeMapCache.Get(valueType); // Check for the specialized types if (dbType == null) { if (valueType?.IsEnum == true) { dbType = DbType.String; } else if (valueType == bytesType) { dbType = DbType.Binary; } } } #endregion // Create the parameter command.Parameters.Add(command.CreateParameter(queryField.Parameter.Name, value, dbType)); }
public bool IsActionAllowed(CRUDAction action) => allowedActions?.Contains(action) ?? true;
// Always get first available private Pieces PseudoRandom(IEnumerable <IOccurancy <Pieces> > occurancies, IEnumerable <Pieces> history) { var available = (occurancies as IList <IOccurancy <Pieces> > ?? occurancies.ToList()).Where(x => !history.Contains(x.Value)).ToList(); if (available.Any()) { Pieces piece = available[0].Value; return(piece); } return(Pieces.Invalid); }
/// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="queryField"></param> /// <param name="propertiesToSkip"></param> /// <param name="entityType"></param> /// <param name="dbFields"></param> private static void CreateParameters(this IDbCommand command, QueryField queryField, IEnumerable <string> propertiesToSkip, Type entityType, IEnumerable <DbField> dbFields = null) { if (queryField == null) { return; } // Skip if (propertiesToSkip?.Contains(queryField.Field.Name, StringComparer.OrdinalIgnoreCase) == true) { return; } // Variables var dbField = GetDbField(queryField.Field.Name, dbFields); var value = queryField.Parameter.Value; var valueType = value?.GetType()?.GetUnderlyingType(); var isEnum = valueType?.IsEnum; // PropertyHandler var classProperty = PropertyCache.Get(entityType, queryField.Field); var propertyHandler = GetPropertyHandler(classProperty, valueType); var definition = InvokePropertyHandlerSetMethod(propertyHandler, value, classProperty); if (definition != null) { valueType = definition.ReturnType.GetUnderlyingType(); value = definition.Value; } // Automatic if (IsAutomaticConversion(dbField)) { var underlyingType = dbField.Type.GetUnderlyingType(); value = AutomaticConvert(value, classProperty?.PropertyInfo?.PropertyType?.GetUnderlyingType(), underlyingType); valueType = underlyingType; } // DbType var dbType = (valueType != null ? clientTypeToDbTypeResolver.Resolve(valueType) : null) ?? classProperty?.GetDbType() ?? value?.GetType()?.GetDbType(); // Try get fallback dbType by classProperty to avoid being mistaken as string when value is null. if (dbType == null && classProperty != null) { dbType = clientTypeToDbTypeResolver.Resolve(classProperty.PropertyInfo.PropertyType); } // Specialized enum if (dbType == null && isEnum.HasValue && isEnum == true) { dbType = Converter.EnumDefaultDatabaseType; } // Add the parameter command.Parameters.Add(command.CreateParameter(queryField.Parameter.Name, value, dbType)); }
public static bool IsAnyOf(this Guid? @this, IEnumerable <Guid> items) => @this.HasValue && (items?.Contains(@this) == true);
public static bool HasPermission(this IProvideMetadata type, IEnumerable <string> claims) { var permissions = type.GetMetadata <IEnumerable <string> >(PermissionsKey, new List <string>()); return(permissions.All(x => claims?.Contains(x) ?? false)); }
public static void TestFindVariantCrossingIons() { string myFile = Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestData\VariantCrossTest.psmtsv"); List <string> warnings = new List <string>(); List <PsmFromTsv> psms; psms = PsmTsvReader.ReadTsv(myFile, out warnings); // test will fail if the order of psms is changed to something other than top to bottom row // check that variant psm properties are being parsed correctly Assert.AreEqual("", psms[0].IdentifiedSequenceVariations); Assert.AreEqual("A147T", psms[1].IdentifiedSequenceVariations); Assert.AreEqual("541-541", psms[0].SpliceSites); Assert.AreEqual("", psms[1].SpliceSites); // check that the correct ions are being added to VariantCrossingIons List <List <string> > expected = new List <List <string> >(); expected.Add(new List <string>() { }); // no variant (7527) expected.Add(new List <string>() { "b3" }); // b fragments before and after variant (4211) expected.Add(new List <string>() { "y3" }); // y fragments before and after variant (7759) expected.Add(new List <string>() { "b4", "b16" }); // variant at 1st position (9221) expected.Add(new List <string>() { "y1", "y9" }); // variant at last position (6778) expected.Add(new List <string>() { "b4", "y35" }); // peptide comes from multiple proteins (8613) expected.Add(new List <string>() { "b1", "b10", "y1", "y6" }); // variation spans the whole peptide (8765) expected.Add(new List <string>() { }); // variant before peptide (8169) expected.Add(new List <string>() { }); // variant after peptide (6532) expected.Add(new List <string>() { "a3" }); // a fragments before and after variant (4212) expected.Add(new List <string>() { "c3" }); // c fragments before and after variant (4213) expected.Add(new List <string>() { "x3" }); // x fragments before and after variant (7760) expected.Add(new List <string>() { "zDot3" }); // z fragments before and after variant (7761) expected.Add(new List <string>() { }); // M fragment with length almost the whole peptide and variant in the middle (7762) expected.Add(new List <string>() { }); // D fragment with length almost the whole peptide and variant in the middle (7763) for (int i = 0; i < psms.Count; i++) { IEnumerable <string> actualIons = psms[i].VariantCrossingIons.Select(p => p.NeutralTheoreticalProduct.Annotation); foreach (string expectedIon in expected[i]) { Assert.IsTrue(actualIons.Contains(expectedIon), "VariantCrossingIons should contain ion " + expectedIon + " in file " + psms[i].FileNameWithoutExtension + "."); } foreach (string actualIon in actualIons) { Assert.IsTrue(expected[i].Contains(actualIon), "VariantCrossingIons should not contain ion " + actualIon + " in file " + psms[i].FileNameWithoutExtension + "."); } } }
internal static bool HasClusterConfigActionCapability(IEnumerable <string> capabilities) { return(capabilities.Contains(ClusterConfigActionCapabilitityName, StringComparer.OrdinalIgnoreCase)); }
/// <summary> /// True if the list contains CLEAR. /// </summary> public static bool ContainsClearKeyword(IEnumerable <string> values) { return(values?.Contains(Clear, StringComparer.OrdinalIgnoreCase) == true); }
public IEnumerable <ApiResource> FindApiResourcesByScope(IEnumerable <string> scopeNames) => Collection.Where(c => scopeNames?.Contains(c.ApiId) == true);
public static bool ContainsIgnoreCase(this IEnumerable <string> list, string value) => list?.Contains(value, StringComparer.OrdinalIgnoreCase) ?? false;
/// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="param"></param> /// <param name="propertiesToSkip"></param> /// <param name="dbFields"></param> private static void CreateParametersInternal(IDbCommand command, object param, IEnumerable <string> propertiesToSkip, IEnumerable <DbField> dbFields = null) { var type = param.GetType(); // Check if (type.IsGenericType && type.GetGenericTypeDefinition() == StaticType.Dictionary) { throw new InvalidParameterException("The supported type of dictionary object must be of type IDictionary<string, object>."); } // Variables var classProperties = type.IsClassType() ? PropertyCache.Get(type) : type.GetClassProperties(); // Skip if (propertiesToSkip != null) { classProperties = classProperties? .Where(p => propertiesToSkip?.Contains(p.PropertyInfo.Name, StringComparer.OrdinalIgnoreCase) == false); } // Iterate foreach (var classProperty in classProperties) { var name = classProperty.GetMappedName(); var dbField = GetDbField(name, dbFields); var value = classProperty.PropertyInfo.GetValue(param); var valueType = value?.GetType(); var isEnum = valueType?.IsEnum; var returnType = (Type)null; // Propertyhandler var propertyHandler = GetProperyHandler(classProperty, valueType); var definition = InvokePropertyHandlerSetMethod(propertyHandler, value, classProperty); if (definition != null) { returnType = definition.ReturnType.GetUnderlyingType(); value = definition.Value; } // Automatic if (IsAutomaticConversion(dbField)) { var underlyingType = dbField.Type.GetUnderlyingType(); value = AutomaticConvert(value, classProperty.PropertyInfo.PropertyType.GetUnderlyingType(), underlyingType); returnType = underlyingType; } // DbType var dbType = (returnType != null ? clientTypeToDbTypeResolver.Resolve(returnType) : null) ?? classProperty.GetDbType() ?? value?.GetType()?.GetDbType(); // Specialized enum if (dbType == null && isEnum.HasValue && isEnum.Value == true) { dbType = DbType.String; } // Add the parameter command.Parameters.Add(command.CreateParameter(name, value, dbType)); } }
/// <summary> /// Set the <see cref="IDbCommand"/> object existing <see cref="IDbDataParameter"/> values. /// </summary> /// <param name="command">The command object to be used.</param> /// <param name="param">The instance of where the parameter values will be set.</param> /// <param name="propertiesToSkip">The list of the properties to be skipped.</param> /// <param name="resetOthers">True to reset the other parameter object. This will ignore the skipped properties.</param> /// <param name="dbSetting">The database setting that is currently in used.</param> internal static void SetParameters(this IDbCommand command, object param, IEnumerable <string> propertiesToSkip, bool resetOthers, IDbSetting dbSetting) { // Do nothing if there is no parameter if (command.Parameters.Count == 0) { return; } // Check for presence if (param == null) { foreach (var parameter in command.Parameters.OfType <DbParameter>()) { parameter.Value = DBNull.Value; parameter.ResetDbType(); } } // Supporting the IDictionary<string, object> else if (param is ExpandoObject || param is IDictionary <string, object> ) { SetParameters(command, (IDictionary <string, object>)param, propertiesToSkip, resetOthers, dbSetting); } // Supporting the QueryField else if (param is QueryField) { SetParameters(command, (QueryField)param, propertiesToSkip, resetOthers, dbSetting); } // Supporting the IEnumerable<QueryField> else if (param is IEnumerable <QueryField> ) { SetParameters(command, (IEnumerable <QueryField>)param, propertiesToSkip, resetOthers, dbSetting); } // Supporting the QueryGroup else if (param is QueryGroup) { SetParameters(command, (QueryGroup)param, propertiesToSkip, resetOthers, dbSetting); } // Otherwise, iterate the properties else { var type = param.GetType(); // Check the validity of the type if (type.IsGenericType && type.GetGenericTypeDefinition() == m_dictionaryType) { throw new InvalidOperationException("Invalid parameters passed. The supported type of dictionary object must be typeof(IDictionary<string, object>)."); } // variables for properties var properties = (IEnumerable <ClassProperty>)null; // Add this check for performance if (propertiesToSkip == null) { properties = PropertyCache.Get(type, dbSetting); } else { properties = PropertyCache.Get(type, dbSetting) .Where(p => propertiesToSkip?.Contains(p.PropertyInfo.Name, StringComparer.OrdinalIgnoreCase) == false); } // Ensure there are properties if (resetOthers == true && properties.Any() != true) { SetParameters(command, (object)null, propertiesToSkip, true, dbSetting); } else { var parameters = command.Parameters.OfType <DbParameter>(); var missingParameters = (IList <DbParameter>)null; // Iterate the parameter instead foreach (var parameter in parameters) { var property = properties.FirstOrDefault(p => string.Equals(p.GetUnquotedMappedName(), parameter.ParameterName, StringComparison.OrdinalIgnoreCase)); // Skip if null if (property == null) { // Add to missing properties if allowed to if (resetOthers == true) { if (missingParameters == null) { missingParameters = new List <DbParameter>(); } missingParameters.Add(parameter); } // Continue to next continue; } // Get the property values var value = property.PropertyInfo.GetValue(param); var dbType = property.GetDbType() ?? TypeMapper.Get(property.PropertyInfo.PropertyType.GetUnderlyingType()); // Ensure the type mapping if (dbType == null) { if (value == null && property.PropertyInfo.PropertyType == m_bytesType) { dbType = DbType.Binary; } } // Set the parameter parameter.Value = value; if (dbType != null) { parameter.DbType = dbType.Value; } } // If there is any (then set to null) if (resetOthers == true && missingParameters?.Any() == true) { foreach (var parameter in missingParameters) { parameter.Value = DBNull.Value; parameter.ResetDbType(); } } } } }
public static bool NotIn <T>(this T value, IEnumerable <T> sequence) { return(!sequence.Contains(value)); }