private bool HasNoCustomMessageOverload(IGrouping <string, MethodInfo> shouldlyMethod) { var hasFuncStringOverload = shouldlyMethod.Any(m => m.GetParameters().Any(IsCustomMessageParameter <Func <string> >)); var hasStringOverload = shouldlyMethod.Any(m => m.GetParameters().Any(IsCustomMessageParameter <string>)); return(!hasFuncStringOverload && !hasStringOverload); }
/// <summary> /// Calculate the Data Entry Module Permissions for a given set of roles in a specific Agency. /// </summary> /// <param name="rolesInAgency">A set of roles in an Agency.</param> /// <param name="isSystemAdministrator">Calculations may differ for system administrators.</param> /// <returns></returns> private static List <DataEntryModulePermissions> CalculateDataEntryPermissionsGrantedByRoles(IGrouping <Guid, Role> rolesInAgency, bool isSystemAdministrator) { return(ModuleTypeInfo.ReportModules.Select(dataEntryModule => new DataEntryModulePermissions { // The Data Entry Module Type ModuleType = dataEntryModule, // Create is granted if the Identity is in any Role that has the Create Right for the specific Module Type. CreateGranted = rolesInAgency.Any( x => x.ModulePermissions.Any(y => y.ModuleType == dataEntryModule && y.Permissions.CanCreate)), // Delete is granted if the Identity is in any Role that has the Delete Right for the specific Module Type. DeleteGranted = rolesInAgency.Any( x => x.ModulePermissions.Any(y => y.ModuleType == dataEntryModule && y.Permissions.CanDelete)), // View is granted if the Identity is in any Role that has the View Right for the specific Module Type. ViewGranted = rolesInAgency.Any( x => x.ModulePermissions.Any(y => y.ModuleType == dataEntryModule && y.Permissions.CanView)), // Modify is granted if the Identity is in any Role that has the Modify Right for the specific Module Type. ModifyGranted = rolesInAgency.Any( x => x.ModulePermissions.Any(y => y.ModuleType == dataEntryModule && y.Permissions.CanModify)) }).ToList()); }
private ActionDTO SimplifyOperations(IGrouping <int, ActionDTO> g) { ActionDTO result; if (g.Any(a => a.ActionType == ActionType.Delete && g.Key > 0)) { result = new ActionDTO { Id = g.Key, ActionType = ActionType.Delete } } ; else if (g.Any(a => a.ActionType == ActionType.Add && g.Key < 0)) { var last = g.LastOrDefault(a => a.ActionType == ActionType.Modify); result = new ActionDTO { Id = g.Key, ActionType = ActionType.Add, Text = last?.Text, Date = last?.Date }; } else if (g.Key > 0) { var last = g.Last(a => a.ActionType == ActionType.Modify); result = new ActionDTO { Id = g.Key, ActionType = ActionType.Modify, Text = last.Text, Date = last.Date }; } else { throw new HttpResponseException(HttpStatusCode.BadRequest); } return(result); }
public void TagsCanBeVariant() { ILocalizationService languageService = LocalizationService; ILanguage language = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(language); // en-US is already there Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); ContentTypeService.Save(contentType); IContent content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.SetCultureName("name-fr", "fr-FR"); content1.SetCultureName("name-en", "en-US"); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags", "plus" }, culture: "fr-FR"); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "another", "one" }, culture: "en-US"); ContentService.SaveAndPublish(content1); content1 = ContentService.GetById(content1.Id); string[] frTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "fr-FR").ToArray(); Assert.AreEqual(5, frTags.Length); Assert.Contains("plus", frTags); Assert.AreEqual(-1, frTags.IndexOf("one")); string[] enTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "en-US").ToArray(); Assert.AreEqual(4, enTags.Length); Assert.Contains("one", enTags); Assert.AreEqual(-1, enTags.IndexOf("plus")); IEnumerable <IGrouping <int?, ITag> > tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); foreach (ITag tag in TagService.GetAllTags()) { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); } Assert.AreEqual(2, tagGroups.Count()); IGrouping <int?, ITag> frTagGroup = tagGroups.FirstOrDefault(x => x.Key == 2); Assert.IsNotNull(frTagGroup); Assert.AreEqual(5, frTagGroup.Count()); Assert.IsTrue(frTagGroup.Any(x => x.Text == "plus")); Assert.IsFalse(frTagGroup.Any(x => x.Text == "one")); IGrouping <int?, ITag> enTagGroup = tagGroups.FirstOrDefault(x => x.Key == 1); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); Assert.IsFalse(enTagGroup.Any(x => x.Text == "plus")); }
private IEnumerable <T> Dedup <T>(IGrouping <string, T> services, Func <T, bool> IsCancelled) { if (services.Any(s => IsCancelled(s)) && services.Any(s => !IsCancelled(s))) { return(services.Where(s => !IsCancelled(s))); } return(services); }
private static bool?ConvertIsGirl(IGrouping <string, NameWithDetailResult> group) { if (group.Any(detail => detail.IsGirl == true)) { return(true); } if (group.Any(detail => detail.IsGirl == false)) { return(false); } return(null); }
/// <summary> /// AI利用状況情報を更新する /// </summary> /// /// <param name="aiRiyouJoukyou">AI利用状況情報</param> /// /// private async Task UpdateAsync(IGrouping <string, dynamic> aiRiyouJoukyou) { if (!aiRiyouJoukyou.Any()) { return; } var first = aiRiyouJoukyou.Select(x => x).First(); int.TryParse(aiRiyouJoukyou.Key.Substring(0, 4), out int year); int.TryParse(aiRiyouJoukyou.Key.Substring(4, 2), out int month); var tunnelNumber = aiRiyouJoukyou.Count(); var souEnchou = aiRiyouJoukyou.Sum(x => x.tunnel.TunnelEnchou); AiRiyouJoukyouModel model = await GetAiRiyouJoukyouAsync(first.anken.CustomerId, first.anken.AnkenId, year, month); if (model.TunnelNumber != tunnelNumber || model.SouEnchou != souEnchou) { model.TunnelNumber = tunnelNumber; model.SouEnchou = souEnchou; model.UpdatedAt = DateTime.Now; _context.Entry(model).State = EntityState.Modified; } }
/// <summary> /// AI利用状況情報を追加する /// </summary> /// /// <param name="aiRiyouJoukyou">AI利用状況情報</param> /// /// private async Task InsertAsync(IGrouping <string, dynamic> aiRiyouJoukyou) { if (!aiRiyouJoukyou.Any()) { return; } var first = aiRiyouJoukyou.Select(x => x).First(); int.TryParse(aiRiyouJoukyou.Key.Substring(0, 4), out int year); int.TryParse(aiRiyouJoukyou.Key.Substring(4, 2), out int month); var tunnelNumber = aiRiyouJoukyou.Count(); var souEnchou = aiRiyouJoukyou.Sum(x => x.tunnel.TunnelEnchou); await _context.AiRiyouJoukyous.AddAsync(new AiRiyouJoukyouModel { CustomerId = first.anken.CustomerId, AnkenId = first.anken.AnkenId, Year = year, Month = month, TunnelNumber = tunnelNumber, SouEnchou = souEnchou, TankaId = 1, CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now }); }
public static Delivery MapToDelivery(this IGrouping <int, Message> groupedMessages) { var delivery = new Delivery(); if (!groupedMessages.Any()) { return(delivery); } delivery.PositionHistory = new List <Zuehlke.Camp2013.ConnectedVehicles.Position>(); delivery.StatusHistory = new List <DeliveryStatus>(); delivery.Vehicle = new Vehicle { VehicleId = groupedMessages.First().VehicleId, SensorHistory = new List <SensorData>() }; foreach (var message in groupedMessages) { delivery.PositionHistory.Add(message.MapToPosition()); if (message.Type == MessageType.STATUS) { delivery.StatusHistory.Add(message.MapToDeliveryStatus()); } if (message.Type == MessageType.SENSOR) { delivery.Vehicle.SensorHistory.Add(message.MapToSensorData()); } } return(delivery); }
/// <summary> /// Builds the class constructor. /// </summary> /// <param name="type">The type.</param> /// <param name="sb">The string builder.</param> /// <param name="options">The options.</param> private static void BuildClassConstructor(IGrouping <string, PropertyBag> type, StringBuilder sb, JsGeneratorOptions options) { if ( type.Any( p => (p.CollectionInnerTypes != null && p.CollectionInnerTypes.Any(q => !q.IsPrimitiveType)) || p.TransformablePropertyType == PropertyBag.TransformablePropertyTypeEnum.ReferenceType)) { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = function (cons, overrideObj) {{"); sb.AppendLine("\tif (!overrideObj) { overrideObj = { }; }"); sb.AppendLine("\tif (!cons) { cons = { }; }"); } else if (type.First().TypeDefinition.IsEnum) { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = {{"); } else { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = function (cons) {{"); sb.AppendLine("\tif (!cons) { cons = { }; }"); } }
/// <summary> /// Check that changes grouped by entity id belongs to website. /// </summary> /// <param name="groupedChanges">Changes grouped by entity id.</param> /// <param name="context">Crm DB context.</param> /// <param name="websiteId">Website id.</param> /// <returns></returns> private bool ChangesBelongsToWebsite(IGrouping <Guid, IChangedItem> groupedChanges, CrmDbContext context, Guid websiteId) { var entityId = groupedChanges.Key; var entityName = this.GetEntityNameFromChangedItem(groupedChanges.First()); if (string.Equals("adx_website", entityName, StringComparison.OrdinalIgnoreCase)) { return(websiteId == entityId); } // if entity hasn't relationship with website or entity was deleted -> mark as `belongs to website` EntityTrackingInfo info; if (groupedChanges.Any(gc => gc.Type == ChangeType.RemoveOrDeleted) || !entityInfoList.TryGetValue(entityName, out info) || info.WebsiteLookupAttribute == null) { return(true); } // trying to get website's id from changed items var itemWithWebsiteIdValue = groupedChanges .OfType <NewOrUpdatedItem>() .FirstOrDefault(item => item.NewOrUpdatedEntity.Contains(info.WebsiteLookupAttribute)); // if all changes doesn't contain website lookup attribute but we know that entity should have it then try to get value from service context var updatedEntity = itemWithWebsiteIdValue != null ? itemWithWebsiteIdValue.NewOrUpdatedEntity : context.Service.RetrieveSingle(new EntityReference(entityName, entityId), new ColumnSet(info.WebsiteLookupAttribute)); return(updatedEntity?.GetAttributeValue <EntityReference>(info.WebsiteLookupAttribute)?.Id == websiteId); }
public static List <Dictionary <int, List <T> > > Split <T>(this IGrouping <string, T> list, int?maxlength = 25) { if (list.Any()) { var aList = new List <T>(); var rList = new List <Dictionary <int, List <T> > >(); var seq = 1; var page = 1; foreach (var i in list) { aList.Add(i); if (seq == maxlength) { rList.Add(new Dictionary <int, List <T> >() { { page, aList } }); aList = new List <T>(); seq = 0; page++; } seq++; } rList.Add(new Dictionary <int, List <T> >() { { page, aList } }); return(rList); } return(new List <Dictionary <int, List <T> > >()); }
internal Album(IGrouping <string, SONG> album) { Name = album.Key.IsNullorEmpty() ? Consts.UnknownAlbum : album.Key; // uint value, use their max value DiscCount = album.Max(x => x.DiscCount); TrackCount = album.Max(x => x.TrackCount); Year = album.Max(x => x.Year); // TODO: not combine all, just use not-null value // string[] value, use their all value (remove duplicated values) combine AlbumArtists = (from aa in album where !aa.AlbumArtists.IsNullorEmpty() select aa.AlbumArtists).FirstOrDefault()?.Split(new string[] { Consts.ArraySeparator }, StringSplitOptions.RemoveEmptyEntries);//album.Where(x => !x.AlbumArtists.IsNullorEmpty()).FirstOrDefault().AlbumArtists; Genres = (from aa in album where !aa.Genres.IsNullorEmpty() select aa.Genres).FirstOrDefault()?.Split(new string[] { Consts.ArraySeparator }, StringSplitOptions.RemoveEmptyEntries); AlbumArtistsSort = (from aa in album where !aa.AlbumArtistsSort.IsNullorEmpty() select aa.AlbumArtistsSort).FirstOrDefault()?.Split(new string[] { Consts.ArraySeparator }, StringSplitOptions.RemoveEmptyEntries); // normal value, use their not-null value AlbumSort = (from aa in album where !aa.AlbumSort.IsNullorEmpty() select aa.AlbumSort).FirstOrDefault(); ReplayGainAlbumGain = (from aa in album where aa.ReplayGainAlbumGain != double.NaN select aa.ReplayGainAlbumGain).FirstOrDefault(); ReplayGainAlbumPeak = (from aa in album where aa.ReplayGainAlbumPeak != double.NaN select aa.ReplayGainAlbumPeak).FirstOrDefault(); PicturePath = (from aa in album where !aa.PicturePath.IsNullorEmpty() select aa.PicturePath).FirstOrDefault(); // songs, serialized as "ID0|ID1|ID2...|IDn" Songs = album.Select(x => x.ID).Distinct().ToArray(); IsOnedrive = album.Any(a => a.IsOneDrive); }
private void ShowItem(ChoiceActionItemCollection items, IGrouping <string, Type> CurrentModuleTypes) { foreach (ChoiceActionItem item in items) { item.ActiveItemsBehavior = ActiveItemsBehavior.Independent; if (item.Caption == "Default") { item.Active[HideReason] = true; } if (item.Model != null) { var NavItem = item.Model as IModelNavigationItem; if (NavItem.View != null) { //Debug.WriteLine(string.Format("{0}:{1}", " NavItem.View.Id", NavItem.View.Id)); //Debug.WriteLine(string.Format("{0}:{1}", " NavItem.View.GetType().FullName", NavItem.View.GetType().FullName)); var ListViewModel = NavItem.View as IModelListView; if (ListViewModel != null) { item.Active[HideReason] = CurrentModuleTypes.Any(types => types.FullName == ListViewModel.ModelClass.Name); Debug.WriteLine(string.Format("{0}:{1}", item.Caption, item.Active[HideReason])); } } } if (item.Items == null) { return; } ShowItem(item.Items, CurrentModuleTypes); } }
private static bool NodeDataGroupingIsNotEmpty(IGrouping <T, T> nodes) { if (nodes == null) { return(false); } return(nodes.Any()); }
private void CheckPropertyMergeability <T>(string propertyName, Func <Node, T> getter, IGrouping <string, Node> group) { var value = getter(group.First()); if (group.Any(n => EqualityComparer <T> .Default.Equals(getter(n), value) == false)) { throw new FormatException(string.Format("Inconsistency in partial state '{0}'. Property '{1}' does not match on all states.", group.Key, propertyName)); } }
private static Type GetArrayType(IGrouping <string, KeyValuePair <string, dynamic> > groupedProperties) { if (groupedProperties.Any(x => x.Value is string[])) { return(typeof(string)); } if (groupedProperties.Any(x => x.Value is int[])) { return(typeof(int)); } if (groupedProperties.Any(x => x.Value is float[])) { return(typeof(float)); } return(null); }
/// <summary> /// Validates a group of operations with the same context Uri. /// </summary> /// <param name="operations">Operations to validate.</param> private void ValidateOperationMetadataGroup(IGrouping <string, ODataOperation> operations) { Debug.Assert(operations != null, "operations must not be null."); Debug.Assert(operations.Any(), "operations.Any()"); Debug.Assert(operations.All(o => this.GetOperationMetadataString(o) == operations.Key), "The operations should be grouped by their metadata."); if (operations.Count() > 1 && operations.Any(o => o.Target == null)) { throw new ODataException(Strings.ODataJsonLightResourceSerializer_ActionsAndFunctionsGroupMustSpecifyTarget(operations.Key)); } foreach (IGrouping <string, ODataOperation> operationsByTarget in operations.GroupBy(this.GetOperationTargetUriString)) { if (operationsByTarget.Count() > 1) { throw new ODataException(Strings.ODataJsonLightResourceSerializer_ActionsAndFunctionsGroupMustNotHaveDuplicateTarget(operations.Key, operationsByTarget.Key)); } } }
internal static Scope ToModel(this IGrouping <DbScope, DbScopeClaim> scopeAndClaims) { var scope = Mapper.Map <Scope>(scopeAndClaims.Key); if (scopeAndClaims.Any(x => x != null)) { scope.Claims = scopeAndClaims.Where(x => x != null).Select(Mapper.Map <ScopeClaim>).ToList(); } return(scope); }
public GroupedChunkSubKeys(IGrouping <ulong, LevelDbWorldKey2> groupedSubChunks) { if (!groupedSubChunks.Any()) { throw new ArgumentOutOfRangeException(nameof(groupedSubChunks)); } foreach (var sc in groupedSubChunks) { Subchunks.Add(sc.SubChunkId, sc); } }
private List <PokemonData> GetPokemonByIV(IGrouping <PokemonId, PokemonData> pokemon, int amount) { if (!pokemon.Any()) { return(new List <PokemonData>()); } //Test out first one to make sure things are correct double perfectResult = CalculateIVPerfection(pokemon.First()); return(pokemon.OrderByDescending(x => CalculateIVPerfection(x)).ThenByDescending(x => x.Cp).Skip(amount).ToList()); }
private AgencyPermissions CalculateAgencyPermissionsFromRoles(IGrouping <Guid, Role> rolesInAgency, bool isAdministrator) { return(new AgencyPermissions { // the group key is the id of the Agency. AgencyId = rolesInAgency.Key, // Admin Rights are granted if the identity is in ANY role that has the Agency Admin Right. // Or if the identity is a System Administrator AdministrationGranted = rolesInAgency.Any(x => x.AgencyPermissions.IsAgencyAdmin) || isAdministrator, // Report Administration is Granted if the identity is in any role that has the ReportAdmin right. ReportAdministrationGranted = rolesInAgency.Any(x => x.AgencyPermissions.IsReportAdmin), // Designer Permissions must be granted by at least one role in the Agency DesignerPermissions = CalculateDesignerPermissionsGrantedByRoles(rolesInAgency, isAdministrator), // Calculate the Permissions for all Data Entry Modules DataEntryModulePermissions = CalculateDataEntryPermissionsGrantedByRoles(rolesInAgency, isAdministrator) }); }
private bool HasDefaultBrowsableCategory(IGrouping <XmlNode, XmlNode> parentCategories) { return(parentCategories.Any((categoryNode) => { var node = categoryNode.Attributes.GetNamedItem("name", AndroidNamespaceUri); return ( node != null && (node.Value == "android.intent.category.DEFAULT" || node.Value == "android.intent.category.BROWSABLE") ); })); }
private List <StudentAbsenceDaysModel> CalculateLastWeekDays(List <DateTime> calendarDates, IGrouping <object, StudentAbsencesForEmails> g) { var days = new List <StudentAbsenceDaysModel>(); foreach (var day in calendarDates) { days.Add(new StudentAbsenceDaysModel { Date = day, Absent = g.Any(x => x.EventDate.Date == day) }); } return(days); }
public static ChatThreadViewModel FromDb(IGrouping <int, Chat> thread, string userId, int studentId) { ChatThreadViewModel model = new ChatThreadViewModel() { Id = thread.Last().Id, Title = thread.Last().Title, AddedAt = thread.Last().AddedAt.ToString("dd.MM.yyyy HH:mm:ss") }; if (!string.IsNullOrEmpty(userId)) { model.IsRead = thread.Any(t => t.ReceiverUserId == userId) ? thread.OrderBy(t => t.AddedAt).Last(t => t.ReceiverUserId == userId).IsRead : true; if (thread.Last().SenderUserId == userId) { model.Author = thread.Last().ReceiverUser != null?thread.Last().ReceiverUser.FirstName + " " + thread.Last().ReceiverUser.LastName : thread.Last().ReceiverStudent.FirstName + " " + thread.Last().ReceiverStudent.LastName; } else if (thread.Last().ReceiverUserId == userId) { model.Author = thread.Last().SenderUser != null?thread.Last().SenderUser.FirstName + " " + thread.Last().SenderUser.LastName : thread.Last().SenderStudent.FirstName + " " + thread.Last().SenderStudent.LastName; } } if (studentId != 0) { model.IsRead = thread.Any(t => t.ReceiverStudentId == studentId) ? thread.OrderBy(t => t.AddedAt).Last(t => t.ReceiverStudentId == studentId).IsRead : true; if (thread.Last().SenderStudentId == studentId) { model.Author = thread.Last().ReceiverStudent != null?thread.Last().ReceiverStudent.FirstName + " " + thread.Last().ReceiverStudent.LastName : thread.Last().ReceiverUser.FirstName + " " + thread.Last().ReceiverUser.LastName; } else if (thread.Last().ReceiverStudentId == studentId) { model.Author = thread.Last().SenderStudent != null?thread.Last().SenderStudent.FirstName + " " + thread.Last().SenderStudent.LastName : thread.Last().SenderUser.FirstName + " " + thread.Last().SenderUser.LastName; } } return(model); }
private SensorGroup QueryVirtual(IGrouping <int, DataRow> item) { if (!item.Any()) { return(null); } var agroup = new SensorGroup(item.Key, GroupType.VirtualSensor); DataRow row = item.First(); // 虚拟传感器的分组信息(公式、参数、子集) agroup.FormulaId = row["FORMAULAID"] == DBNull.Value ? -1 : Convert.ToInt32(row["FORMAULAID"]); agroup.FactorTypeId = row["SAFETY_FACTOR_TYPE_ID"] == DBNull.Value ? -1 : Convert.ToInt32(row["SAFETY_FACTOR_TYPE_ID"]); agroup.FactorTypeTable = row["THEMES_TABLE_NAME"] == DBNull.Value ? "" : Convert.ToString(row["THEMES_TABLE_NAME"]); agroup.TableColums = row["THEMES_COLUMNS"] == DBNull.Value ? "" : Convert.ToString(row["THEMES_COLUMNS"]); int paraIndex = 1; while (!row.IsNull("Parameter" + paraIndex)) { agroup.FormulaParams.Add(Convert.ToDouble(row["Parameter" + paraIndex])); paraIndex++; } foreach (DataRow dr in item) { if (!dr.IsNull("CorrentSensorId")) { agroup.AddItem(new GroupItem { SensorId = Convert.ToInt32(dr["CorrentSensorId"]), DtuId = Convert.ToUInt32(dr["VDTU_ID"]) }); } } // 虚拟传感器的基础信息 var virtualSensor = new Sensor { DtuID = Convert.ToUInt32(row["DTU_ID"]), SensorID = Convert.ToUInt32(row["SENSOR_ID"]), FormulaID = row.IsNull("FORMAULAID") ? 0 : Convert.ToUInt32(row["FORMAULAID"]), FactorType = Convert.ToUInt32(row["SAFETY_FACTOR_TYPE_ID"]), ProtocolType = row.IsNull("PROTOCOL_ID") ? 0 : Convert.ToUInt32(row["PROTOCOL_ID"]), FactorTypeTable = Convert.ToString(row["THEMES_TABLE_NAME"]), TableColums = Convert.ToString(row["THEMES_COLUMNS"]), SensorType = SensorType.Virtual, StructId = Convert.ToUInt32(row["STRUCT_ID"]) }; agroup.VirtualSensor = virtualSensor; return(agroup); }
public void TagsCanBeInvariant() { Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); IContent content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "another", "one" }); ContentService.SaveAndPublish(content1); content1 = ContentService.GetById(content1.Id); string[] enTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); Assert.AreEqual(4, enTags.Length); Assert.Contains("one", enTags); Assert.AreEqual(-1, enTags.IndexOf("plus")); IEnumerable <IGrouping <int?, ITag> > tagGroups = TagService.GetAllTags().GroupBy(x => x.LanguageId); foreach (ITag tag in TagService.GetAllTags()) { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); } Assert.AreEqual(1, tagGroups.Count()); IGrouping <int?, ITag> enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); Assert.IsFalse(enTagGroup.Any(x => x.Text == "plus")); }
public int CalculateSpecialPrice(SpecialPrice specialPrice, IGrouping <string, Product> grouping) { var result = 0; var groupCount = grouping.Count() - specialPrice.Quantity; //1- No Special price, just add standard price if (groupCount < 0) { result += grouping.Sum(g => g.Price); return(result); } //2- Scanned items exactly equals special price quantity. if (grouping != null && grouping.Count() == groupCount) { result += specialPrice.Price; var group = grouping.FirstOrDefault(); if (group != null) { result += groupCount * group.Price; } return(result); } //3- Scanned items > special price quantity & < twice the special price quantity result += specialPrice.Price; if (grouping != null && !grouping.Any()) { return(result); } //4- Scanned items > twice the special price quantity var discountedGroups = groupCount / specialPrice.Quantity; var nonDiscountedPrice = groupCount % specialPrice.Quantity; if (discountedGroups > 0) { result += discountedGroups * specialPrice.Price; } var product = grouping?.FirstOrDefault(); if (product != null) { result += nonDiscountedPrice * product.Price; } return(result); }
/// <summary> /// Calculate the /// </summary> /// <param name="rolesInAgency"></param> /// <param name="isSystemAdministrator"></param> /// <returns></returns> private static List <DesignerPermissions> CalculateDesignerPermissionsGrantedByRoles(IGrouping <Guid, Role> rolesInAgency, bool isSystemAdministrator) { // Calculate Admin Designer Permissions return(new List <DesignerPermissions> { // Data Entry Designer new DesignerPermissions { // Granted if the identity is in any role that has the Data Entry Designer right. // Or if the account is a system administrator AccessGranted = rolesInAgency.Any(x => x.AgencyPermissions.CanAccessDataEntryDesigner) || isSystemAdministrator, DesignerType = ModuleType.DataEntryDesigner }, // Workflow Designer new DesignerPermissions { // Granted if the identity is in any role that has the Workflow Designer right. // Or if the account is a system administrator AccessGranted = rolesInAgency.Any(x => x.AgencyPermissions.CanAccessWorkflowDesigner) || isSystemAdministrator, DesignerType = ModuleType.WorkflowDesigner } }); }
public MutableGrouping(IGrouping <TKey, TElement> grouping) { if (grouping == null) { throw new ArgumentNullException("grouping"); } if (!grouping.Any()) { return; } Key = grouping.Key; AddRange(grouping); }
private static IPlugin FindMaxVersionPlugin(IGrouping<string, IPlugin> plugins) { Debug.Assert(plugins.Any()); var maxVersionPlugin = plugins.First(); foreach (var plugin in plugins) { if (maxVersionPlugin.Version.CompareTo(plugin.Version) == -1) { LogManager.Warning(String.Format("Found previous version of plugin. Current version:" + PluginTostring(plugin) + " Previous version: " + PluginTostring(maxVersionPlugin))); maxVersionPlugin = plugin; } else { if (maxVersionPlugin != plugin) { LogManager.Warning(String.Format("Found previous version of plugin. Current version: " + PluginTostring(maxVersionPlugin) +" Previous version: " + PluginTostring(plugin))); } } } return maxVersionPlugin; }
private async Task Run(IGrouping<string, Series> group, bool addNewItems, CancellationToken cancellationToken) { var tvdbId = group.Key; // Todo: Support series by imdb id var seriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); seriesProviderIds[MetadataProviders.Tvdb.ToString()] = tvdbId; var seriesDataPath = TvdbSeriesProvider.GetSeriesDataPath(_config.ApplicationPaths, seriesProviderIds); var episodeFiles = Directory.EnumerateFiles(seriesDataPath, "*.xml", SearchOption.TopDirectoryOnly) .Select(Path.GetFileNameWithoutExtension) .Where(i => i.StartsWith("episode-", StringComparison.OrdinalIgnoreCase)) .ToList(); var episodeLookup = episodeFiles .Select(i => { var parts = i.Split('-'); if (parts.Length == 3) { int seasonNumber; if (int.TryParse(parts[1], NumberStyles.Integer, _usCulture, out seasonNumber)) { int episodeNumber; if (int.TryParse(parts[2], NumberStyles.Integer, _usCulture, out episodeNumber)) { return new Tuple<int, int>(seasonNumber, episodeNumber); } } } return new Tuple<int, int>(-1, -1); }) .Where(i => i.Item1 != -1 && i.Item2 != -1) .ToList(); var hasBadData = HasInvalidContent(group); var anySeasonsRemoved = await RemoveObsoleteOrMissingSeasons(group, episodeLookup) .ConfigureAwait(false); var anyEpisodesRemoved = await RemoveObsoleteOrMissingEpisodes(group, episodeLookup) .ConfigureAwait(false); var hasNewEpisodes = false; if (addNewItems && !group.Any(i => !i.IsInternetMetadataEnabled())) { var seriesConfig = _config.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, typeof(Series).Name, StringComparison.OrdinalIgnoreCase)); if (seriesConfig == null || !seriesConfig.DisabledMetadataFetchers.Contains(TvdbSeriesProvider.Current.Name, StringComparer.OrdinalIgnoreCase)) { hasNewEpisodes = await AddMissingEpisodes(group.ToList(), hasBadData, seriesDataPath, episodeLookup, cancellationToken) .ConfigureAwait(false); } } if (hasNewEpisodes || anySeasonsRemoved || anyEpisodesRemoved) { foreach (var series in group) { var directoryService = new DirectoryService(_logger, _fileSystem); await series.RefreshMetadata(new MetadataRefreshOptions(directoryService), cancellationToken).ConfigureAwait(false); await series.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(directoryService), true) .ConfigureAwait(false); } } }
private static bool AllContentDeleted(IGrouping<DeletedParagraphCollectionType, BlockContentInfo> g) { var someNotDeleted = g.Any(b => ! AllParaContentIsDeleted(b.ThisBlockContentElement)); return ! someNotDeleted; }
public ActivityEditorVm( Model.Task task, Dal.SoheilEdmContext uow, IGrouping<Model.Activity, Model.StateStationActivity> ssaGroup) : base(ssaGroup.Key) { Message = new Common.SoheilException.EmbeddedException(); if (!ssaGroup.Any()) { Message.AddEmbeddedException("فعالیتی وجود ندارد"); return; } //make ProcessList self-aware of all changes ProcessList.CollectionChanged += (s, e) => { if (e.NewItems != null) foreach (ProcessEditorVm processVm in e.NewItems) { ProcessList_Added(processVm); } }; //Add Choices foreach (var choice in ssaGroup.OrderBy(ssa => ssa.ManHour)) { Choices.Add(new ChoiceEditorVm(choice)); } //Add existing processes foreach (var process in task.Processes.Where(x => x.StateStationActivity.Activity.Id == ssaGroup.Key.Id)) { ProcessList.Add(new ProcessEditorVm(process, Model, uow)); } //Add process command AddProcessCommand = new Commands.Command(o => { DateTime dt; if (GetTaskStart == null) dt = ProcessList.Any() ? ProcessList .Where(x => x.ActivityModel.Id == ssaGroup.Key.Id) .Max(x => x.Model.EndDateTime) : task.StartDateTime; else dt = GetTaskStart(); var minMH = ssaGroup.Min(x => x.ManHour); var processVm = new ProcessEditorVm( new Model.Process { StartDateTime = dt, EndDateTime = dt, StateStationActivity = ssaGroup.First(x=>x.ManHour == minMH), TargetCount = 0, Task = task, }, Model, uow);//activity Model is set here ProcessList.Add(processVm); processVm.IsSelected = true; }); }
/// <summary> /// Builds the class constructor. /// </summary> /// <param name="type">The type.</param> /// <param name="sb">The string builder.</param> /// <param name="options">The options.</param> private static void BuildClassConstructor(IGrouping<string, PropertyBag> type, StringBuilder sb, JsGeneratorOptions options) { if ( type.Any( p => (p.CollectionInnerTypes != null && p.CollectionInnerTypes.Any(q => !q.IsPrimitiveType)) || p.TransformablePropertyType == PropertyBag.TransformablePropertyTypeEnum.ReferenceType)) { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = function (cons, overrideObj) {{"); sb.AppendLine("\tif (!overrideObj) { overrideObj = { }; }"); sb.AppendLine("\tif (!cons) { cons = { }; }"); } else if (type.First().TypeDefinition.IsEnum) { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = {{"); } else { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = function (cons) {{"); sb.AppendLine("\tif (!cons) { cons = { }; }"); } }
/// <summary> /// Validates a group of operations with the same context Uri. /// </summary> /// <param name="operations">Operations to validate.</param> private void ValidateOperationMetadataGroup(IGrouping<string, ODataOperation> operations) { Debug.Assert(operations != null, "operations must not be null."); Debug.Assert(operations.Any(), "operations.Any()"); Debug.Assert(operations.All(o => this.GetOperationMetadataString(o) == operations.Key), "The operations should be grouped by their metadata."); if (operations.Count() > 1 && operations.Any(o => o.Target == null)) { throw new ODataException(OData.Core.Strings.ODataJsonLightEntryAndFeedSerializer_ActionsAndFunctionsGroupMustSpecifyTarget(operations.Key)); } foreach (IGrouping<string, ODataOperation> operationsByTarget in operations.GroupBy(this.GetOperationTargetUriString)) { if (operationsByTarget.Count() > 1) { throw new ODataException(OData.Core.Strings.ODataJsonLightEntryAndFeedSerializer_ActionsAndFunctionsGroupMustNotHaveDuplicateTarget(operations.Key, operationsByTarget.Key)); } } }