public void AddFiles(DroneConfig config, IList<string> sourceFiles, IList<string> referenceFiles) { if(config == null) throw new ArgumentNullException("config"); if(sourceFiles == null) throw new ArgumentNullException("sourceFiles"); if(referenceFiles == null) throw new ArgumentNullException("referenceFiles"); var sourcesToAdd = sourceFiles.Except(config.SourceFiles).ToList(); var referencesToAdd = referenceFiles.Except(config.ReferenceFiles).ToList(); if (sourcesToAdd.Count == 0 && referencesToAdd.Count == 0) { this.log.Warn("no files added. files already exists in config"); return; } var fileNotFound = this.EnsureFilesExists(config.DirPath, sourcesToAdd.Concat(referencesToAdd)); if (fileNotFound) return; config.SourceFiles.AddRange(sourcesToAdd); config.ReferenceFiles.AddRange(referencesToAdd); foreach (var file in sourcesToAdd.Concat(referencesToAdd)) this.log.Info("added '{0}'", file); }
/// Assuming that excludeGroup is small public void Send(Packet packet, IList<NetNode> sendToList, IList<NetNode> excludeGroup, int channel = 0) { var msg = packet.SendMessage(this); var group = sendToList.Except(excludeGroup).Cast<NetConnection>().ToList(); if (group.Count == 0) return; Peer.SendMessage(msg, group, (Lidgren.Network.NetDeliveryMethod)packet.Method, channel); }
public UserHistoryEntry Analyze(DateTime date, IList<long> before, IList<long> after) { var gainedIds = after.Except(before); var lostIds = before.Except(after); var allProfiles = parser.WhoAre(gainedIds.Concat(lostIds)).ToLookup(x => x.Id); var gained = Separate(gainedIds, allProfiles); var lost = Separate(lostIds, allProfiles); return new UserHistoryEntry(date, gained, lost, after.Count); }
public void UpdateProjects(IList<string> newProjects) { var oldProjects = Projects.Select(x => x.ProjectFilePath).ToList(); foreach (var i in newProjects.Except(oldProjects)) { Projects.Add(new UploadProjectInfo(i)); } foreach (var i in oldProjects.Except(newProjects)) { Projects.RemoveAll(x => x.ProjectFilePath == i); } }
public static List<int[]> ChooseSets(IList<int[]> sets, IList<int> universe) { var selectedSets = new List<int[]>(); while (universe.Count > 0) { var currentSet = sets.OrderByDescending(s => s.Count(universe.Contains)).First(); selectedSets.Add(currentSet); sets.Remove(currentSet); universe = universe.Except(currentSet).ToList(); } return selectedSets; }
public async Task SaveManga(IList<JsonManga> mangas) { if (mangas == null) throw new ArgumentNullException("mangas"); _logger.Trace("Saving " + mangas.Count() + " mangas to database..."); using (MangaEdenContext context = new MangaEdenContext()) { List<JsonManga> existing = await context.Mangas.ToListAsync(); context.Mangas.AddRange(mangas.Except(existing, new JsonMangaComparer())); await context.SaveChangesAsync(); _logger.Trace("Saved."); } }
public static IList<string> ProcessWatchers(this IBot bot, string repositoryName, IList<string> existingWatchers, IEnumerable<dynamic> watchers) { var currentWatchers = watchers.Select(c => c.login.ToString()).Cast<string>().ToList(); var newWatchers = currentWatchers.Except(existingWatchers).ToList(); foreach (var w in newWatchers) { bot.SayToAllRooms(string.Format("{0} is now watching {1}", w, repositoryName)); } var noLongerWatching = existingWatchers.Except(currentWatchers).ToList(); foreach (var w in noLongerWatching) { bot.SayToAllRooms(string.Format("{0} is no longer watching {1}", w, repositoryName)); } return existingWatchers.Concat(newWatchers).Except(noLongerWatching).ToList(); }
/// <summary> /// Update the project file with the given references. Only change the file if /// there would be an actual change tot he file required /// </summary> /// <param name="references"></param> /// <returns>true if the project file was updated</returns> internal bool UpdateReferences(IList<Reference> references) { var xmlDoc = ReadXML(); var existing = ReadReferences(xmlDoc).Where((r)=>r.HintPath != null).ToList(); var update = existing.Count != references.Count; if (!update) { update = existing.Except(references).ToList().Count > 0; } if (!update) { update = references.Except(existing).ToList().Count > 0; } if (update) { WriteReferences(xmlDoc,references); return true; } return false; }
public SourceCreatorTreeNode(ISourceFactory factory, Type baseType, IList<Type> creatorTypes) { m_type = baseType; if (!m_type.IsAbstract) { m_instance = Activator.CreateInstance(m_type, factory) as ISourceCreator; m_instance.Init(); } var childCreatorTypes = creatorTypes.Where(t => t.BaseType == m_type).ToList(); if (childCreatorTypes.Count > 0) { // remove children from search creatorTypes = creatorTypes.Except(childCreatorTypes).ToList(); m_childCreatorNodes = childCreatorTypes.Select(t => new SourceCreatorTreeNode(factory, t, creatorTypes)).ToList(); } }
private void LoadSelectionZones() { var results = new List <TimeZoneSelectionData>(); var precedence = File.ReadAllLines(@"data\zone-precedence.txt"); var splitPoints = GetAllZoneSplitPoints(); IList <string> last = null; var useConsole = TryHideConsoleCursor(); for (int i = splitPoints.Count - 1; i >= 0; i--) { if (useConsole) { var pct = 100 * (1.0 * (splitPoints.Count - i)) / splitPoints.Count; Console.Write("{0:F1}%", pct); Console.CursorLeft = 0; } var point = splitPoints[i]; var zones = GetSelectionZones(point, precedence); if (last == null) { last = zones; continue; } var items = zones.Except(last) .Select(x => new TimeZoneSelectionData { Id = x, ThresholdUtc = point.ToDateTimeUtc() }); results.AddRange(items); last = zones; } var remaining = last?.Except(results.Select(x => x.Id)); if (remaining != null) { var items = remaining .Select(x => new TimeZoneSelectionData { Id = x, ThresholdUtc = DateTime.MaxValue }); results.AddRange(items); } _data.SelectionZones.AddRange(results .OrderBy(x => GetStandardOffset(x.Id)) .ThenBy(x => GetDaylightOffset(x.Id)) .ThenByDescending(x => x.ThresholdUtc) .ThenBy(x => x.Id)); if (useConsole) { Console.WriteLine(); Console.CursorVisible = true; } }
// ReSharper disable UnusedParameter.Local private void AssertParameterRule( Func<string, Type, string, IArgumentNullExceptionFixture> addMethod, ParameterInfo parameter, Type type, MethodBase method, IList<RegexRule> existingRules, IList<RegexRule> regexRules, bool expectedInclude) { IArgumentNullExceptionFixture actual = addMethod(parameter.Name, type, method == null ? null : method.Name); int expectedRules = existingRules.Count + 1; if (expectedInclude && method != null) expectedRules++; if (expectedInclude && type != null) expectedRules++; Assert.Same(addMethod.Target, actual); Assert.Equal(expectedRules, regexRules.Count); Assert.False(existingRules.Except(regexRules).Any()); RegexRule addedRule = regexRules.Except(existingRules).Single(r => r.Parameter != null); Assert.Equal(expectedInclude, addedRule.Include); Assert.NotNull(addedRule.Parameter); Assert.True(addedRule.MatchParameter(type ?? GetType(), method ?? new Mock<MethodBase>().Object, parameter)); if (type == null) { Assert.Null(addedRule.Type); } else { Assert.NotNull(addedRule.Type); Assert.True(addedRule.MatchType(type)); } if (method == null) { Assert.Null(addedRule.Method); } else { Assert.NotNull(addedRule.Method); Assert.True(addedRule.MatchMethod(type ?? GetType(), method)); } }
public bool IsDuplicate(IList <TriageItem> openedIssueItems, IList <TriageItem> existingIssueItems) { return(existingIssueItems.Count == openedIssueItems.Count && !existingIssueItems.Except(openedIssueItems).Any()); }
private static bool ContainSameFeatures(IList <IFeature> list1, IList <IFeature> list2) { return(!list1.Except(list2).Any() && !list2.Except(list1).Any()); }
private void btnSave_Click(object sender, EventArgs e) { try { WarehouseIn objW = new WarehouseIn(); objW.Id = WarehouseInId; objW.Vender = txtVendor.Text.Trim(); objW.ReceivedBy = txtReceivedBy.Text.Trim(); objW.AuditBy = txtAuditBy.Text.Trim(); objW.BillDate = dtBillDate.Value.ClearTime(); objW.ReviewedBy = txtReviewedBy.Text.Trim(); if (objW.ReceivedBy == objW.ReviewedBy) { MessageBox.Show("收货人与复核人不能是同一个人!", "提示"); return; } IList <WarehouseInItem> lst = (gridIn.DataSource as BindingSource).DataSource as IList <WarehouseInItem>; //foreach (DataGridViewRow row in gridIn.Rows) //{ // WarehouseInItem item = new WarehouseInItem(); // item.Id = Convert.ToInt32(row.Cells["Id"].Value); // item.Product_Id = Convert.ToInt32(row.Cells["ProductName"].Value); // item.ProductName = Convert.ToString(row.Cells["ProductName"].FormattedValue); // item.Brand = Convert.ToString(row.Cells["Brand"].Value); // item.Specification = Convert.ToString(row.Cells["Specification"].Value); // item.Unit = Convert.ToString(row.Cells["Unit"].Value); // item.Memo = Convert.ToString(row.Cells["Memo"].Value); // item.Quantity = Convert.ToDouble(row.Cells["Quantity"].Value); // item.UnitPrice = Convert.ToDouble(row.Cells["UnitPrice"].Value); // if (item.Quantity > 0) // lst.Add(item); //} IList <int> needDelItem = new List <int>(); var oldItem = (new Entities()).WarehouseInItem.Where(item => item.WarehouseIn_Id == WarehouseInId).ToList(); if (WarehouseInId > 0) { IList <int> lstId = oldItem.Where(item => item.WarehouseIn_Id == WarehouseInId).Select(d => d.Id).ToList(); needDelItem = lstId.Except(lst.Where(item => item.Id > 0 && item.Quantity > 0 && item.Product_Id > 0).Select(item => item.Id).ToList()).ToList(); } using (TransactionScope scope = new TransactionScope()) { entities.Save <WarehouseIn>(objW); foreach (WarehouseInItem item in lst) { if (item.Quantity <= 0 || item.Product_Id <= 0) { continue; } double changedQty = item.Quantity; item.WarehouseIn_Id = objW.Id; if (item.Id > 0) { var temp = oldItem.First(tmp => tmp.Id == item.Id); changedQty = item.Quantity - temp.Quantity; } entities.Save <WarehouseInItem>(item); var product = entities.Product.Find(item.Product_Id); product.StockQuantity = product.StockQuantity + changedQty; entities.Save <Product>(product); } if (needDelItem.Count > 0) { var delItems = oldItem.Where(tmp => needDelItem.Contains(tmp.Id)); var temp = from t in delItems group t by t.Product_Id into tt select new { ProductId = tt.Key, Quantity = tt.Sum(x => x.Quantity) }; foreach (var t1 in temp) { var product = entities.Product.Find(t1.ProductId); product.StockQuantity = product.StockQuantity - t1.Quantity; entities.Save <Product>(product); } entities.Delete <WarehouseInItem>(needDelItem); } scope.Complete(); } MessageBox.Show("数据保存成功!", "提示"); this.Close(); } catch (Exception exp) { MessageBox.Show("数据保存失败!", "提示"); LogHelper.WriteLog(LogType.Error, exp, this.GetType()); } }
protected override void FillHollow(IList <Vector2Int32> area, IList <Vector2Int32> interrior) { IEnumerable <Vector2Int32> border = area.Except(interrior); }
public void AddPhotos(IList<string> paths) { if (paths.Count + this.Photos.Count > MaxPhotoUploadLimit) { this.WarningMessage = string.Format(CultureInfo.CurrentUICulture, Resources.MaxUploadWarning, MaxPhotoUploadLimit); } else { try { this.IsProcessingPhotos = true; Task.Factory.StartNew( () => paths.Except(this.photoPaths).Select(path => Photo.BuildPhotoFromPath(path)).ToArray(), CancellationToken.None) .ContinueWith( photoTask => { this.IsProcessingPhotos = false; foreach (var photo in photoTask.Result) { this.Photos.Add(photo); } }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); } catch { this.IsProcessingPhotos = false; } } }
private bool ValidateGrammar(IList<string> terminals, IList<Production> productions) { var declaredNonTerminals = productions.Select(x => x.ProductionHead).Distinct().ToList(); var grammarSymbolsInTails = productions.SelectMany(x => x.ProductionTail).Distinct().ToList(); //check if there are any declared terminals that are used //as the head of a production. var v = terminals.Intersect(declaredNonTerminals).ToList(); if(v.Count > 0) { return false; } //check if there are any symbols used in a production that are not a terminal //and are not the head of some production. v = grammarSymbolsInTails.Except(terminals).Except(declaredNonTerminals).ToList(); if(v.Count > 0) { return false; } //check if there are any declared terminals that are not used in any production. v = terminals.Except(grammarSymbolsInTails).ToList(); if(v.Count > 0) { return false; } //check that there is only one nonterminal that does not appear in a production //this nonterminal is the root of the grammar. v = declaredNonTerminals.Except(grammarSymbolsInTails).ToList(); if(v.Count != 1) { return false; } return false; }
public static bool IsSubset <T>(IList <T> subset, IList <T> superset) { return(!subset.Except(superset).Any()); }
public static bool SequenceEqualAnyOrder <TSource>(this IList <TSource> first, IList <TSource> second) { return(first.Count == second.Count && !first.Except(second).Any()); }
//================================================================================================= private static void RunTiaPortal() { #region tia and project Progress("Check running TIA Portal"); bool tiaStartedWithoutInterface = false; Service.OpenProject(Parameters.ProjectPath, ref tiaPortal, ref project); if ((tiaPortal == null) || (project == null)) { CancelGeneration("Could not open project."); return; } Progress(String.Format("Project {0} is open", project.Path.FullName)); #endregion #region test models /* * Console.WriteLine("!!! TESTING !!!"); * DeviceUserGroup testGroup = project.DeviceGroups.Find(Parameters.TemplateGroupName); * ManagePlc testPlcs = new ManagePlc(testGroup); * * * NetworkPort testPlcPort = testPlcs.AllDevices[0].DeviceItems[1].DeviceItems[6].DeviceItems[0].GetService<NetworkPort>(); * NetworkPort patnerPort = testPlcPort.ConnectedPorts[0]; * * AttributeValue thisname = Service.GetAttribute(patnerPort, "Name"); * * testPlcPort.DisconnectFromPort(patnerPort); * testPlcPort.ConnectToPort(patnerPort); */ #endregion #region master copy Progress("Creating master copy."); DeviceUserGroup templateGroup = project.DeviceGroups.Find(Parameters.TemplateGroupName); if (templateGroup == null) { CancelGeneration("Group not found."); return; } //=======copy to master copy======== //MasterCopyComposition masterCopies = project.ProjectLibrary.MasterCopyFolder.MasterCopies; MasterCopy templateCopy = null; try { templateCopy = project.ProjectLibrary.MasterCopyFolder.MasterCopies.Create(templateGroup); } catch (Exception ex) { CancelGeneration("Could not create master copy.", ex); return; } if (templateCopy == null) { CancelGeneration("Could not create master copy."); return; } MasterCopy deleteMasterCopy = project.ProjectLibrary.MasterCopyFolder.MasterCopies.Find(templateCopy.Name); #endregion #region get basic info from template group IList <Device> templatePlcDevices = Service.GetPlcDevicesInGroup(templateGroup); ManagePlc templatePlcs = new ManagePlc(templatePlcDevices); templatePlcs.GetAll_iDeviceParnerIoAdresses(); if (templatePlcs.AllDevices.Count != 1) { CancelGeneration("No PLC or more than 1 PLC in group."); return; } #endregion #region change name and IP of first group (template Group) string indexformat = "D2"; uint groupCounter = 1; Progress("Adjusting template group."); string currentPrefix = Parameters.Prefix + groupCounter.ToString(indexformat); //templateGroup.Name = templateGroup.Name + groupCounter.ToString(indexformat); templateGroup.Name = Parameters.NewGroupNamePrefix + groupCounter.ToString(indexformat); //templateNetworkInterface.IoControllers[0].IoSystem.Name = currentPrefix + temlateIoSystemName; Service.ChangeDeviceNames(templateGroup, currentPrefix); templatePlcs.ChangeIoSystemName(currentPrefix); #endregion #region copy group loop DeviceUserGroupComposition userGroups = project.DeviceGroups; while (++groupCounter <= Parameters.NumOfGroups) { #region copy group Progress("Creating Group " + groupCounter); currentPrefix = Parameters.Prefix + groupCounter.ToString(indexformat); DeviceUserGroup newGroup; try { newGroup = userGroups.CreateFrom(templateCopy); } catch (Exception e) { CancelGeneration("Could not create new Group", e); return; } #endregion #region read in devices //newGroup.Name = newGroup.Name + groupCounter.ToString(indexformat); ; newGroup.Name = Parameters.NewGroupNamePrefix + groupCounter.ToString(indexformat);; Service.ChangeDeviceNames(newGroup, currentPrefix); IList <Device> plcDevices = Service.GetPlcDevicesInGroup(newGroup); ManagePlc plcs = new ManagePlc(plcDevices); IList <Device> hmiDevices = Service.GetHmiDevicesInGroup(newGroup); ManageHmi hmis = new ManageHmi(hmiDevices); IList <Device> driveDevices = Service.GetG120DevicesInGroup(newGroup); ManageDrive drives = new ManageDrive(driveDevices); IList <Device> allDevices = Service.GetAllDevicesInGroup(newGroup); IList <Device> tempIoDevices = allDevices.Except(hmis.AllDevices).Except(drives.AllDevices).ToList(); tempIoDevices.Remove(plcs.AllDevices[0]); ManageIo ioDevices = new ManageIo(tempIoDevices); #endregion #region change settigns plcs.ChangeIpAddresses(groupCounter - 1); plcs.CreateNewIoSystem(templatePlcs.originalSubnet, currentPrefix); plcs.ConnectToMasterIoSystem(templatePlcs.originalIoSystem); plcs.GetAll_iDeviceParnerIoAdresses(); plcs.CopyFromTemplate(templatePlcs); plcs.AdjustFSettings(Parameters.FBaseAddrOffset * (groupCounter - 1), Parameters.FDestAddrOffset * (groupCounter - 1)); plcs.AdjustPnDeviceNumberWithOffset((groupCounter - 1)); plcs.AdjustPartnerIoAddresses(Parameters.IDeviceIoAddressOffset * (groupCounter - 1)); plcs.Restore(); plcs.ChangePnDeviceNames(currentPrefix); //plcs.SetAllIDeviceParnerAdresses(); ioDevices.ChangeIpAddresses(groupCounter - 1); ioDevices.SwitchIoSystem(templatePlcs.originalSubnet, plcs.newIoSystem); if (templatePlcs.LowerBoundForFDestinationAddresses_attribues?.Value != null) { ioDevices.AdjustFDestinationAddress(Parameters.FDestAddrOffset * (groupCounter - 1), (ulong)templatePlcs.LowerBoundForFDestinationAddresses_attribues.Value, (ulong)templatePlcs.UpperBoundForFDestinationAddresses_attribues.Value); } ioDevices.Restore(); ioDevices.ChangePnDeviceNames(currentPrefix); hmis.ChangeIpAddresses(groupCounter - 1); hmis.DisconnectFromSubnet(); hmis.ConnectToSubnet(templatePlcs.originalSubnet); hmis.Restore(); hmis.ChangePnDeviceNames(currentPrefix); drives.ChangeIpAddresses(groupCounter - 1); drives.SwitchIoSystem(templatePlcs.originalSubnet, plcs.newIoSystem); if (templatePlcs.LowerBoundForFDestinationAddresses_attribues?.Value != null) { drives.AdjustFDestinationAddress(Parameters.FDestAddrOffset * (groupCounter - 1), (ulong)templatePlcs.LowerBoundForFDestinationAddresses_attribues.Value, (ulong)templatePlcs.UpperBoundForFDestinationAddresses_attribues.Value); } drives.Restore(); drives.ChangePnDeviceNames(currentPrefix); plcs.SetAllToConnections(); plcs.RestoreAllPartnerPorts(); hmis.RestoreAllPartnerPorts(); drives.RestoreAllPartnerPorts(); ioDevices.RestoreAllPartnerPorts(); #endregion plcs.DelecteOldSubnet(); //deleteNetworkSubnet.Delete(); } #endregion try { deleteMasterCopy.Delete(); } catch (Exception ex) { Program.FaultMessage("Could not delete Mastercopy.", ex); } Progress(""); Console.WriteLine("Copy complete."); if (tiaStartedWithoutInterface == true) { Console.WriteLine("Saving project."); project.Save(); project.Close(); } else { Console.WriteLine("Please save project within TIAP."); } try { tiaPortal.Dispose(); } catch { } }
private async void UpdateGithubReposAsync(object state) { string json = await _client.GetRepositoriesAsync(); if (json == null) { return; } using (var scope = _scopeFactory.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService <GithubRepositoryContext>(); IList <GithubRepository> repos = new List <GithubRepository>(); JArray obj = JArray.Parse(json); foreach (JToken repo in obj) { RepositoryData data = repo.ToObject <RepositoryData>(); if (!data.Fork) { string readme_html = await _client.GetReadmeAsync("/repos/Sarius587/" + data.Name + "/readme"); AdditionalRepositoryData additionalData = await context.AdditionalData.SingleOrDefaultAsync(a => a.RepositoryId == data.Id); int id = -1; if (additionalData == null) { AdditionalRepositoryData newAdditionalData = new AdditionalRepositoryData { RepositoryId = data.Id, CustomExperience = null, LastEdit = DateTime.UtcNow }; await context.AdditionalData.AddAsync(newAdditionalData); await context.SaveChangesAsync(); id = newAdditionalData.Id; } else { id = additionalData.Id; } repos.Add(new GithubRepository { RepositoryId = data.Id, Name = data.Name, Description = data.Description, Url = data.Html_url, Readme = readme_html, AdditionalRepositoryDataId = id }); } } IList <GithubRepository> db_repos = await context.Repositories.ToListAsync(); var add_list = repos.Except(db_repos); var remove_list = db_repos.Except(repos); context.Repositories.RemoveRange(remove_list); context.Repositories.AddRange(add_list); await context.SaveChangesAsync(); } }
/// <summary> /// Updates the due dates. /// </summary> /// <param name="releaseCalendar">The release calendar.</param> /// <param name="artifacts">The artifacts.</param> /// <param name="developerId">The developer identifier.</param> private void UpdateDueDates(ReleaseCalendar releaseCalendar, IList<ArtifactFillListItem> artifacts, int developerId) { var modifiedIds = artifacts.Except(artifacts.RetrieveAddedOrDeleted()).Where(a => a.IsSelected.Value).Select(a => a.ProjectArtifactID.Value).ToList(); this.projectArtifactService.UpdateDueDate(modifiedIds, releaseCalendar.StartDate.Date, developerId); }
// ************************************** // UpdateTags // ************************************** private static Content UpdateTags(this SongSearchContext ctx, Content content, IList<int> tagsModel) { if (tagsModel == null) { return content; } var contentTags = content.Tags.ToList(); var contentTagsToRemove = contentTags.Where(t => !tagsModel.Contains(t.TagId)); contentTagsToRemove.ForEach(x => content.Tags.Remove(x)); var contentTagsToAdd = tagsModel.Except(contentTags.Select(t => t.TagId).Intersect(tagsModel)); foreach (var contentTag in contentTagsToAdd) { var tag = ctx.Tags.SingleOrDefault(t => t.TagId == contentTag); if (tag != null) { content.Tags.Add(tag); } } return content; }
/// <summary> /// Function to retrieve span releases. /// </summary> /// <param name="result">The list of release.</param> /// <param name="onlyForDate">The date parameter.</param> /// <returns>List of release list item.</returns> public static IList<ReleaseListItem> RetrieveSpanReleaseList(IList<ReleaseListItem> result, DateTime? onlyForDate) { var multispanCandidates = result.Where(item => item.EndDate.Value.AddMinutes(-1).Date > item.StartDate.Value.Date).ToList(); if (multispanCandidates.Count > 0) { if (onlyForDate.HasValue) { foreach (var multiSpan in multispanCandidates) { multiSpan.ActualStartDate = multiSpan.StartDate; multiSpan.ActualEndDate = multiSpan.EndDate; if (multiSpan.StartDate.Value.Date < onlyForDate.Value.Date) { multiSpan.StartDate = onlyForDate.Value.Date; } if (multiSpan.EndDate.Value.AddMinutes(-1).Date > onlyForDate.Value.Date) { multiSpan.EndDate = onlyForDate.Value.AddDays(1).Date; } } } else { var multispanList = new List<ReleaseListItem>(); foreach (var multiSpan in multispanCandidates) { multiSpan.ActualStartDate = multiSpan.StartDate; multiSpan.ActualEndDate = multiSpan.EndDate; var days = (multiSpan.EndDate.Value.Date - multiSpan.StartDate.Value.Date).TotalDays + 1; for (int i = 0; i < days; i++) { var multispanItem = multiSpan.CopyObject<ReleaseListItem>(); multispanItem.StartDate = (i == 0) ? multiSpan.StartDate : multiSpan.StartDate.Value.AddDays(i).Date; multispanItem.EndDate = (i == days - 1) ? multispanItem.EndDate : multispanItem.StartDate.Value.AddDays(1).Date; multispanList.Add(multispanItem); } } return result.Except(multispanCandidates).Concat(multispanList).ToList(); } } return result; }
private static void UniquifyParameterNames(IList<FunctionParameter> parameters) { DebugCheck.NotNull(parameters); foreach (var parameter in parameters) { parameter.Name = parameters.Except(new[] { parameter }).UniquifyName(parameter.Name); } }
private IList<ReportRipartizioneBilancioDTO> elaboraRigheContiVuoti(IList<ReportRipartizioneBilancioDTO> listaRiparto) { var listaRipartoByConti = listaRiparto.Where(item => item.IdConto > 0).GroupBy(item => item.IdConto); var contiToDelete = (from listaRipartoConto in listaRipartoByConti where listaRipartoConto.All(item => item.Importo.GetValueOrDefault() == 0) select listaRipartoConto.Key).ToList(); return listaRiparto.Except(listaRiparto.Where(item => contiToDelete.Contains(item.IdConto))).ToList(); }
private IList<MessageDTO> applyPayload(IList<MessageDTO> messages) { int payload = tc.getTargetLoad(); if(messages.Count > payload ) { IList<MessageDTO> partialMessages = messages.Take(payload).ToList(); IList<MessageDTO> remainingMessages = messages.Except(partialMessages, mc).ToList(); return partialMessages; } else { return messages; } }
/// <summary> /// allows only what is found in the return value of WhiteList /// </summary> public IEnumerable<ITransition> AllowTransitions(IList<ITransition> transitions) { return transitions.Except(base.TransitionsInCommonWithList(transitions)) .Where(x => object.Equals(x.WorkflowId, _workflowId)); }
private static IList<EdmSchemaError> HandleValidationErrors(IList<EdmSchemaError> schemaErrors) { IEnumerable<EdmSchemaError> warningsToRemove = schemaErrors.Where(s => s.ErrorCode == ERRORCODE_MAPPINGALLQUERYVIEWATCOMPILETIME); // When EntityContainerMapping only has QueryView, the mapping is valid return schemaErrors.Except(warningsToRemove).ToList(); }
public async Task <IActionResult> EditRoles(string userName, EditRoleViewModel rolesViewModel) { User user = await this.userManager.FindByNameAsync(userName); if (user == null) { return(NotFound("User can not be found")); } IList <string> userRoles = await this.userManager.GetRolesAsync(user); string[] selectedRoles = rolesViewModel.RoleNames; selectedRoles = selectedRoles ?? new string[] { }; IdentityResult addedRolesResult = await this.userManager.AddToRolesAsync(user, selectedRoles.Except(userRoles)); if (!addedRolesResult.Succeeded) { return(BadRequest($"Failed to add to roles user {userName}")); } IdentityResult removedRolesResult = await this.userManager.RemoveFromRolesAsync(user, userRoles.Except(selectedRoles)); if (!removedRolesResult.Succeeded) { return(BadRequest($"Failed to remove the roles for {userName}")); } return(Ok(await this.userManager.GetRolesAsync(user))); }
private static IEnumerable <string> PerformScan <T>(IList <Assembly> loaded, out string[] errorReport) { var dllsWithReference = new List <string>(); var errors = new List <string>(); var assembliesWithErrors = new List <Assembly>(); //load each of the LoadFrom assemblies into the Load context too foreach (var a in loaded) { var name = AppDomain.CurrentDomain.ApplyPolicy(a.FullName); Assembly.ReflectionOnlyLoad(name); } //get the list of assembly names to compare below var loadedNames = loaded.Select(x => x.GetName().Name).ToArray(); //Then load each referenced assembly into the context foreach (var a in loaded) { //don't load any referenced assemblies that are already found in the loaded array - this is based on name // regardless of version. We'll assume that if the assembly found in the folder matches the assembly name // being looked for, that is the version the user has shipped their package with and therefore it 'must' be correct foreach (var assemblyName in a.GetReferencedAssemblies().Where(ass => loadedNames.Contains(ass.Name) == false)) { try { var name = AppDomain.CurrentDomain.ApplyPolicy(assemblyName.FullName); Assembly.ReflectionOnlyLoad(name); } catch (FileNotFoundException) { //if an exception occurs it means that a referenced assembly could not be found errors.Add( string.Concat("This package references the assembly '", assemblyName.Name, "' which was not found")); assembliesWithErrors.Add(a); } catch (Exception ex) { //if an exception occurs it means that a referenced assembly could not be found errors.Add( string.Concat("This package could not be verified for compatibility. An error occurred while loading a referenced assembly '", assemblyName.Name, "' see error log for full details.")); assembliesWithErrors.Add(a); LogHelper.Error <PackageBinaryInspector>("An error occurred scanning package assemblies", ex); } } } var contractType = GetLoadFromContractType <T>(); //now that we have all referenced types into the context we can look up stuff foreach (var a in loaded.Except(assembliesWithErrors)) { //now we need to see if they contain any type 'T' var reflectedAssembly = a; try { var found = reflectedAssembly.GetExportedTypes() .Where(contractType.IsAssignableFrom); if (found.Any()) { dllsWithReference.Add(reflectedAssembly.FullName); } } catch (Exception ex) { //This is a hack that nobody can seem to get around, I've read everything and it seems that // this is quite a common thing when loading types into reflection only load context, so // we're just going to ignore this specific one for now var typeLoadEx = ex as TypeLoadException; if (typeLoadEx != null) { if (typeLoadEx.Message.InvariantContains("does not have an implementation")) { //ignore continue; } } else { errors.Add( string.Concat("This package could not be verified for compatibility. An error occurred while scanning a packaged assembly '", a.GetName().Name, "' see error log for full details.")); assembliesWithErrors.Add(a); LogHelper.Error <PackageBinaryInspector>("An error occurred scanning package assemblies", ex); } } } errorReport = errors.ToArray(); return(dllsWithReference); }
private static Mitarbeiter NextMitarbeiter(IList <Mitarbeiter> alleDieDaSind, IList <Mitarbeiter> schonEingeteilt, Arbeitstag arbeitstag, Arbeitswoche woche = null, DienstTyp ma4Diensttyp = DienstTyp.None, GruppenTyp etage = GruppenTyp.Gelb | GruppenTyp.Gruen | GruppenTyp.Nest | GruppenTyp.Rot) { var arbeitstagPlanzeiten = arbeitstag.Planzeiten.ToList(); var topf = alleDieDaSind.Except(schonEingeteilt).Where(x => x.DefaultGruppe.IstFarbGruppe()).ToList(); if (topf.Count == 0) { return(null); } //alle die nicht allein sind in der gruppe var sonderTopf = topf.ToList(); var mitarbeiter = new List <Mitarbeiter>(); //Wenn RandDienst dann gilt erstmal die Wunschdienst REgel zwingend if (ma4Diensttyp.IstRandDienst()) { mitarbeiter = sonderTopf = topf.Where(x => (x.Wunschdienste & ma4Diensttyp) == ma4Diensttyp).ToList(); } //erstma gucken für die ganz RandRand Dienste //alle verfügbaren wo mehr als einer noch in der Gruppe ist //und in der Gruppe darf noch keiner einen RandRandDienst haben if (sonderTopf.Count == 0 && ma4Diensttyp.IstRandRandDienst()) { sonderTopf = topf.GroupBy(x => x.DefaultGruppe).Where(x => x.Count() > 1) .SelectMany(x => x.Where(ma => !arbeitstagPlanzeiten.Any(y => y.Gruppe == ma.DefaultGruppe && y.Dienst.IstRandRandDienst()))).ToList(); } //dann gucken für die ganz Rand Dienste if (sonderTopf.Count == 0 && ma4Diensttyp.IstRandDienst()) { sonderTopf = topf.GroupBy(x => x.DefaultGruppe).Where(x => x.Count() > 1) .SelectMany(x => x.Where(ma => !arbeitstagPlanzeiten.Any(y => y.Gruppe == ma.DefaultGruppe && y.Dienst.IstRandDienst()))).ToList(); } //Probieren einen zu Finden aus einer Gruppen die noch keinen Randdienst hat if (sonderTopf.Count == 0 && ma4Diensttyp.IstRandDienst()) { sonderTopf = topf.GroupBy(x => x.DefaultGruppe) .SelectMany(x => x.Where(ma => !arbeitstagPlanzeiten.Any(y => y.Gruppe == ma.DefaultGruppe && y.Dienst.IstRandDienst()))).ToList(); } //die mit Wunschdienst aus Etage if (mitarbeiter.Count == 0) { mitarbeiter = sonderTopf.Where(x => (x.Wunschdienste & ma4Diensttyp) == ma4Diensttyp && (etage & x.DefaultGruppe) == x.DefaultGruppe).ToList(); } //die von Etage if (mitarbeiter.Count == 0) { mitarbeiter = sonderTopf.Where(x => (etage & x.DefaultGruppe) == x.DefaultGruppe).ToList(); } //Wunschdienst if (mitarbeiter.Count == 0) { mitarbeiter = sonderTopf.Where(x => (x.Wunschdienste & ma4Diensttyp) == ma4Diensttyp).ToList(); } //Wenn mit der RandDienstlogik niemand gefunden wurde, dann vllt vorher nochmal schauen ob ein Wunschdienstler Lust hat if (mitarbeiter.Count == 0 && ma4Diensttyp.IstRandDienst()) { sonderTopf = topf.Where(x => (x.Wunschdienste & ma4Diensttyp) == ma4Diensttyp).ToList(); } if (mitarbeiter.Count == 0) { mitarbeiter = sonderTopf; } if (mitarbeiter.Count == 0)//bei allen gucken wenn keiner will { mitarbeiter = topf; } //RandDienste Gleichverteilen über die Woche if (woche != null && ma4Diensttyp.IstRandDienst()) { var geplanteRanddienste = woche.Arbeitstage.SelectMany(x => x.Planzeiten.Where(p => p.Dienst == ma4Diensttyp)).ToList(); var mitarbeiterMitRanddiensten = geplanteRanddienste.Select(x => x.ErledigtDurch).Distinct().ToList(); //irgendein Mitarbeiter da, der noch gar nix hat if (mitarbeiter.Except(mitarbeiterMitRanddiensten).Any()) { mitarbeiter = mitarbeiter.Except(mitarbeiterMitRanddiensten).ToList(); } else { var mitarbeiterMitAnzahlRanddienstInderWoche = geplanteRanddienste.GroupBy(g => g.ErledigtDurch).ToDictionary(x => x.Key, c => c.Count()); var minCount = mitarbeiterMitAnzahlRanddienstInderWoche.Min(x => x.Value); var mitarbeiterMitWenigstenCounts = mitarbeiterMitAnzahlRanddienstInderWoche.Where(x => x.Value == minCount).Select(x => x.Key).ToList(); var mitarbeiterMitMehrcounts = mitarbeiterMitAnzahlRanddienstInderWoche.Where(x => x.Value != minCount).Select(x => x.Key).ToList(); if (mitarbeiter.Intersect(mitarbeiterMitWenigstenCounts).Any()) { mitarbeiter = mitarbeiter.Intersect(mitarbeiterMitWenigstenCounts).ToList(); } else if (mitarbeiter.Except(mitarbeiterMitRanddiensten.Except(mitarbeiterMitMehrcounts)).Any()) { mitarbeiter = mitarbeiter.Except(mitarbeiterMitRanddiensten.Except(mitarbeiterMitMehrcounts)).ToList(); } //sofern noch einer übrig bleibt soll derjenige der am Vortag das gemacht, nicht nochmal dran sein var vortag = woche.Arbeitstage.Single(x => x.Datum == arbeitstag.Datum.AddDays(-1)); var letzte = vortag?.Planzeiten?.Where(x => x.Dienst == ma4Diensttyp).Select(x => x.ErledigtDurch).ToList() ?? new List <Mitarbeiter>(); if (mitarbeiter.Except(letzte).Any()) { mitarbeiter = mitarbeiter.Except(letzte).ToList(); } } //am gleichen Tag vllt nicht unbedingt auch noch aus der gleichen gruppe var ma4Gruppencheck = arbeitstag.Planzeiten.Where(x => x.Dienst == ma4Diensttyp).Select(x => x.ErledigtDurch).ToList(); var maGleicherGruppe = mitarbeiter.Where(x => ma4Gruppencheck.Any(m => m.DefaultGruppe == x.DefaultGruppe)).ToList(); if (mitarbeiter.Except(maGleicherGruppe).Any()) { mitarbeiter = mitarbeiter.Except(maGleicherGruppe).ToList(); } } int ichBinDran = Zufall.Next(0, mitarbeiter.Count); #if DEBUG Console.WriteLine($"{ma4Diensttyp}: {ichBinDran} von {mitarbeiter.Count}"); #endif return(mitarbeiter[ichBinDran]); }
protected virtual void FillHollow(IList <Vector2Int32> area, IList <Vector2Int32> interrior) { IEnumerable <Vector2Int32> border = area.Except(interrior).ToList(); // Draw the border if (_wvm.TilePicker.TileStyleActive) { foreach (Vector2Int32 pixel in border) { if (!_wvm.CurrentWorld.ValidTileLocation(pixel)) { continue; } int index = pixel.X + pixel.Y * _wvm.CurrentWorld.TilesWide; if (!_wvm.CheckTiles[index]) { _wvm.CheckTiles[index] = true; if (_wvm.Selection.IsValid(pixel)) { _wvm.UndoManager.SaveTile(pixel); if (_wvm.TilePicker.WallStyleActive) { _wvm.TilePicker.WallStyleActive = false; _wvm.SetPixel(pixel.X, pixel.Y, mode: PaintMode.TileAndWall); _wvm.TilePicker.WallStyleActive = true; } else { _wvm.SetPixel(pixel.X, pixel.Y, mode: PaintMode.TileAndWall); } /* Heathtech */ BlendRules.ResetUVCache(_wvm, pixel.X, pixel.Y, 1, 1); } } } } // Draw the wall in the interrior, exclude the border so no overlaps foreach (Vector2Int32 pixel in interrior) { if (!_wvm.CurrentWorld.ValidTileLocation(pixel)) { continue; } if (_wvm.Selection.IsValid(pixel)) { _wvm.UndoManager.SaveTile(pixel); _wvm.SetPixel(pixel.X, pixel.Y, mode: PaintMode.TileAndWall, erase: true); if (_wvm.TilePicker.WallStyleActive) { if (_wvm.TilePicker.TileStyleActive) { _wvm.TilePicker.TileStyleActive = false; _wvm.SetPixel(pixel.X, pixel.Y, mode: PaintMode.TileAndWall); _wvm.TilePicker.TileStyleActive = true; } else { _wvm.SetPixel(pixel.X, pixel.Y, mode: PaintMode.TileAndWall); } } /* Heathtech */ BlendRules.ResetUVCache(_wvm, pixel.X, pixel.Y, 1, 1); } } }
protected IList <TileGrouping> GetAllGroupsWithoutBonusTiles(IList <TileGrouping> tileGroups) { var bonusTiles = GetAllGroupsOfSpecificType <BonusTile>(tileGroups); return(tileGroups.Except(bonusTiles).ToList()); }
private IEnumerable<FieldAssociation> DuplicateCheck(IList<FieldAssociation> addRange) { if (!addRange.Any() || !this.associations.Any()) { return addRange; } IEnumerable<FieldAssociation> d = addRange.Except(this.associations.Intersect(addRange)); return d; }
/// <summary> /// allows only what is found in the return value of WhiteList /// </summary> public IEnumerable <ITransition> AllowTransitions(IList <ITransition> transitions) { return(transitions.Except(base.TransitionsInCommonWithList(transitions)) .Where(x => object.Equals(x.WorkflowId, _workflowId))); }
public static IEnumerable <T> ExceptObjects <T> (this IList <T> first, IList <T> second) where T : IMovieIntro { return(first.Except(second, new ObjectsComparer <T>())); }
private static void CompareListsNew(IList<Article> list1, List<Article> list2, ListBox lb1, ListBox lb2, ListBox lb3) { lb1.BeginUpdate(); lb2.BeginUpdate(); lb3.BeginUpdate(); lb1.Items.AddRange(list1.Except(list2).ToArray()); lb2.Items.AddRange(list2.Except(list1).ToArray()); lb3.Items.AddRange(list1.Intersect(list2).ToArray()); lb1.EndUpdate(); lb2.EndUpdate(); lb3.EndUpdate(); }
private void GetWorksWithCustomers() { IEnumerable <WorkDto> forPurchase = Works.Except(FreeForSale); FreeForPurchase = forPurchase.ToList(); }
// ReSharper disable UnusedParameter.Local private void AssertTypeRule( Func<Type, IArgumentNullExceptionFixture> addMethod, IList<RegexRule> existingRules, IList<RegexRule> regexRules, bool expectedInclude) { IArgumentNullExceptionFixture actual = addMethod(GetType()); Assert.Same(addMethod.Target, actual); Assert.Equal(existingRules.Count + 1, regexRules.Count); Assert.False(existingRules.Except(regexRules).Any()); RegexRule addedRule = regexRules.Except(existingRules).Single(); Assert.Equal(expectedInclude, addedRule.Include); Assert.NotNull(addedRule.Type); Assert.Null(addedRule.Method); Assert.Null(addedRule.Parameter); Assert.True(addedRule.MatchType(GetType())); }
public void TestCreateTelemetry() { //1 string deviceCode = RndString(max: 20); string propName1 = RndString(max: 20); string timeMark1 = RndTime.TimeFormater(); string propValue1 = RndString(); string propName2 = RndString(max: 20); string timeMark2 = RndTime.TimeFormater(); string propValue2 = RndString(); string propName3 = RndString(max: 20); string timeMark3 = RndTime.TimeFormater(); string propValue3 = RndString(); var data = new List <(string propName, string timeMarker, string propValue)> { (propName1, timeMark1, propValue1), (propName2, timeMark2, propValue2), (propName3, timeMark3, propValue3) }; var pv1 = new PropertiesValues(new Dictionary <string, string> { { propName1, propValue1 } }); Telemetry telemetry1 = new Telemetry(MyCode, pv1, timeMark1.TimeFormater(), deviceCode); var pv2 = new PropertiesValues(new Dictionary <string, string> { { propName2, propValue2 } }); Telemetry telemetry2 = new Telemetry(MyCode, pv2, timeMark2.TimeFormater(), deviceCode); var pv3 = new PropertiesValues(new Dictionary <string, string> { { propName3, propValue3 } }); Telemetry telemetry3 = new Telemetry(MyCode, pv3, timeMark3.TimeFormater(), deviceCode); IList <Telemetry> telemetriesExpected = new List <Telemetry> { telemetry1, telemetry2, telemetry3 }; var kvp = new KeyValuePair <string, IList <(string propName, string timeMarker, string propValue)> >(deviceCode, data); //2 IList <Telemetry> telemetries = CreateTelemetry(kvp); //3 bool Compare(Telemetry a, Telemetry b) { return(a.DeviceCode == b.DeviceCode && a.MessageType == b.MessageType && a.TargetDeviceCode == b.TargetDeviceCode && a.TimeMarker == b.TimeMarker && !a.Values.Except(b.Values).Any()); } var comparer = new EquaComparer <Telemetry>(Compare, obg => obg.DeviceCode.GetHashCode()); Assert.IsEmpty(telemetries.Except(telemetriesExpected, comparer)); }
/// <summary> /// Adds, updates or removes entries from the Target collection based on values in the New collection using the specified primary keys /// </summary> public List <TEntry> MergeCollections <TEntry>(IList <TEntry> targetCollection, IList <TEntry> newCollection, IList <EntityKeyPropertyInfo> keyProperties, Func <TEntry, TEntry, TEntry> getUpdateEntry, Func <TEntry, TEntry> addEntry, Action <IList <TEntry> > removeEntriesFromCollection) where TEntry : class { if (targetCollection == null) { throw new ArgumentNullException(nameof(targetCollection)); } if (newCollection == null) { throw new ArgumentNullException(nameof(newCollection)); } if (getUpdateEntry == null) { throw new ArgumentNullException(nameof(getUpdateEntry)); } if (addEntry == null) { throw new ArgumentNullException(nameof(addEntry)); } var resultingCollection = new List <TEntry>(newCollection.Count); // Get all New collection entries that are not present in the Target collection (to add them to the Target collection) var newEntries = newCollection.Where(entry => targetCollection .SingleOrDefault(source => EntityComparer.CompareEntities <TEntry>(source, entry, keyProperties)) == null) .ToArray(); // Get all Target collection entries that are not present in the New collection (to remove them from the Target collection) var entriesToRemove = targetCollection.Where(entry => newCollection .SingleOrDefault(newItem => EntityComparer.CompareEntities <TEntry>(newItem, entry, keyProperties)) == null) .ToArray(); /* Get a copy of Target collection for safe iterations (in case entries get removed * from the collection in getUpdatedEntry */ var target = targetCollection.Except(entriesToRemove).ToArray(); if (entriesToRemove.Length > 0) { removeEntriesFromCollection?.Invoke(entriesToRemove); } // Update pre-existing entries in Target collection for (int i = 0; i < target.Length; i++) { TEntry newState = newCollection.Single(newItem => EntityComparer.CompareEntities(newItem, target[i], keyProperties)); resultingCollection.Add(getUpdateEntry.Invoke(target[i], newState)); } // Add entries that don't exist in the Target collection if (newEntries.Length > 0) { foreach (var entry in newEntries) { resultingCollection.Add(addEntry.Invoke(entry)); } } return(resultingCollection); }
public async Task Submit(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files, string filter) { // See if any of them are archives var archives = (from file in files let ext = Path.GetExtension(file).ToLowerInvariant() where ext == ".zip" || ext == ".nupkg" || ext == ".snupkg" || ext == ".vsix" || ext == ".appxupload" || ext == ".msixupload" select file).ToList(); // expand the archives and sign recursively first var tempZips = new List <TemporaryZipFile>(); try { foreach (var archive in archives) { tempZips.Add(new TemporaryZipFile(archive, filter, logger)); } // See if there's any files in the expanded zip that we need to sign var allFiles = tempZips.SelectMany(tz => tz.FilteredFilesInDirectory).ToList(); if (allFiles.Count > 0) { // Send the files from the archives through the aggregator to sign await Submit(hashMode, name, description, descriptionUrl, allFiles, filter); // After signing the contents, save the zip // For NuPkg, this step removes the signature too, but that's ok as it'll get signed below tempZips.ForEach(tz => tz.Save()); } } finally { tempZips.ForEach(tz => tz.Dispose()); tempZips.Clear(); } // See if there's any appx's in here, process them recursively first to sign the inner files var appxs = (from file in files let ext = Path.GetExtension(file).ToLowerInvariant() where ext == ".appx" || ext == ".eappx" || ext == ".msix" || ext == ".emsix" select file).ToList(); // See if there's any appxbundles here, process them recursively first // expand the archives and sign recursively first // This will also update the publisher information to get it ready for signing var tempAppxs = new List <AppxFile>(); try { foreach (var appx in appxs) { tempAppxs.Add(await appxFileFactory.Create(appx, filter)); } // See if there's any files in the expanded zip that we need to sign var allFiles = tempAppxs.SelectMany(tz => tz.FilteredFilesInDirectory).ToList(); if (allFiles.Count > 0) { // Send the files from the archives through the aggregator to sign await Submit(hashMode, name, description, descriptionUrl, allFiles, filter); } // Save the appx with the updated publisher info tempAppxs.ForEach(tz => tz.Save()); } finally { tempAppxs.ForEach(tz => tz.Dispose()); tempAppxs.Clear(); } var bundles = (from file in files let ext = Path.GetExtension(file).ToLowerInvariant() where ext == ".appxbundle" || ext == ".eappxbundle" || ext == ".msixbundle" || ext == ".emsixbundle" select file).ToList(); var tempBundles = new List <AppxBundleFile>(); try { foreach (var bundle in bundles) { tempBundles.Add(new AppxBundleFile(bundle, logger, makeappxPath)); } // See if there's any files in the expanded zip that we need to sign var allFiles = tempBundles.SelectMany(tz => tz.FilteredFilesInDirectory).ToList(); if (allFiles.Count > 0) { // Send the files from the archives through the aggregator to sign await Submit(hashMode, name, description, descriptionUrl, allFiles, filter); // After signing the contents, save the zip tempBundles.ForEach(tz => tz.Save()); } } finally { tempBundles.ForEach(tz => tz.Dispose()); tempBundles.Clear(); } // split by code sign service and fallback to default var grouped = (from kvp in codeSignServices join file in files on kvp.Key equals Path.GetExtension(file).ToLowerInvariant() group file by kvp.Value into g select g).ToList(); // get all files and exclude existing; // This is to catch PE files that don't have the correct extension set var defaultFiles = files.Except(grouped.SelectMany(g => g)) .Where(IsPeFile) .Select(f => new { defaultCodeSignService, f }) .GroupBy(a => a.defaultCodeSignService, k => k.f) .SingleOrDefault(); // one group here if (defaultFiles != null) { grouped.Add(defaultFiles); } await Task.WhenAll(grouped.Select(g => g.Key.Submit(hashMode, name, description, descriptionUrl, g.ToList(), filter))); }
public virtual IEnumerable <string> GetCandidateItems(Split split, User u) { var userItems = u.Feedbacks.Select(f => f.Item.Id); return(_allCandidateItems.Except(userItems).Take(_maxNumCandidates)); }
private static IList<string> GetDifference(IList<string> existingHandles, IList<string> currentHandles) { // We are using LINQ to get the difference between the two lists. // The non-LINQ version looks like the following: // IList<string> differentHandles = new List<string>(); // foreach (string handle in currentHandles) // { // if (!existingHandles.Contains(handle)) // { // currentHandles.Add(handle); // } // } // return differentHandles; return currentHandles.Except(existingHandles).ToList(); }
public void ComUserStartUpdate(int CommunityId, IList <int> UsersId, bool Start) { if (!Manager.IsInTransaction()) { Manager.BeginTransaction(); } IList <Domain.SubscriptionExpiration> expirations = new List <Domain.SubscriptionExpiration>(); UsersId = UsersId.Distinct().ToList(); int counter = UsersId.Count; if (counter > 500) { int block = (counter / 500) + 1; for (int curblock = 0; curblock < block; curblock++) { IList <int> currentId = UsersId.Skip(500 * curblock).Take(500).ToList(); IList <Domain.SubscriptionExpiration> curExps = Manager.GetAll <Domain.SubscriptionExpiration>(se => currentId.Contains(se.PersonId)); expirations = expirations.Union(curExps).ToList(); } expirations = expirations.Distinct().ToList(); } else { expirations = Manager.GetAll <Domain.SubscriptionExpiration>(exp => exp.Deleted == BaseStatusDeleted.None && exp.CommunityId == CommunityId && UsersId.Contains(exp.PersonId)); } IList <int> settedUsersId = expirations.Select(exp => exp.PersonId).Distinct().ToList(); IList <int> unSettedUsersId = UsersId.Except(settedUsersId).ToList(); if (unSettedUsersId != null && unSettedUsersId.Any()) { foreach (int UserIdNotSet in unSettedUsersId) { Domain.SubscriptionExpiration expiration = new Domain.SubscriptionExpiration(); expiration.CreateMetaInfo(Manager.GetLitePerson(UC.CurrentUserID), UC.IpAddress, UC.ProxyIpAddress); expiration.CommunityId = CommunityId; expiration.PersonId = UserIdNotSet; Domain.dtoUserExpiration exp = ComUserDurationGet(CommunityId, UserIdNotSet); expiration.Duration = exp.Duration; expirations.Add(expiration); } } DateTime StartDt = DateTime.Now; foreach (Domain.SubscriptionExpiration exp in expirations) { if (Start && exp.Duration >= 0) { exp.StartDate = StartDt; //exp.EndDate = StartDt.AddDays(exp.Duration); } else { exp.StartDate = null; //exp.EndDate = null; } } bool saved = false; try { Manager.SaveOrUpdateList <Domain.SubscriptionExpiration>(expirations); Manager.Commit(); saved = true; } catch { Manager.RollBack(); } if (saved) { CacheHelper.UserReset(); } }
public async Task <ActionResult> Edit2(EditUserFormViewModel2 viewModel) { // selectedRole is the name of the checkbox list on the html form // HERE WE ARE USING SAME FORM & VIEWMODEL FOR ADD & EDIT // BUT BOTH SCENARIOS ARE DIFFERENT, // ADD NEED PASSWORD & CONFIRM PASSWORD IN VIEW & VIEWMODEL & THEY ARE MANDATORY // WITH THEM MODEL WILL BE NOT VALIDATED // EDIT DO NOT NEED PASSWORD & CONFIRM PASSWORD IN VIEW & VIEWMODEL // MODEL VALIDATION WILL STOP US FROM EDITING USER AND WILL ASK FOR PASSWORKD & CONFIRM PASSWORD // SPLIT VIEWS & VIEWMODELS FOR ADD & EDIT //var user = UserManager.Users.FirstOrDefault(u => u.Id == viewModel.Id); // If SelectedRoles is null, then add Empty String //selectedRoles = selectedRoles ?? new string[] { }; // not needed as by default initized in constructor //selectedClaims = selectedClaims ?? new string[] { }; //IEnumerable<SelectListItem> SelectedRolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem() //{ // Selected = userRoles.Contains(x.Name), // Text = x.Name, // Value = x.Name //}); //IEnumerable<SelectListItem> SelectedClaimsList = ClaimsStore.AllClaims.Select(x => new SelectListItem() //{ // Selected = userClaims.Any(uc => uc.Value == x.Value), // Text = x.Type, // Value = x.Value //}); IdentityResult result = null; IList <string> userRoles = await UserManager.GetRolesAsync(viewModel.Id); IList <Claim> userClaims = await UserManager.GetClaimsAsync(viewModel.Id); if (!ModelState.IsValid) { // Add Error ModelState.AddModelError("", "Something failed."); return(View("EditUserForm2", viewModel)); } ApplicationUser user = await UserManager.FindByIdAsync(viewModel.Id); if (user == null) { ViewBag.ErrorMessage = $"User with Id = {viewModel.Email} cannot be found"; return(View("NotFound")); //return HttpNotFound(); } user.UserName = viewModel.Email; user.Email = viewModel.Email; user.DrivingLicense = viewModel.DrivingLicense; user.Phone = viewModel.Phone; result = await UserManager.UpdateAsync(user); // Error Occurs While Updating User, no need to add Roles & Claims if (!result.Succeeded) { ViewBag.Message = "Error occurred while updating Record(s)"; foreach (var error in result.Errors) { ModelState.AddModelError("", error); } return(View("EditUserForm2", viewModel)); } // Only add newly added roles, do not add already added roles. result = await UserManager.AddToRolesAsync(user.Id, viewModel.GetSelectedRoles().Except(userRoles).ToArray <string>()); // Error occurs while adding roles array, but user edited if (!result.Succeeded) { // Add error ViewBag.Message = "Error occurred while adding Record(s)"; foreach (var error in result.Errors) { ModelState.AddModelError("", error); } return(View("EditUserForm2", viewModel)); } // Remove all roles other than selected roles. result = await UserManager.RemoveFromRolesAsync(user.Id, userRoles.Except(viewModel.GetSelectedRoles()).ToArray <string>()); // Error occurs while removing roles, but user edited, role added, not removed if (!result.Succeeded) { ViewBag.Message = "Error occurred while updating Record(s)"; foreach (var error in result.Errors) { ModelState.AddModelError("", error); } return(View("EditUserForm2", viewModel)); } // Removing Claim Array foreach (var claim in userClaims) { result = await UserManager.RemoveClaimAsync(user.Id, claim); } if (!result.Succeeded) { ViewBag.Message = "Error occurred while updating Record(s)"; foreach (var error in result.Errors) { ModelState.AddModelError("", error); } return(View("EditUserForm2", viewModel)); } //IList<Claim> selectedClaimsOnForm = new List<Claim>(); List <Claim> selectedClaimsOnForm = CompareClaimValues(viewModel.AllClaimsList); // Adding Claim Array foreach (var claim in selectedClaimsOnForm) { result = await UserManager.AddClaimAsync(user.Id, claim); } if (!result.Succeeded) { ViewBag.Message = "Error occurred while updating Record(s)"; foreach (var error in result.Errors) { ModelState.AddModelError("", error); } return(View("EditUserForm2", viewModel)); } // User Added, Role Added, Role Removed Successfully. Show List Role ViewBag.Message = "Record(s) updated successfully."; return(List()); }
public IList <Domain.dtoExpirationConfig> GetCommunityExpirationConfig( int CommunityId, int LangId, string LangCode) { Language defLang = Manager.GetDefaultLanguage(); if (defLang == null) { defLang = new Language(); defLang.Code = "us-EN"; defLang.Id = 1; } if (LangId <= 0) { LangId = defLang.Id; } if (string.IsNullOrWhiteSpace(LangCode)) { LangCode = defLang.Code; } List <Domain.ExpirationConfig> oldcfg = (from Domain.ExpirationConfig conf in Manager.GetIQ <Domain.ExpirationConfig>() where conf.CommunityId == CommunityId select conf ).ToList(); List <Domain.dtoExpirationConfig> config = oldcfg.Select(c => new Domain.dtoExpirationConfig(c)).ToList(); IList <int> idCommunityRoles = Manager.GetAvailableRoles(CommunityId); IList <int> oldRoles = (from Domain.dtoExpirationConfig conf in config select conf.RoleId).ToList(); IList <int> newRoles = idCommunityRoles.Except(oldRoles).ToList(); if (newRoles != null && newRoles.Any()) { int ComTypeId = Manager.GetIdCommunityType(CommunityId); List <Domain.ExpirationConfig> oldsysConf = (from Domain.ExpirationConfig conf in Manager.GetIQ <Domain.ExpirationConfig>() where conf.CommunityId == 0 && conf.CommunityTypeId == ComTypeId select conf ).ToList(); List <Domain.dtoExpirationConfig> SysConfig = oldsysConf.Select(c => new Domain.dtoExpirationConfig(c)) .ToList(); foreach (int newroleId in newRoles) { Domain.dtoExpirationConfig newcfg = new Domain.dtoExpirationConfig(); newcfg.RoleId = newroleId; Domain.dtoExpirationConfig sysConf = SysConfig.FirstOrDefault(c => c.RoleId == newroleId); if (sysConf != null && sysConf.RoleId > 0) { newcfg.Duration = sysConf.Duration; } else { newcfg.Duration = -1; } config.Add(newcfg); } } if (config != null && config.Any()) { config.ForEach(c => { c.RoleName = Manager.GetTranslatedRole(c.RoleId, LangId); c.DurationName = settings.GetValidityName(LangCode, c.Duration); } ); } return(config); }
private static IList <EntityRecommendation> PopulateCompositeEntity(CompositeEntity compositeEntity, IList <EntityRecommendation> entities, JObject entitiesAndMetadata, bool verbose) { var childrenEntites = new JObject(); var childrenEntitiesMetadata = new JObject(); if (verbose) { childrenEntites[MetadataKey] = new JObject(); } // This is now implemented as O(n^2) search and can be reduced to O(2n) using a map as an optimization if n grows var compositeEntityMetadata = entities.FirstOrDefault(e => e.Type == compositeEntity.ParentType && e.Entity == compositeEntity.Value); // This is an error case and should not happen in theory if (compositeEntityMetadata == null) { return(entities); } if (verbose) { childrenEntitiesMetadata = ExtractEntityMetadata(compositeEntityMetadata); childrenEntites[MetadataKey] = new JObject(); } var coveredSet = new HashSet <EntityRecommendation>(); foreach (var child in compositeEntity.Children) { foreach (var entity in entities) { // We already covered this entity if (coveredSet.Contains(entity)) { continue; } // This entity doesn't belong to this composite entity if (child.Type != entity.Type || !CompositeContainsEntity(compositeEntityMetadata, entity)) { continue; } // Add to the set to ensure that we don't consider the same child entity more than once per composite coveredSet.Add(entity); AddProperty(childrenEntites, ExtractNormalizedEntityName(entity), ExtractEntityValue(entity)); if (verbose) { AddProperty((JObject)childrenEntites[MetadataKey], ExtractNormalizedEntityName(entity), ExtractEntityMetadata(entity)); } } } AddProperty(entitiesAndMetadata, compositeEntity.ParentType, childrenEntites); if (verbose) { AddProperty((JObject)entitiesAndMetadata[MetadataKey], compositeEntity.ParentType, childrenEntitiesMetadata); } // filter entities that were covered by this composite entity return(entities.Except(coveredSet).ToList()); }
/// <summary> /// Search products /// </summary> /// <param name="categoryId">Category identifier; 0 to load all recordss</param> /// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param> /// <param name="featuredProducts">A value indicating whether loaded products are marked as featured (relates only to categories and manufacturers). 0 to load featured products only, 1 to load not featured products only, null to load all products</param> /// <param name="priceMin">Minimum price; null to load all records</param> /// <param name="priceMax">Maximum price; null to load all records</param> /// <param name="productTagId">Product tag identifier; 0 to load all records</param> /// <param name="keywords">Keywords</param> /// <param name="searchDescriptions">A value indicating whether to search in descriptions</param> /// <param name="languageId">Language identifier</param> /// <param name="filteredSpecs">Filtered product specification identifiers</param> /// <param name="orderBy">Order by</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Product collection</returns> public virtual IPagedList<Product> SearchProducts(int categoryId, int manufacturerId, bool? featuredProducts, decimal? priceMin, decimal? priceMax, int productTagId, string keywords, bool searchDescriptions, int languageId, IList<int> filteredSpecs, ProductSortingEnum orderBy, int pageIndex, int pageSize, bool showHidden = false) { bool searchLocalizedValue = false; if (languageId > 0) { if (showHidden) { searchLocalizedValue = true; } else { //ensure that we have at least two published languages var totalPublishedLanguages = _languageService.GetAllLanguages(false).Count; searchLocalizedValue = totalPublishedLanguages >= 2; } } if (_commonSettings.UseStoredProceduresIfSupported && _dataProvider.StoredProceduredSupported) { //stored procedures are enabled and supported by the database. //It's much faster than the LINQ implementation below //TODO We should not reference SqlParameter here. DAL should do it. var pTotalRecords = new SqlParameter { ParameterName = "TotalRecords", Direction = ParameterDirection.Output, SqlDbType = SqlDbType.Int }; string commaSeparatedSpecIds = ""; if (filteredSpecs != null) { ((List<int>)filteredSpecs).Sort(); for (int i = 0; i < filteredSpecs.Count; i++) { commaSeparatedSpecIds += filteredSpecs[i].ToString(); if (i != filteredSpecs.Count - 1) { commaSeparatedSpecIds += ","; } } } //some databases don't support int.MaxValue if (pageSize == int.MaxValue) pageSize = int.MaxValue - 1; var products = _dbContext.ExecuteStoredProcedureList<Product>( //"EXEC [ProductLoadAllPaged] @CategoryId, @ManufacturerId, @ProductTagId, @FeaturedProducts, @PriceMin, @PriceMax, @Keywords, @SearchDescriptions, @FilteredSpecs, @LanguageId, @OrderBy, @PageIndex, @PageSize, @ShowHidden, @TotalRecords", "ProductLoadAllPaged", new SqlParameter { ParameterName = "CategoryId", Value = categoryId, SqlDbType = SqlDbType.Int }, new SqlParameter { ParameterName = "ManufacturerId", Value = manufacturerId, SqlDbType = SqlDbType.Int }, new SqlParameter { ParameterName = "ProductTagId", Value = productTagId, SqlDbType = SqlDbType.Int }, new SqlParameter { ParameterName = "FeaturedProducts", Value = featuredProducts.HasValue ? (object)featuredProducts.Value : DBNull.Value, SqlDbType = SqlDbType.Bit }, new SqlParameter { ParameterName = "PriceMin", Value = priceMin.HasValue ? (object)priceMin.Value : DBNull.Value, SqlDbType = SqlDbType.Decimal }, new SqlParameter { ParameterName = "PriceMax", Value = priceMax.HasValue ? (object)priceMax.Value : DBNull.Value, SqlDbType = SqlDbType.Decimal }, new SqlParameter { ParameterName = "Keywords", Value = keywords != null ? (object)keywords : DBNull.Value, SqlDbType = SqlDbType.NVarChar }, new SqlParameter { ParameterName = "SearchDescriptions", Value = searchDescriptions, SqlDbType = SqlDbType.Bit }, new SqlParameter { ParameterName = "FilteredSpecs", Value = commaSeparatedSpecIds != null ? (object)commaSeparatedSpecIds : DBNull.Value, SqlDbType = SqlDbType.NVarChar }, new SqlParameter { ParameterName = "LanguageId", Value = searchLocalizedValue ? languageId : 0, SqlDbType = SqlDbType.Int }, new SqlParameter { ParameterName = "OrderBy", Value = (int)orderBy, SqlDbType = SqlDbType.Int }, new SqlParameter { ParameterName = "PageIndex", Value = pageIndex, SqlDbType = SqlDbType.Int }, new SqlParameter { ParameterName = "PageSize", Value = pageSize, SqlDbType = SqlDbType.Int }, new SqlParameter { ParameterName = "ShowHidden", Value = showHidden, SqlDbType = SqlDbType.Bit }, pTotalRecords); int totalRecords = (pTotalRecords.Value != DBNull.Value) ? Convert.ToInt32(pTotalRecords.Value) : 0; return new PagedList<Product>(products, pageIndex, pageSize, totalRecords); } else { //stored procedures aren't supported. Use LINQ #region Search products //products var query = _productRepository.Table; query = query.Where(p => !p.Deleted); if (!showHidden) { query = query.Where(p => p.Published); } //searching by keyword if (!String.IsNullOrWhiteSpace(keywords)) { query = from p in query join lp in _localizedPropertyRepository.Table on p.Id equals lp.EntityId into p_lp from lp in p_lp.DefaultIfEmpty() from pv in p.ProductVariants.DefaultIfEmpty() where (p.Name.Contains(keywords)) || (searchDescriptions && p.ShortDescription.Contains(keywords)) || (searchDescriptions && p.FullDescription.Contains(keywords)) || (pv.Name.Contains(keywords)) || (searchDescriptions && pv.Description.Contains(keywords)) || //localized values (searchLocalizedValue && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "Name" && lp.LocaleValue.Contains(keywords)) || (searchDescriptions && searchLocalizedValue && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "ShortDescription" && lp.LocaleValue.Contains(keywords)) || (searchDescriptions && searchLocalizedValue && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "FullDescription" && lp.LocaleValue.Contains(keywords)) select p; } //product variants //The function 'CurrentUtcDateTime' is not supported by SQL Server Compact. //That's why we pass the date value var nowUtc = DateTime.UtcNow; query = from p in query from pv in p.ProductVariants.DefaultIfEmpty() where //deleted (showHidden || !pv.Deleted) && //published (showHidden || pv.Published) && //price min ( !priceMin.HasValue || //special price (specified price and valid date range) ((pv.SpecialPrice.HasValue && ((!pv.SpecialPriceStartDateTimeUtc.HasValue || pv.SpecialPriceStartDateTimeUtc.Value < nowUtc) && (!pv.SpecialPriceEndDateTimeUtc.HasValue || pv.SpecialPriceEndDateTimeUtc.Value > nowUtc))) && (pv.SpecialPrice >= priceMin.Value)) || //regular price (price isn't specified or date range isn't valid) ((!pv.SpecialPrice.HasValue || ((pv.SpecialPriceStartDateTimeUtc.HasValue && pv.SpecialPriceStartDateTimeUtc.Value > nowUtc) || (pv.SpecialPriceEndDateTimeUtc.HasValue && pv.SpecialPriceEndDateTimeUtc.Value < nowUtc))) && (pv.Price >= priceMin.Value)) ) && //price max ( !priceMax.HasValue || //special price (specified price and valid date range) ((pv.SpecialPrice.HasValue && ((!pv.SpecialPriceStartDateTimeUtc.HasValue || pv.SpecialPriceStartDateTimeUtc.Value < nowUtc) && (!pv.SpecialPriceEndDateTimeUtc.HasValue || pv.SpecialPriceEndDateTimeUtc.Value > nowUtc))) && (pv.SpecialPrice <= priceMax.Value)) || //regular price (price isn't specified or date range isn't valid) ((!pv.SpecialPrice.HasValue || ((pv.SpecialPriceStartDateTimeUtc.HasValue && pv.SpecialPriceStartDateTimeUtc.Value > nowUtc) || (pv.SpecialPriceEndDateTimeUtc.HasValue && pv.SpecialPriceEndDateTimeUtc.Value < nowUtc))) && (pv.Price <= priceMax.Value)) ) && //available dates (showHidden || (!pv.AvailableStartDateTimeUtc.HasValue || pv.AvailableStartDateTimeUtc.Value < nowUtc)) && (showHidden || (!pv.AvailableEndDateTimeUtc.HasValue || pv.AvailableEndDateTimeUtc.Value > nowUtc)) select p; //search by specs if (filteredSpecs != null && filteredSpecs.Count > 0) { query = from p in query where !filteredSpecs .Except( p.ProductSpecificationAttributes.Where(psa => psa.AllowFiltering).Select( psa => psa.SpecificationAttributeOptionId)) .Any() select p; } //category filtering if (categoryId > 0) { query = from p in query from pc in p.ProductCategories.Where(pc => pc.CategoryId == categoryId) where (!featuredProducts.HasValue || featuredProducts.Value == pc.IsFeaturedProduct) select p; } //manufacturer filtering if (manufacturerId > 0) { query = from p in query from pm in p.ProductManufacturers.Where(pm => pm.ManufacturerId == manufacturerId) where (!featuredProducts.HasValue || featuredProducts.Value == pm.IsFeaturedProduct) select p; } //related products filtering //if (relatedToProductId > 0) //{ // query = from p in query // join rp in _relatedProductRepository.Table on p.Id equals rp.ProductId2 // where (relatedToProductId == rp.ProductId1) // select p; //} //tag filtering if (productTagId > 0) { query = from p in query from pt in p.ProductTags.Where(pt => pt.Id == productTagId) select p; } //only distinct products (group by ID) //if we use standard Distinct() method, then all fields will be compared (low performance) //it'll not work in SQL Server Compact when searching products by a keyword) query = from p in query group p by p.Id into pGroup orderby pGroup.Key select pGroup.FirstOrDefault(); //sort products if (orderBy == ProductSortingEnum.Position && categoryId > 0) { //category position query = query.OrderBy(p => p.ProductCategories.Where(pc => pc.CategoryId == categoryId).FirstOrDefault().DisplayOrder); } else if (orderBy == ProductSortingEnum.Position && manufacturerId > 0) { //manufacturer position query = query.OrderBy(p => p.ProductManufacturers.Where(pm => pm.ManufacturerId == manufacturerId).FirstOrDefault().DisplayOrder); } //else if (orderBy == ProductSortingEnum.Position && relatedToProductId > 0) //{ // //sort by related product display order // query = from p in query // join rp in _relatedProductRepository.Table on p.Id equals rp.ProductId2 // where (relatedToProductId == rp.ProductId1) // orderby rp.DisplayOrder // select p; //} else if (orderBy == ProductSortingEnum.Position) { query = query.OrderBy(p => p.Name); } else if (orderBy == ProductSortingEnum.Name) { query = query.OrderBy(p => p.Name); } else if (orderBy == ProductSortingEnum.Price) { query = query.OrderBy(p => p.ProductVariants.FirstOrDefault().Price); } else if (orderBy == ProductSortingEnum.CreatedOn) query = query.OrderByDescending(p => p.CreatedOnUtc); else query = query.OrderBy(p => p.Name); var products = new PagedList<Product>(query, pageIndex, pageSize); return products; #endregion } }
/// <summary> The command characters are valid. </summary> /// <param name="candidate"> The List of characters to be checked against valid characters. </param> /// <returns> True if all characters are valid, else false. /// </returns> private bool CommandCharactersAreValid(IList <char> candidate) { return(!candidate.Except(this._validCharacters).Any()); }
private IEnumerable <RatingPool> GetLegendMateria2RatingPools(IList <CharacterRatingContextInfo> characterRatingContextInfos) { string lm2Tag = "LM2: "; IList <RatingPool> lm2RatingPools = characterRatingContextInfos.Where(c => c.LegendMateria2 != null).Select(c => c.LegendMateria2.Effect) .Distinct().Select(p => new RatingPool() { RatingPoolName = p }).ToList(); //who is in each mote combination based pool foreach (var pool in lm2RatingPools) { pool.CharactersInRatingPool = characterRatingContextInfos .Where(c => c.LegendMateria2?.Effect == pool.RatingPoolName).Select(c => c).ToList(); } //touch up select pools to unify names //trance RatingPool trancePool = new RatingPool() { RatingPoolName = "Trance", CharactersInRatingPool = new List <CharacterRatingContextInfo>() }; IList <RatingPool> tranceRatingPoolsToRemove = new List <RatingPool>(); foreach (var pool in lm2RatingPools) { if (pool.RatingPoolName.Contains("Trance")) { foreach (var character in pool.CharactersInRatingPool) { trancePool.CharactersInRatingPool.Add(character); } tranceRatingPoolsToRemove.Add(pool); } } lm2RatingPools = lm2RatingPools.Except(tranceRatingPoolsToRemove).ToList(); lm2RatingPools.Add(trancePool); //RatingPool adedPool = lm2RatingPools.FirstOrDefault(p => p.RatingPoolName == "Trance"); //QuickCast 3 RatingPool quickCastPool = new RatingPool() { RatingPoolName = "Quick Cast 3", CharactersInRatingPool = new List <CharacterRatingContextInfo>() }; IList <RatingPool> quickCastRatingPoolsToRemove = new List <RatingPool>(); foreach (var pool in lm2RatingPools) { if (pool.RatingPoolName.Contains("Quick Cast 3") && pool.CharactersInRatingPool.Count == 1) { foreach (var character in pool.CharactersInRatingPool) { quickCastPool.CharactersInRatingPool.Add(character); } quickCastRatingPoolsToRemove.Add(pool); } } lm2RatingPools = lm2RatingPools.Except(quickCastRatingPoolsToRemove).ToList(); lm2RatingPools.Add(quickCastPool); //Attack Buildup RatingPool atkBuildupPool = new RatingPool() { RatingPoolName = "Attack Buildup", CharactersInRatingPool = new List <CharacterRatingContextInfo>() }; IList <RatingPool> atkBuildupRatingPoolsToRemove = new List <RatingPool>(); foreach (var pool in lm2RatingPools) { if (pool.RatingPoolName.Contains("ATK +") && pool.RatingPoolName.Contains("each hit dealt") && pool.CharactersInRatingPool.Count == 1) { foreach (var character in pool.CharactersInRatingPool) { atkBuildupPool.CharactersInRatingPool.Add(character); } atkBuildupRatingPoolsToRemove.Add(pool); } } lm2RatingPools = lm2RatingPools.Except(atkBuildupRatingPoolsToRemove).ToList(); lm2RatingPools.Add(atkBuildupPool); //Minor Imperil RatingPool imperilPool = new RatingPool() { RatingPoolName = "Minor Imperil", CharactersInRatingPool = new List <CharacterRatingContextInfo>() }; IList <RatingPool> imperilRatingPoolsToRemove = new List <RatingPool>(); foreach (var pool in lm2RatingPools) { if (pool.RatingPoolName.Contains("chance to cause Minor Imperil") && pool.CharactersInRatingPool.Count == 1) { foreach (var character in pool.CharactersInRatingPool) { imperilPool.CharactersInRatingPool.Add(character); } imperilRatingPoolsToRemove.Add(pool); } } lm2RatingPools = lm2RatingPools.Except(imperilRatingPoolsToRemove).ToList(); lm2RatingPools.Add(imperilPool); //remove single member pools IList <RatingPool> singleMemberRatingPools = lm2RatingPools.Where(p => p.CharactersInRatingPool.Count == 1).ToList(); lm2RatingPools = lm2RatingPools.Except(singleMemberRatingPools).ToList(); //add in the lm 2 tag foreach (var pool in lm2RatingPools) { pool.RatingPoolName = $"{lm2Tag}{pool.RatingPoolName}"; } return(lm2RatingPools); }
private IInputElement SetPointerOver(IPointerDevice device, IInputRoot root, IList<IInputElement> elements) { foreach (var control in _pointerOvers.Except(elements).ToList()) { PointerEventArgs e = new PointerEventArgs { RoutedEvent = InputElement.PointerLeaveEvent, Device = device, Source = control, }; _pointerOvers.Remove(control); control.RaiseEvent(e); } foreach (var control in elements.Except(_pointerOvers)) { PointerEventArgs e = new PointerEventArgs { RoutedEvent = InputElement.PointerEnterEvent, Device = device, Source = control, }; _pointerOvers.Add(control); control.RaiseEvent(e); } root.PointerOverElement = elements.FirstOrDefault() ?? root; return root.PointerOverElement; }
/// <summary> /// Called when the children of the given path changed /// </summary> /// <param name="e">The <see cref="Kafka.Client.ZooKeeperIntegration.Events.ZooKeeperChildChangedEventArgs"/> instance containing the event data /// as parent path and children (null if parent was deleted). /// </param> public void HandleChildChange(ZooKeeperChildChangedEventArgs e) { Guard.NotNull(e, "e"); Guard.NotNullNorEmpty(e.Path, "e.Path"); Guard.NotNull(e.Children, "e.Children"); lock (this.syncLock) { try { string path = e.Path; IList <string> childs = e.Children; Logger.Debug("Watcher fired for path: " + path); switch (path) { case ZooKeeperClient.DefaultBrokerTopicsPath: List <string> oldTopics = this.oldBrokerTopicsPartitionsMap.Keys.ToList(); List <string> newTopics = childs.Except(oldTopics).ToList(); Logger.Debug("List of topics was changed at " + e.Path); Logger.Debug("Current topics -> " + e.Children.ToMultiString(",")); Logger.Debug("Old list of topics -> " + oldTopics.ToMultiString(",")); Logger.Debug("List of newly registered topics -> " + newTopics.ToMultiString(",")); foreach (var newTopic in newTopics) { string brokerTopicPath = ZooKeeperClient.DefaultBrokerTopicsPath + "/" + newTopic; IList <string> brokerList = this.zkclient.GetChildrenParentMayNotExist(brokerTopicPath); this.ProcessNewBrokerInExistingTopic(newTopic, brokerList); this.zkclient.Subscribe(ZooKeeperClient.DefaultBrokerTopicsPath + "/" + newTopic, this); } break; case ZooKeeperClient.DefaultBrokerIdsPath: Logger.Debug("List of brokers changed in the Kafka cluster " + e.Path); Logger.Debug("Currently registered list of brokers -> " + e.Children.ToMultiString(",")); this.ProcessBrokerChange(path, childs); break; default: string[] parts = path.Split('/'); string topic = parts.Last(); if (parts.Length == 4 && parts[2] == "topics" && childs != null) { Logger.Debug("List of brokers changed at " + path); Logger.Debug( "Currently registered list of brokers for topic " + topic + " -> " + childs.ToMultiString(",")); this.ProcessNewBrokerInExistingTopic(topic, childs); } break; } this.oldBrokerTopicsPartitionsMap = this.actualBrokerTopicsPartitionsMap; this.oldBrokerIdMap = this.actualBrokerIdMap; } catch (Exception exc) { Logger.Debug("Error while handling " + e, exc); } } }
public static CompilationUnitSyntax AddUsingDirectives( this CompilationUnitSyntax root, IList<UsingDirectiveSyntax> usingDirectives, bool placeSystemNamespaceFirst, params SyntaxAnnotation[] annotations) { if (usingDirectives.Count == 0) { return root; } var comparer = placeSystemNamespaceFirst ? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance : UsingsAndExternAliasesDirectiveComparer.NormalInstance; var usings = AddUsingDirectives(root, usingDirectives); // If the user likes to have their Usings statements unsorted, allow them to if (root.Usings.IsSorted(comparer)) { usings.Sort(comparer); } // If any using we added was moved to the first location, then take the trivia from // the start of the first token and add it to the using we added. This way things // like #define's and #r's will stay above the using. var firstUsingChanged = root.Usings.Count == 0 || usings[0] != root.Usings[0]; if (firstUsingChanged && root.Externs.Count == 0) { var firstToken = root.GetFirstToken(); // Move the leading directives from the first directive to the new using. var firstUsing = usings[0].WithLeadingTrivia(firstToken.LeadingTrivia.Where(t => !t.IsDocComment() && !t.IsElastic())); // Remove the leading directives from the first token. var newFirstToken = firstToken.WithLeadingTrivia(firstToken.LeadingTrivia.Where(t => t.IsDocComment() || t.IsElastic())); // Remove the leading trivia from the first token from the tree. root = root.ReplaceToken(firstToken, newFirstToken); // Create the new list of usings. var finalUsings = new List<UsingDirectiveSyntax>(); finalUsings.Add(firstUsing); finalUsings.AddRange(root.Usings); finalUsings.AddRange(usingDirectives.Except(new[] { usings[0] })); finalUsings.Sort(comparer); usings = finalUsings; } usings = usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToList(); return root.WithUsings(usings.ToSyntaxList()); }
private void SavePRMBOQTemplateItemMapEntity() { try { foreach (TreeNode catNode in treeItem.Nodes) { PrepareCurrentlyPopulatedMappedItems(catNode); } foreach (TreeNode tn in treeItem.CheckedNodes) { PRMBOQTemplateItemMapEntity ent = new PRMBOQTemplateItemMapEntity(); ent.ItemID = Int64.Parse(tn.Value.ToString()); ent.BOQTemplateID = BOQTemplateID; newMappedItems.Add(ent); } if (currentMappedItems.Count <= 0) { IList <PRMBOQTemplateItemMapEntity> unCheckedList = currentlyPopulatedMappedItems.Except(newMappedItems, new CustomerComparer()).ToList(); IList <PRMBOQTemplateItemMapEntity> templateItemList = new List <PRMBOQTemplateItemMapEntity>(); foreach (var v in temporaryMappedItems) { PRMBOQTemplateItemMapEntity ent = new PRMBOQTemplateItemMapEntity(); ent.ItemID = v.ItemID; ent.BOQTemplateID = BOQTemplateID; templateItemList.Add(ent); } IList <PRMBOQTemplateItemMapEntity> addCheckedList = templateItemList.Except(unCheckedList, new CustomerComparerAnother()).ToList(); Int64 i = 0; StringBuilder xmlStr = new StringBuilder(); xmlStr.Append("<m>"); String subXmlStr = null; foreach (PRMBOQTemplateItemMapEntity ent in addCheckedList) { i++; subXmlStr = subXmlStr + "<i><a>" + ent.BOQTemplateID + "</a><b>" + ent.ItemID + "</b><c>" + i + "</c></i>"; } xmlStr.Append(subXmlStr.ToString()); xmlStr.Append("</m>"); FCCBulkInsertXML.GetFacadeCreate().GetIL(xmlStr.ToString(), CommonConstants.BOQItemMapTableInfo); } else if (currentMappedItems.Count > 0) { currentlyPopulatedMappedItems = currentlyPopulatedMappedItems.Intersect(currentMappedItems, new CustomerComparer()).ToList(); IList <PRMBOQTemplateItemMapEntity> deleteList = currentlyPopulatedMappedItems.Except(newMappedItems, new CustomerComparer()).ToList(); IList <PRMBOQTemplateItemMapEntity> addNewList = newMappedItems.Except(currentlyPopulatedMappedItems, new CustomerComparer()).ToList(); if (deleteList != null && deleteList.Count > 0) { foreach (PRMBOQTemplateItemMapEntity ent in deleteList) { String fe1 = SqlExpressionBuilder.PrepareFilterExpression(PRMBOQTemplateItemMapEntity.FLD_NAME_BOQTemplateID, ent.BOQTemplateID.ToString(), SQLMatchType.Equal); String fe2 = SqlExpressionBuilder.PrepareFilterExpression(PRMBOQTemplateItemMapEntity.FLD_NAME_ItemID, ent.ItemID.ToString(), SQLMatchType.Equal); String fe = SqlExpressionBuilder.PrepareFilterExpression(fe1, SQLJoinType.AND, fe2); FCCPRMBOQTemplateItemMap.GetFacadeCreate().Delete(ent, fe, DatabaseOperationType.Delete, TransactionRequired.No); } } if (addNewList != null && addNewList.Count > 0) { foreach (PRMBOQTemplateItemMapEntity ent in addNewList) { FCCPRMBOQTemplateItemMap.GetFacadeCreate().Add(ent, DatabaseOperationType.Add, TransactionRequired.No); } } } MiscUtil.ShowMessage(lblMessage, "Template Project Cost Item Map Updated Successfully.", false); } catch (Exception ex) { MiscUtil.ShowMessage(lblMessage, "An Error Occoured.", true); } }
/// <summary> /// Search products /// </summary> /// <param name="filterableSpecificationAttributeOptionIds">The specification attribute option identifiers applied to loaded products (all pages)</param> /// <param name="loadFilterableSpecificationAttributeOptionIds">A value indicating whether we should load the specification attribute option identifiers applied to loaded products (all pages)</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="categoryIds">Category identifiers</param> /// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param> /// <param name="storeId">Store identifier; 0 to load all records</param> /// <param name="vendorId">Vendor identifier; 0 to load all records</param> /// <param name="warehouseId">Warehouse identifier; 0 to load all records</param> /// <param name="productType">Product type; 0 to load all records</param> /// <param name="visibleIndividuallyOnly">A values indicating whether to load only products marked as "visible individually"; "false" to load all records; "true" to load "visible individually" only</param> /// <param name="featuredProducts">A value indicating whether loaded products are marked as featured (relates only to categories and manufacturers). 0 to load featured products only, 1 to load not featured products only, null to load all products</param> /// <param name="priceMin">Minimum price; null to load all records</param> /// <param name="priceMax">Maximum price; null to load all records</param> /// <param name="productTagId">Product tag identifier; 0 to load all records</param> /// <param name="keywords">Keywords</param> /// <param name="searchDescriptions">A value indicating whether to search by a specified "keyword" in product descriptions</param> /// <param name="searchSku">A value indicating whether to search by a specified "keyword" in product SKU</param> /// <param name="searchProductTags">A value indicating whether to search by a specified "keyword" in product tags</param> /// <param name="languageId">Language identifier (search for text searching)</param> /// <param name="filteredSpecs">Filtered product specification identifiers</param> /// <param name="orderBy">Order by</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <param name="overridePublished"> /// null - process "Published" property according to "showHidden" parameter /// true - load only "Published" products /// false - load only "Unpublished" products /// </param> /// <returns>Products</returns> public virtual IPagedList<Product> SearchProducts( out IList<int> filterableSpecificationAttributeOptionIds, bool loadFilterableSpecificationAttributeOptionIds = false, int pageIndex = 0, int pageSize = 2147483647, //Int32.MaxValue IList<int> categoryIds = null, int manufacturerId = 0, int storeId = 0, int vendorId = 0, int warehouseId = 0, ProductType? productType = null, bool visibleIndividuallyOnly = false, bool? featuredProducts = null, decimal? priceMin = null, decimal? priceMax = null, int productTagId = 0, string keywords = null, bool searchDescriptions = false, bool searchSku = true, bool searchProductTags = false, int languageId = 0, IList<int> filteredSpecs = null, ProductSortingEnum orderBy = ProductSortingEnum.Position, bool showHidden = false, bool? overridePublished = null) { filterableSpecificationAttributeOptionIds = new List<int>(); //search by keyword bool searchLocalizedValue = false; if (languageId > 0) { if (showHidden) { searchLocalizedValue = true; } else { //ensure that we have at least two published languages var totalPublishedLanguages = _languageService.GetAllLanguages().Count; searchLocalizedValue = totalPublishedLanguages >= 2; } } //validate "categoryIds" parameter if (categoryIds !=null && categoryIds.Contains(0)) categoryIds.Remove(0); //Access control list. Allowed customer roles var allowedCustomerRolesIds = _workContext.CurrentCustomer.GetCustomerRoleIds(); if (_commonSettings.UseStoredProceduresIfSupported && _dataProvider.StoredProceduredSupported) { //stored procedures are enabled and supported by the database. //It's much faster than the LINQ implementation below #region Use stored procedure //pass category identifiers as comma-delimited string string commaSeparatedCategoryIds = categoryIds == null ? "" : string.Join(",", categoryIds); //pass customer role identifiers as comma-delimited string string commaSeparatedAllowedCustomerRoleIds = string.Join(",", allowedCustomerRolesIds); //pass specification identifiers as comma-delimited string string commaSeparatedSpecIds = ""; if (filteredSpecs != null) { ((List<int>)filteredSpecs).Sort(); commaSeparatedSpecIds = string.Join(",", filteredSpecs); } //some databases don't support int.MaxValue if (pageSize == int.MaxValue) pageSize = int.MaxValue - 1; //prepare parameters var pCategoryIds = _dataProvider.GetParameter(); pCategoryIds.ParameterName = "CategoryIds"; pCategoryIds.Value = commaSeparatedCategoryIds != null ? (object)commaSeparatedCategoryIds : DBNull.Value; pCategoryIds.DbType = DbType.String; var pManufacturerId = _dataProvider.GetParameter(); pManufacturerId.ParameterName = "ManufacturerId"; pManufacturerId.Value = manufacturerId; pManufacturerId.DbType = DbType.Int32; var pStoreId = _dataProvider.GetParameter(); pStoreId.ParameterName = "StoreId"; pStoreId.Value = !_catalogSettings.IgnoreStoreLimitations ? storeId : 0; pStoreId.DbType = DbType.Int32; var pVendorId = _dataProvider.GetParameter(); pVendorId.ParameterName = "VendorId"; pVendorId.Value = vendorId; pVendorId.DbType = DbType.Int32; var pWarehouseId = _dataProvider.GetParameter(); pWarehouseId.ParameterName = "WarehouseId"; pWarehouseId.Value = warehouseId; pWarehouseId.DbType = DbType.Int32; var pProductTypeId = _dataProvider.GetParameter(); pProductTypeId.ParameterName = "ProductTypeId"; pProductTypeId.Value = productType.HasValue ? (object)productType.Value : DBNull.Value; pProductTypeId.DbType = DbType.Int32; var pVisibleIndividuallyOnly = _dataProvider.GetParameter(); pVisibleIndividuallyOnly.ParameterName = "VisibleIndividuallyOnly"; pVisibleIndividuallyOnly.Value = visibleIndividuallyOnly; pVisibleIndividuallyOnly.DbType = DbType.Int32; var pProductTagId = _dataProvider.GetParameter(); pProductTagId.ParameterName = "ProductTagId"; pProductTagId.Value = productTagId; pProductTagId.DbType = DbType.Int32; var pFeaturedProducts = _dataProvider.GetParameter(); pFeaturedProducts.ParameterName = "FeaturedProducts"; pFeaturedProducts.Value = featuredProducts.HasValue ? (object)featuredProducts.Value : DBNull.Value; pFeaturedProducts.DbType = DbType.Boolean; var pPriceMin = _dataProvider.GetParameter(); pPriceMin.ParameterName = "PriceMin"; pPriceMin.Value = priceMin.HasValue ? (object)priceMin.Value : DBNull.Value; pPriceMin.DbType = DbType.Decimal; var pPriceMax = _dataProvider.GetParameter(); pPriceMax.ParameterName = "PriceMax"; pPriceMax.Value = priceMax.HasValue ? (object)priceMax.Value : DBNull.Value; pPriceMax.DbType = DbType.Decimal; var pKeywords = _dataProvider.GetParameter(); pKeywords.ParameterName = "Keywords"; pKeywords.Value = keywords != null ? (object)keywords : DBNull.Value; pKeywords.DbType = DbType.String; var pSearchDescriptions = _dataProvider.GetParameter(); pSearchDescriptions.ParameterName = "SearchDescriptions"; pSearchDescriptions.Value = searchDescriptions; pSearchDescriptions.DbType = DbType.Boolean; var pSearchSku = _dataProvider.GetParameter(); pSearchSku.ParameterName = "SearchSku"; pSearchSku.Value = searchSku; pSearchSku.DbType = DbType.Boolean; var pSearchProductTags = _dataProvider.GetParameter(); pSearchProductTags.ParameterName = "SearchProductTags"; pSearchProductTags.Value = searchProductTags; pSearchProductTags.DbType = DbType.Boolean; var pUseFullTextSearch = _dataProvider.GetParameter(); pUseFullTextSearch.ParameterName = "UseFullTextSearch"; pUseFullTextSearch.Value = _commonSettings.UseFullTextSearch; pUseFullTextSearch.DbType = DbType.Boolean; var pFullTextMode = _dataProvider.GetParameter(); pFullTextMode.ParameterName = "FullTextMode"; pFullTextMode.Value = (int)_commonSettings.FullTextMode; pFullTextMode.DbType = DbType.Int32; var pFilteredSpecs = _dataProvider.GetParameter(); pFilteredSpecs.ParameterName = "FilteredSpecs"; pFilteredSpecs.Value = commaSeparatedSpecIds != null ? (object)commaSeparatedSpecIds : DBNull.Value; pFilteredSpecs.DbType = DbType.String; var pLanguageId = _dataProvider.GetParameter(); pLanguageId.ParameterName = "LanguageId"; pLanguageId.Value = searchLocalizedValue ? languageId : 0; pLanguageId.DbType = DbType.Int32; var pOrderBy = _dataProvider.GetParameter(); pOrderBy.ParameterName = "OrderBy"; pOrderBy.Value = (int)orderBy; pOrderBy.DbType = DbType.Int32; var pAllowedCustomerRoleIds = _dataProvider.GetParameter(); pAllowedCustomerRoleIds.ParameterName = "AllowedCustomerRoleIds"; pAllowedCustomerRoleIds.Value = commaSeparatedAllowedCustomerRoleIds; pAllowedCustomerRoleIds.DbType = DbType.String; var pPageIndex = _dataProvider.GetParameter(); pPageIndex.ParameterName = "PageIndex"; pPageIndex.Value = pageIndex; pPageIndex.DbType = DbType.Int32; var pPageSize = _dataProvider.GetParameter(); pPageSize.ParameterName = "PageSize"; pPageSize.Value = pageSize; pPageSize.DbType = DbType.Int32; var pShowHidden = _dataProvider.GetParameter(); pShowHidden.ParameterName = "ShowHidden"; pShowHidden.Value = showHidden; pShowHidden.DbType = DbType.Boolean; var pOverridePublished = _dataProvider.GetParameter(); pOverridePublished.ParameterName = "OverridePublished"; pOverridePublished.Value = overridePublished != null ? (object)overridePublished.Value : DBNull.Value; pOverridePublished.DbType = DbType.Boolean; var pLoadFilterableSpecificationAttributeOptionIds = _dataProvider.GetParameter(); pLoadFilterableSpecificationAttributeOptionIds.ParameterName = "LoadFilterableSpecificationAttributeOptionIds"; pLoadFilterableSpecificationAttributeOptionIds.Value = loadFilterableSpecificationAttributeOptionIds; pLoadFilterableSpecificationAttributeOptionIds.DbType = DbType.Boolean; var pFilterableSpecificationAttributeOptionIds = _dataProvider.GetParameter(); pFilterableSpecificationAttributeOptionIds.ParameterName = "FilterableSpecificationAttributeOptionIds"; pFilterableSpecificationAttributeOptionIds.Direction = ParameterDirection.Output; pFilterableSpecificationAttributeOptionIds.Size = int.MaxValue - 1; pFilterableSpecificationAttributeOptionIds.DbType = DbType.String; var pTotalRecords = _dataProvider.GetParameter(); pTotalRecords.ParameterName = "TotalRecords"; pTotalRecords.Direction = ParameterDirection.Output; pTotalRecords.DbType = DbType.Int32; //invoke stored procedure var products = _dbContext.ExecuteStoredProcedureList<Product>( "ProductLoadAllPaged", pCategoryIds, pManufacturerId, pStoreId, pVendorId, pWarehouseId, pProductTypeId, pVisibleIndividuallyOnly, pProductTagId, pFeaturedProducts, pPriceMin, pPriceMax, pKeywords, pSearchDescriptions, pSearchSku, pSearchProductTags, pUseFullTextSearch, pFullTextMode, pFilteredSpecs, pLanguageId, pOrderBy, pAllowedCustomerRoleIds, pPageIndex, pPageSize, pShowHidden, pOverridePublished, pLoadFilterableSpecificationAttributeOptionIds, pFilterableSpecificationAttributeOptionIds, pTotalRecords); //get filterable specification attribute option identifier string filterableSpecificationAttributeOptionIdsStr = (pFilterableSpecificationAttributeOptionIds.Value != DBNull.Value) ? (string)pFilterableSpecificationAttributeOptionIds.Value : ""; if (loadFilterableSpecificationAttributeOptionIds && !string.IsNullOrWhiteSpace(filterableSpecificationAttributeOptionIdsStr)) { filterableSpecificationAttributeOptionIds = filterableSpecificationAttributeOptionIdsStr .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries) .Select(x => Convert.ToInt32(x.Trim())) .ToList(); } //return products int totalRecords = (pTotalRecords.Value != DBNull.Value) ? Convert.ToInt32(pTotalRecords.Value) : 0; return new PagedList<Product>(products, pageIndex, pageSize, totalRecords); #endregion } else { //stored procedures aren't supported. Use LINQ #region Search products //products var query = _productRepository.Table; query = query.Where(p => !p.Deleted); if (!overridePublished.HasValue) { //process according to "showHidden" if (!showHidden) { query = query.Where(p => p.Published); } } else if (overridePublished.Value) { //published only query = query.Where(p => p.Published); } else if (!overridePublished.Value) { //unpublished only query = query.Where(p => !p.Published); } if (visibleIndividuallyOnly) { query = query.Where(p => p.VisibleIndividually); } if (productType.HasValue) { var productTypeId = (int) productType.Value; query = query.Where(p => p.ProductTypeId == productTypeId); } //The function 'CurrentUtcDateTime' is not supported by SQL Server Compact. //That's why we pass the date value var nowUtc = DateTime.UtcNow; if (priceMin.HasValue) { //min price query = query.Where(p => //special price (specified price and valid date range) ((p.SpecialPrice.HasValue && ((!p.SpecialPriceStartDateTimeUtc.HasValue || p.SpecialPriceStartDateTimeUtc.Value < nowUtc) && (!p.SpecialPriceEndDateTimeUtc.HasValue || p.SpecialPriceEndDateTimeUtc.Value > nowUtc))) && (p.SpecialPrice >= priceMin.Value)) || //regular price (price isn't specified or date range isn't valid) ((!p.SpecialPrice.HasValue || ((p.SpecialPriceStartDateTimeUtc.HasValue && p.SpecialPriceStartDateTimeUtc.Value > nowUtc) || (p.SpecialPriceEndDateTimeUtc.HasValue && p.SpecialPriceEndDateTimeUtc.Value < nowUtc))) && (p.Price >= priceMin.Value))); } if (priceMax.HasValue) { //max price query = query.Where(p => //special price (specified price and valid date range) ((p.SpecialPrice.HasValue && ((!p.SpecialPriceStartDateTimeUtc.HasValue || p.SpecialPriceStartDateTimeUtc.Value < nowUtc) && (!p.SpecialPriceEndDateTimeUtc.HasValue || p.SpecialPriceEndDateTimeUtc.Value > nowUtc))) && (p.SpecialPrice <= priceMax.Value)) || //regular price (price isn't specified or date range isn't valid) ((!p.SpecialPrice.HasValue || ((p.SpecialPriceStartDateTimeUtc.HasValue && p.SpecialPriceStartDateTimeUtc.Value > nowUtc) || (p.SpecialPriceEndDateTimeUtc.HasValue && p.SpecialPriceEndDateTimeUtc.Value < nowUtc))) && (p.Price <= priceMax.Value))); } if (!showHidden) { //available dates query = query.Where(p => (!p.AvailableStartDateTimeUtc.HasValue || p.AvailableStartDateTimeUtc.Value < nowUtc) && (!p.AvailableEndDateTimeUtc.HasValue || p.AvailableEndDateTimeUtc.Value > nowUtc)); } //searching by keyword if (!String.IsNullOrWhiteSpace(keywords)) { query = from p in query join lp in _localizedPropertyRepository.Table on p.Id equals lp.EntityId into p_lp from lp in p_lp.DefaultIfEmpty() from pt in p.ProductTags.DefaultIfEmpty() where (p.Name.Contains(keywords)) || (searchDescriptions && p.ShortDescription.Contains(keywords)) || (searchDescriptions && p.FullDescription.Contains(keywords)) || (searchProductTags && pt.Name.Contains(keywords)) || //localized values (searchLocalizedValue && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "Name" && lp.LocaleValue.Contains(keywords)) || (searchDescriptions && searchLocalizedValue && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "ShortDescription" && lp.LocaleValue.Contains(keywords)) || (searchDescriptions && searchLocalizedValue && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "FullDescription" && lp.LocaleValue.Contains(keywords)) select p; } if (!showHidden && !_catalogSettings.IgnoreAcl) { //ACL (access control list) query = from p in query join acl in _aclRepository.Table on new { c1 = p.Id, c2 = "Product" } equals new { c1 = acl.EntityId, c2 = acl.EntityName } into p_acl from acl in p_acl.DefaultIfEmpty() where !p.SubjectToAcl || allowedCustomerRolesIds.Contains(acl.CustomerRoleId) select p; } if (storeId > 0 && !_catalogSettings.IgnoreStoreLimitations) { //Store mapping query = from p in query join sm in _storeMappingRepository.Table on new { c1 = p.Id, c2 = "Product" } equals new { c1 = sm.EntityId, c2 = sm.EntityName } into p_sm from sm in p_sm.DefaultIfEmpty() where !p.LimitedToStores || storeId == sm.StoreId select p; } //search by specs if (filteredSpecs != null && filteredSpecs.Count > 0) { query = from p in query where !filteredSpecs .Except( p.ProductSpecificationAttributes.Where(psa => psa.AllowFiltering).Select( psa => psa.SpecificationAttributeOptionId)) .Any() select p; } //category filtering if (categoryIds != null && categoryIds.Count > 0) { query = from p in query from pc in p.ProductCategories.Where(pc => categoryIds.Contains(pc.CategoryId)) where (!featuredProducts.HasValue || featuredProducts.Value == pc.IsFeaturedProduct) select p; } //manufacturer filtering if (manufacturerId > 0) { query = from p in query from pm in p.ProductManufacturers.Where(pm => pm.ManufacturerId == manufacturerId) where (!featuredProducts.HasValue || featuredProducts.Value == pm.IsFeaturedProduct) select p; } //vendor filtering if (vendorId > 0) { query = query.Where(p => p.VendorId == vendorId); } //warehouse filtering if (warehouseId > 0) { var manageStockInventoryMethodId = (int)ManageInventoryMethod.ManageStock; query = query.Where(p => //"Use multiple warehouses" enabled //we search in each warehouse (p.ManageInventoryMethodId == manageStockInventoryMethodId && p.UseMultipleWarehouses && p.ProductWarehouseInventory.Any(pwi => pwi.WarehouseId == warehouseId)) || //"Use multiple warehouses" disabled //we use standard "warehouse" property ((p.ManageInventoryMethodId != manageStockInventoryMethodId || !p.UseMultipleWarehouses) && p.WarehouseId == warehouseId)); } //related products filtering //if (relatedToProductId > 0) //{ // query = from p in query // join rp in _relatedProductRepository.Table on p.Id equals rp.ProductId2 // where (relatedToProductId == rp.ProductId1) // select p; //} //tag filtering if (productTagId > 0) { query = from p in query from pt in p.ProductTags.Where(pt => pt.Id == productTagId) select p; } //only distinct products (group by ID) //if we use standard Distinct() method, then all fields will be compared (low performance) //it'll not work in SQL Server Compact when searching products by a keyword) query = from p in query group p by p.Id into pGroup orderby pGroup.Key select pGroup.FirstOrDefault(); //sort products if (orderBy == ProductSortingEnum.Position && categoryIds != null && categoryIds.Count > 0) { //category position var firstCategoryId = categoryIds[0]; query = query.OrderBy(p => p.ProductCategories.FirstOrDefault(pc => pc.CategoryId == firstCategoryId).DisplayOrder); } else if (orderBy == ProductSortingEnum.Position && manufacturerId > 0) { //manufacturer position query = query.OrderBy(p => p.ProductManufacturers.FirstOrDefault(pm => pm.ManufacturerId == manufacturerId).DisplayOrder); } else if (orderBy == ProductSortingEnum.Position) { //otherwise sort by name query = query.OrderBy(p => p.Name); } else if (orderBy == ProductSortingEnum.NameAsc) { //Name: A to Z query = query.OrderBy(p => p.Name); } else if (orderBy == ProductSortingEnum.NameDesc) { //Name: Z to A query = query.OrderByDescending(p => p.Name); } else if (orderBy == ProductSortingEnum.PriceAsc) { //Price: Low to High query = query.OrderBy(p => p.Price); } else if (orderBy == ProductSortingEnum.PriceDesc) { //Price: High to Low query = query.OrderByDescending(p => p.Price); } else if (orderBy == ProductSortingEnum.CreatedOn) { //creation date query = query.OrderByDescending(p => p.CreatedOnUtc); } else { //actually this code is not reachable query = query.OrderBy(p => p.Name); } var products = new PagedList<Product>(query, pageIndex, pageSize); //get filterable specification attribute option identifier if (loadFilterableSpecificationAttributeOptionIds) { var querySpecs = from p in query join psa in _productSpecificationAttributeRepository.Table on p.Id equals psa.ProductId where psa.AllowFiltering select psa.SpecificationAttributeOptionId; //only distinct attributes filterableSpecificationAttributeOptionIds = querySpecs .Distinct() .ToList(); } //return products return products; #endregion } }
public async Task <ActionResult> Edit([Bind(Include = "Email, Id")] EditUserViewModel editUser, params string[] selectedRole) { ApplicationUser user = null; IList <string> userRoles = null; if (ModelState.IsValid) { // Edit User Data is Valid user = await UserManager.FindByIdAsync(editUser.Id); if (user == null) { return(HttpNotFound()); } user.UserName = editUser.Email; user.Email = editUser.Email; userRoles = await UserManager.GetRolesAsync(user.Id); // If SelectedRoles is null, then add Empty String selectedRole = selectedRole ?? new string[] { }; // Only add newly added roles, do not add already added roles. var result = await UserManager.AddToRolesAsync(user.Id, selectedRole.Except(userRoles).ToArray <string>()); if (!result.Succeeded) { ModelState.AddModelError("", result.Errors.First()); user = await UserManager.FindByIdAsync(editUser.Id); userRoles = await UserManager.GetRolesAsync(user.Id); return(View(new EditUserViewModel() { Id = user.Id, Email = user.Email, RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem() { Selected = userRoles.Contains(x.Name), Text = x.Name, Value = x.Name }) })); } // Remove all Roles other than selected roles. result = await UserManager.RemoveFromRolesAsync(user.Id, userRoles.Except(selectedRole).ToArray <string>()); if (!result.Succeeded) { ModelState.AddModelError("", result.Errors.First()); user = await UserManager.FindByIdAsync(editUser.Id); userRoles = await UserManager.GetRolesAsync(user.Id); return(View(new EditUserViewModel() { Id = user.Id, Email = user.Email, RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem() { Selected = userRoles.Contains(x.Name), Text = x.Name, Value = x.Name }) })); } return(RedirectToAction("Index")); } ModelState.AddModelError("", "Something failed."); //return RedirectToAction("Edit", routeValues: new { id = editUser.Id } ); user = await UserManager.FindByIdAsync(editUser.Id); userRoles = await UserManager.GetRolesAsync(user.Id); return(View(new EditUserViewModel() { Id = user.Id, Email = user.Email, RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem() { Selected = userRoles.Contains(x.Name), Text = x.Name, Value = x.Name }) })); //return View(ViewModel); //return View(GetUserFormViewModel(editUser.Id).Result); }
/// <summary> /// Search products /// </summary> /// <param name="categoryIds">Category identifiers</param> /// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param> /// <param name="featuredProducts">A value indicating whether loaded products are marked as featured (relates only to categories and manufacturers). 0 to load featured products only, 1 to load not featured products only, null to load all products</param> /// <param name="priceMin">Minimum price; null to load all records</param> /// <param name="priceMax">Maximum price; null to load all records</param> /// <param name="productTagId">Product tag identifier; 0 to load all records</param> /// <param name="keywords">Keywords</param> /// <param name="searchDescriptions">A value indicating whether to search in descriptions</param> /// <param name="languageId">Language identifier</param> /// <param name="filteredSpecs">Filtered product specification identifiers</param> /// <param name="orderBy">Order by</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="loadFilterableSpecificationAttributeOptionIds">A value indicating whether we should load the specification attribute option identifiers applied to loaded products (all pages)</param> /// <param name="filterableSpecificationAttributeOptionIds">The specification attribute option identifiers applied to loaded products (all pages)</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Product collection</returns> public virtual IPagedList<Product> SearchProducts(IList<int> categoryIds, int manufacturerId, bool? featuredProducts, decimal? priceMin, decimal? priceMax, int productTagId, string keywords, bool searchDescriptions, int languageId, IList<int> filteredSpecs, ProductSortingEnum orderBy, int pageIndex, int pageSize, bool loadFilterableSpecificationAttributeOptionIds, out IList<int> filterableSpecificationAttributeOptionIds, bool showHidden = false) { filterableSpecificationAttributeOptionIds = new List<int>(); bool searchLocalizedValue = false; if (languageId > 0) { if (showHidden) { searchLocalizedValue = true; } else { //ensure that we have at least two published languages var totalPublishedLanguages = _languageService.GetAllLanguages(false).Count; searchLocalizedValue = totalPublishedLanguages >= 2; } } if (_commonSettings.UseStoredProceduresIfSupported && _dataProvider.StoredProceduredSupported) { //stored procedures are enabled and supported by the database. //It's much faster than the LINQ implementation below #region Use stored procedure //pass categry identifiers as comma-delimited string string commaSeparatedCategoryIds = ""; if (categoryIds != null) { for (int i = 0; i < categoryIds.Count; i++) { commaSeparatedCategoryIds += categoryIds[i].ToString(); if (i != categoryIds.Count - 1) { commaSeparatedCategoryIds += ","; } } } //pass specification identifiers as comma-delimited string string commaSeparatedSpecIds = ""; if (filteredSpecs != null) { ((List<int>)filteredSpecs).Sort(); for (int i = 0; i < filteredSpecs.Count; i++) { commaSeparatedSpecIds += filteredSpecs[i].ToString(); if (i != filteredSpecs.Count - 1) { commaSeparatedSpecIds += ","; } } } //some databases don't support int.MaxValue if (pageSize == int.MaxValue) pageSize = int.MaxValue - 1; //prepare parameters var pCategoryIds = _dataProvider.GetParameter(); pCategoryIds.ParameterName = "CategoryIds"; pCategoryIds.Value = commaSeparatedCategoryIds != null ? (object)commaSeparatedCategoryIds : DBNull.Value; pCategoryIds.DbType = DbType.String; var pManufacturerId = _dataProvider.GetParameter(); pManufacturerId.ParameterName = "ManufacturerId"; pManufacturerId.Value = manufacturerId; pManufacturerId.DbType = DbType.Int32; var pProductTagId = _dataProvider.GetParameter(); pProductTagId.ParameterName = "ProductTagId"; pProductTagId.Value = productTagId; pProductTagId.DbType = DbType.Int32; var pFeaturedProducts = _dataProvider.GetParameter(); pFeaturedProducts.ParameterName = "FeaturedProducts"; pFeaturedProducts.Value = featuredProducts.HasValue ? (object)featuredProducts.Value : DBNull.Value; pFeaturedProducts.DbType = DbType.Boolean; var pPriceMin = _dataProvider.GetParameter(); pPriceMin.ParameterName = "PriceMin"; pPriceMin.Value = priceMin.HasValue ? (object)priceMin.Value : DBNull.Value; pPriceMin.DbType = DbType.Decimal; var pPriceMax = _dataProvider.GetParameter(); pPriceMax.ParameterName = "PriceMax"; pPriceMax.Value = priceMax.HasValue ? (object)priceMax.Value : DBNull.Value; pPriceMax.DbType = DbType.Decimal; var pKeywords = _dataProvider.GetParameter(); pKeywords.ParameterName = "Keywords"; pKeywords.Value = keywords != null ? (object)keywords : DBNull.Value; pKeywords.DbType = DbType.String; var pSearchDescriptions = _dataProvider.GetParameter(); pSearchDescriptions.ParameterName = "SearchDescriptions"; pSearchDescriptions.Value = searchDescriptions; pSearchDescriptions.DbType = DbType.Boolean; var pFilteredSpecs = _dataProvider.GetParameter(); pFilteredSpecs.ParameterName = "FilteredSpecs"; pFilteredSpecs.Value = commaSeparatedSpecIds != null ? (object)commaSeparatedSpecIds : DBNull.Value; pFilteredSpecs.DbType = DbType.String; var pLanguageId = _dataProvider.GetParameter(); pLanguageId.ParameterName = "LanguageId"; pLanguageId.Value = searchLocalizedValue ? languageId : 0; pLanguageId.DbType = DbType.Int32; var pOrderBy = _dataProvider.GetParameter(); pOrderBy.ParameterName = "OrderBy"; pOrderBy.Value = (int)orderBy; pOrderBy.DbType = DbType.Int32; var pPageIndex = _dataProvider.GetParameter(); pPageIndex.ParameterName = "PageIndex"; pPageIndex.Value = pageIndex; pPageIndex.DbType = DbType.Int32; var pPageSize = _dataProvider.GetParameter(); pPageSize.ParameterName = "PageSize"; pPageSize.Value = pageSize; pPageSize.DbType = DbType.Int32; var pShowHidden = _dataProvider.GetParameter(); pShowHidden.ParameterName = "ShowHidden"; pShowHidden.Value = showHidden; pShowHidden.DbType = DbType.Boolean; var pLoadFilterableSpecificationAttributeOptionIds = _dataProvider.GetParameter(); pLoadFilterableSpecificationAttributeOptionIds.ParameterName = "LoadFilterableSpecificationAttributeOptionIds"; pLoadFilterableSpecificationAttributeOptionIds.Value = loadFilterableSpecificationAttributeOptionIds; pLoadFilterableSpecificationAttributeOptionIds.DbType = DbType.Boolean; var pFilterableSpecificationAttributeOptionIds = _dataProvider.GetParameter(); pFilterableSpecificationAttributeOptionIds.ParameterName = "FilterableSpecificationAttributeOptionIds"; pFilterableSpecificationAttributeOptionIds.Direction = ParameterDirection.Output; pFilterableSpecificationAttributeOptionIds.Size = 100; pFilterableSpecificationAttributeOptionIds.DbType = DbType.String; var pTotalRecords = _dataProvider.GetParameter(); pTotalRecords.ParameterName = "TotalRecords"; pTotalRecords.Direction = ParameterDirection.Output; pTotalRecords.DbType = DbType.Int32; //invoke stored procedure var products = _dbContext.ExecuteStoredProcedureList<Product>( //"EXEC [ProductLoadAllPaged] @CategoryId, @ManufacturerId, @ProductTagId, @FeaturedProducts, @PriceMin, @PriceMax, @Keywords, @SearchDescriptions, @FilteredSpecs, @LanguageId, @OrderBy, @PageIndex, @PageSize, @ShowHidden, @TotalRecords", "ProductLoadAllPaged", pCategoryIds, pManufacturerId, pProductTagId, pFeaturedProducts, pPriceMin, pPriceMax, pKeywords, pSearchDescriptions, pFilteredSpecs, pLanguageId, pOrderBy, pPageIndex, pPageSize, pShowHidden, pLoadFilterableSpecificationAttributeOptionIds, pFilterableSpecificationAttributeOptionIds, pTotalRecords); //get filterable specification attribute option identifier string filterableSpecificationAttributeOptionIdsStr = (pFilterableSpecificationAttributeOptionIds.Value != DBNull.Value) ? (string)pFilterableSpecificationAttributeOptionIds.Value : ""; if (loadFilterableSpecificationAttributeOptionIds && !string.IsNullOrWhiteSpace(filterableSpecificationAttributeOptionIdsStr)) { filterableSpecificationAttributeOptionIds = filterableSpecificationAttributeOptionIdsStr .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries) .Select(x => Convert.ToInt32(x.Trim())) .ToList(); } //return products int totalRecords = (pTotalRecords.Value != DBNull.Value) ? Convert.ToInt32(pTotalRecords.Value) : 0; return new PagedList<Product>(products, pageIndex, pageSize, totalRecords); #endregion } else { //stored procedures aren't supported. Use LINQ #region Search products //products var query = _productRepository.Table; query = query.Where(p => !p.Deleted); if (!showHidden) { query = query.Where(p => p.Published); } //searching by keyword if (!String.IsNullOrWhiteSpace(keywords)) { query = from p in query join lp in _localizedPropertyRepository.Table on p.Id equals lp.EntityId into p_lp from lp in p_lp.DefaultIfEmpty() from pv in p.ProductVariants.DefaultIfEmpty() where (p.Name.Contains(keywords)) || (searchDescriptions && p.ShortDescription.Contains(keywords)) || (searchDescriptions && p.FullDescription.Contains(keywords)) || (pv.Name.Contains(keywords)) || (searchDescriptions && pv.Description.Contains(keywords)) || //localized values (searchLocalizedValue && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "Name" && lp.LocaleValue.Contains(keywords)) || (searchDescriptions && searchLocalizedValue && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "ShortDescription" && lp.LocaleValue.Contains(keywords)) || (searchDescriptions && searchLocalizedValue && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "FullDescription" && lp.LocaleValue.Contains(keywords)) select p; } //product variants //The function 'CurrentUtcDateTime' is not supported by SQL Server Compact. //That's why we pass the date value var nowUtc = DateTime.UtcNow; query = from p in query from pv in p.ProductVariants.DefaultIfEmpty() where //deleted (showHidden || !pv.Deleted) && //published (showHidden || pv.Published) && //price min ( !priceMin.HasValue || //special price (specified price and valid date range) ((pv.SpecialPrice.HasValue && ((!pv.SpecialPriceStartDateTimeUtc.HasValue || pv.SpecialPriceStartDateTimeUtc.Value < nowUtc) && (!pv.SpecialPriceEndDateTimeUtc.HasValue || pv.SpecialPriceEndDateTimeUtc.Value > nowUtc))) && (pv.SpecialPrice >= priceMin.Value)) || //regular price (price isn't specified or date range isn't valid) ((!pv.SpecialPrice.HasValue || ((pv.SpecialPriceStartDateTimeUtc.HasValue && pv.SpecialPriceStartDateTimeUtc.Value > nowUtc) || (pv.SpecialPriceEndDateTimeUtc.HasValue && pv.SpecialPriceEndDateTimeUtc.Value < nowUtc))) && (pv.Price >= priceMin.Value)) ) && //price max ( !priceMax.HasValue || //special price (specified price and valid date range) ((pv.SpecialPrice.HasValue && ((!pv.SpecialPriceStartDateTimeUtc.HasValue || pv.SpecialPriceStartDateTimeUtc.Value < nowUtc) && (!pv.SpecialPriceEndDateTimeUtc.HasValue || pv.SpecialPriceEndDateTimeUtc.Value > nowUtc))) && (pv.SpecialPrice <= priceMax.Value)) || //regular price (price isn't specified or date range isn't valid) ((!pv.SpecialPrice.HasValue || ((pv.SpecialPriceStartDateTimeUtc.HasValue && pv.SpecialPriceStartDateTimeUtc.Value > nowUtc) || (pv.SpecialPriceEndDateTimeUtc.HasValue && pv.SpecialPriceEndDateTimeUtc.Value < nowUtc))) && (pv.Price <= priceMax.Value)) ) && //available dates (showHidden || (!pv.AvailableStartDateTimeUtc.HasValue || pv.AvailableStartDateTimeUtc.Value < nowUtc)) && (showHidden || (!pv.AvailableEndDateTimeUtc.HasValue || pv.AvailableEndDateTimeUtc.Value > nowUtc)) select p; //search by specs if (filteredSpecs != null && filteredSpecs.Count > 0) { query = from p in query where !filteredSpecs .Except( p.ProductSpecificationAttributes.Where(psa => psa.AllowFiltering).Select( psa => psa.SpecificationAttributeOptionId)) .Any() select p; } //category filtering if (categoryIds != null && categoryIds.Count > 0) { //search in subcategories query = from p in query from pc in p.ProductCategories.Where(pc => categoryIds.Contains(pc.CategoryId)) where (!featuredProducts.HasValue || featuredProducts.Value == pc.IsFeaturedProduct) select p; } //manufacturer filtering if (manufacturerId > 0) { query = from p in query from pm in p.ProductManufacturers.Where(pm => pm.ManufacturerId == manufacturerId) where (!featuredProducts.HasValue || featuredProducts.Value == pm.IsFeaturedProduct) select p; } //related products filtering //if (relatedToProductId > 0) //{ // query = from p in query // join rp in _relatedProductRepository.Table on p.Id equals rp.ProductId2 // where (relatedToProductId == rp.ProductId1) // select p; //} //tag filtering if (productTagId > 0) { query = from p in query from pt in p.ProductTags.Where(pt => pt.Id == productTagId) select p; } //only distinct products (group by ID) //if we use standard Distinct() method, then all fields will be compared (low performance) //it'll not work in SQL Server Compact when searching products by a keyword) query = from p in query group p by p.Id into pGroup orderby pGroup.Key select pGroup.FirstOrDefault(); //sort products if (orderBy == ProductSortingEnum.Position && categoryIds != null && categoryIds.Count > 0) { //category position var firstCategoryId = categoryIds[0]; query = query.OrderBy(p => p.ProductCategories.Where(pc => pc.CategoryId == firstCategoryId).FirstOrDefault().DisplayOrder); } else if (orderBy == ProductSortingEnum.Position && manufacturerId > 0) { //manufacturer position query = query.OrderBy(p => p.ProductManufacturers.Where(pm => pm.ManufacturerId == manufacturerId).FirstOrDefault().DisplayOrder); } //else if (orderBy == ProductSortingEnum.Position && relatedToProductId > 0) //{ // //sort by related product display order // query = from p in query // join rp in _relatedProductRepository.Table on p.Id equals rp.ProductId2 // where (relatedToProductId == rp.ProductId1) // orderby rp.DisplayOrder // select p; //} else if (orderBy == ProductSortingEnum.Position) { //sort by name (there's no any position if category or manufactur is not specified) query = query.OrderBy(p => p.Name); } else if (orderBy == ProductSortingEnum.NameAsc) { //Name: A to Z query = query.OrderBy(p => p.Name); } else if (orderBy == ProductSortingEnum.NameDesc) { //Name: Z to A query = query.OrderByDescending(p => p.Name); } else if (orderBy == ProductSortingEnum.PriceAsc) { //Price: Low to High query = query.OrderBy(p => p.ProductVariants.FirstOrDefault().Price); } else if (orderBy == ProductSortingEnum.PriceDesc) { //Price: High to Low query = query.OrderByDescending(p => p.ProductVariants.FirstOrDefault().Price); } else if (orderBy == ProductSortingEnum.CreatedOn) { //creation date query = query.OrderByDescending(p => p.CreatedOnUtc); } else { //actually this code is not reachable query = query.OrderBy(p => p.Name); } var products = new PagedList<Product>(query, pageIndex, pageSize); //get filterable specification attribute option identifier if (loadFilterableSpecificationAttributeOptionIds) { var querySpecs = from p in query join psa in _productSpecificationAttributeRepository.Table on p.Id equals psa.ProductId where psa.AllowFiltering select psa.SpecificationAttributeOptionId; //only distinct attributes filterableSpecificationAttributeOptionIds = querySpecs .Distinct() .ToList(); } //return products return products; #endregion } }
/// <summary> /// Merges a list of entities. These entities must be static and contain a visual component only. /// </summary> /// <param name="entitiesToMerge">Entites to merge.</param> /// <returns>Merged list of entities.</returns> public List<Entity> MergeStaticVisualEntities(IList<Entity> entitiesToMerge) { var entitiesToMergeList = entitiesToMerge.Where(IsVisualEntityToMerge).ToArray(); var entitiesNotToMerge = entitiesToMerge.Except(entitiesToMergeList).ToArray(); var entitiesByCategory = entitiesToMergeList.GroupBy(e => e.GetComponent<ModelEntityComponent>().Material.CompareId); var mergedEntities = new List<Entity>(); foreach (var entityListToMerge in entitiesByCategory) { if (entityListToMerge.Count() == 1) continue; var entity = CreateEntity(true); var mergeData = entityListToMerge.Select(ConvertEntityToGeometryMerge); var mergedGeometry = GeometryData.Merge(mergeData); Mesh mergedMesh = null; GameInstance.EnsureExecutedInMainThread(() => mergedMesh = new Mesh(GameController.Instance.GraphicsDevice, mergedGeometry)); var material = entityListToMerge.First().GetComponent<ModelEntityComponent>().Material; material.TexcoordOffset = Vector2.Zero; material.TexcoordScale = Vector2.One; entity.AddComponent(new ModelEntityComponent(entity, mergedMesh, material, false)); foreach (var entityToRemove in entityListToMerge) { RemoveEntity(entityToRemove); } mergedEntities.Add(entity); } return mergedEntities.Concat(entitiesNotToMerge).ToList(); }