///<summary> /// Find ///</summary> ///<param name="predicate"></param> ///<typeparam name="T"></typeparam> ///<returns></returns> public IEnumerable <KeyValuePair <string, T> > Find <T>(Func <T, bool> predicate, Func <KeyValuePair <string, T>, bool> SomethingElse) { using (TimedLock.Lock(_sharedLock, new TimeSpan(0, 0, 10, 0))) //TODO: timeout süresini config'e al { return(((IEnumerable <KeyValuePair <string, T> >)CacheObject.AsQueryable()).Where(SomethingElse)); } }
public CardHitCountResponse GetCardHitCount(int start = 1, int limit = 3) { if (HitCount.Count == 0) { return(new CardHitCountResponse() { limit = 1, start = start, payload = null, success = true, size = HitCount.Count }); } var index = (start - 1) * limit; var skippedData = HitCount.AsQueryable().Skip(index).Take(limit); var buildUpPayload = from c in HitCount select new { CardPan = c.Key, CardPanHitCount = c.Value }; //StringBuilder bb = new StringBuilder(); return(new CardHitCountResponse() { success = true, payload = buildUpPayload, start = start, limit = limit }); }
private Point FindPointOnRound(Bitmap image, Point center) { var y = center.Y; var blackPixelSectionsDictionary = new Dictionary <int, int>(); var index = 0; for (int i = 0; i < center.X; i++) { var pixel = image.GetPixel(i, y); if (pixel.ToArgb() == Color.Black.ToArgb()) { if (blackPixelSectionsDictionary.ContainsKey(index)) { blackPixelSectionsDictionary[index]++; } else { blackPixelSectionsDictionary.Add(index, 1); } } else { index = i + 1; } } var indexOfMaxValue = blackPixelSectionsDictionary .AsQueryable() .FirstOrDefault(x => x.Value == blackPixelSectionsDictionary.Values.Max()).Key; return(new Point(indexOfMaxValue, y)); }
/// <summary> /// Returns all members which comply with the specified condition. /// </summary> /// <param name="membershipCondition">Expression to evaluate the membership. To return members all members where membership is more than a half, use "t=>t.Value > 0.5"</param> /// <returns>Members of this set that comply to the membership condition</returns> public ReadOnlyCollection <IMember> GetMembers(Expression <Func <KeyValuePair <IMember, double>, bool> > membershipCondition) { IQueryable <KeyValuePair <IMember, double> > filteredMembers = _members.AsQueryable <KeyValuePair <IMember, double> >().Where(membershipCondition); IQueryable <IMember> filteredMembersWithoutMembership = filteredMembers.Select <KeyValuePair <IMember, double>, IMember>(t => t.Key); IMember[] arrMembers = filteredMembersWithoutMembership.ToArray <IMember>(); return(new ReadOnlyCollection <IMember>(arrMembers)); }
public async Task <ApplicationUser> FindAsync(UserLoginInfo login) { var keyValuePair = _userLoginInfos.AsQueryable() .FirstOrDefault(k => k.Value.Any(v => v.LoginProvider == login.LoginProvider && v.ProviderKey == login.ProviderKey)); if (keyValuePair.Key == null) { return(null); } return(await FindByNameAsync(keyValuePair.Key)); }
public static string Get(string url, Dictionary <string, string> postData = null, string referer = "", Action <string> action = null, Action <Dictionary <string, string> > fun = null) { var result = ""; StringBuilder strPostData = new StringBuilder("?"); if (postData != null) { postData.AsQueryable().ToList().ForEach(a => { strPostData.AppendFormat("{0}={1}&", a.Key, a.Value); }); } if (strPostData.Length == 1) { strPostData = strPostData.Clear(); } HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url + strPostData.ToString().TrimEnd('&')); webRequest.CookieContainer = cookie2; webRequest.Method = "GET"; webRequest.Accept = "text/javascript, text/html, application/xml, text/xml, */*;"; if (!string.IsNullOrEmpty(referer)) { webRequest.Referer = referer; } //请求 HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); var responSteam = response.GetResponseStream(); StreamReader strRespon = new StreamReader(responSteam, Encoding.Default); result = strRespon.ReadToEnd(); if (action != null) { action.Invoke(result); } if (fun != null) { Dictionary <string, string> dic = new Dictionary <string, string>(); foreach (var item in cookie2.GetCookies(webRequest.RequestUri)) { var c = item as Cookie; dic.Add(c.Name, c.Value); } fun.Invoke(dic); } return(result); }
public static IQueryable <ISymbol> FindRelatedTypes(this SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) { var result = new Dictionary <ISymbol, int>(); var activeSyntaxTree = semanticModel.SyntaxTree; foreach (var item in node.DescendantNodes()) { if (item.IsKind(SyntaxKind.IdentifierName) == false) { continue; } if (cancellationToken.IsCancellationRequested) { break; } var s = semanticModel.GetSymbol(item, cancellationToken); if (s != null) { if (s.Kind == SymbolKind.NamedType && item.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) || s.Kind == SymbolKind.Method && ((IMethodSymbol)s).IsExtensionMethod) { continue; } var t = s.ContainingType ?? (s.Kind == SymbolKind.NamedType ? s : null); if (t != null) { AddResult(result, activeSyntaxTree, t); } s = s.GetReturnType(); if (s != null) { AddResult(result, activeSyntaxTree, s); } } } return(result.AsQueryable().OrderByDescending(i => i.Value).Select(i => i.Key)); void AddResult(Dictionary <ISymbol, int> d, SyntaxTree tree, ISymbol s) { foreach (var r in s.DeclaringSyntaxReferences) { var st = r.SyntaxTree; if (st != tree) { d[s] = d.TryGetValue(s, out int i) ? ++i : 1; } } } }
public IQueryable<KeyValuePair<string, int>> GetRankingList() { using (var db = new IdentityDbContext()) { var sortedUser = AchievementDb.GetAllUser().OrderByDescending(x => x.RankingPoints); var returnList = new Dictionary<string, int>(); foreach (var user in sortedUser) { var userName = db.Users.First(u => u.Id.Equals(user.ReleatedApplicationUserId)).UserName; returnList.Add(userName, user.RankingPoints); } return returnList.AsQueryable(); } }
public string TestDeserialize2Dic() { //string json = @"{""key1"":""zhangsan"",""key2"":""lisi""}"; //string json = "{\"key1\":\"zhangsan\",\"key2\":\"lisi\"}"; string json = "{key1:\"zhangsan\",key2:\"lisi\"}"; Dictionary <string, string> dic = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(json); string template = @"<li>key:{0},value:{1}</li>"; System.Text.StringBuilder strb = new System.Text.StringBuilder(); strb.Append("Dictionary<string, string>长度" + dic.Count.ToString() + "<ul>"); dic.AsQueryable().ToList().ForEach(x => { strb.AppendLine(string.Format(template, x.Key, x.Value)); }); strb.Append("</ul>"); return(strb.ToString()); }
public IEnumerable <Tuple <EventType, EventHandlerType> > GetConsumersEvents(string queueName = null, string eventName = null) { var queues = _consumer.AsQueryable(); if (!string.IsNullOrEmpty(queueName)) { queues = queues.Where(q => q.Key == queueName); } var handlers = queues.SelectMany(q => q.Value.SelectMany(e => e.Value.Select(eh => Tuple.Create(e.Key, eh)))); //.GroupBy(a => a.Item2) //.Select(b => Tuple.Create(b.First().Item1, b.Key)); if (!string.IsNullOrEmpty(eventName)) { handlers = handlers.Where(a => a.Item1.Name == eventName); } return(handlers.AsEnumerable()); }
/// <summary> /// 删除一列数据 /// </summary> public bool DelIndex(string csvname) { try { var query = from d in ParentWindow.m_DataBase[csvname].AsQueryable() where d.Key == CurrentIndex select d.Value; var indexdata = query.FirstOrDefault(); if (indexdata != null) { var indexquery = from d in m_DataIndex.AsQueryable() where d.Value == CurrentIndex select d.Key; var indexname = indexquery.FirstOrDefault(); if (indexname != null) { m_DataIndex.Remove(indexname); ParentWindow.m_DataBase[csvname].Remove(CurrentIndex); DataListBox.Items.Refresh(); DataListBox.SelectedIndex = 0; if (m_DataIndex.Count > 0) { BaseSetAllData(m_DataIndex[DataListBox.SelectedValue.ToString()]); } ParentWindow.SetDataChange(csvname); return(true); } } return(false); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(false); } }
/// <summary> /// 加载CSV /// </summary> private void LoadCsv(string name) { try { string databasename; var query = from d in m_DataBase.AsQueryable() where d.Key == name select d.Key; databasename = query.FirstOrDefault(); if (databasename == null) { StreamReader sr = new StreamReader(m_FilePath + "\\" + name + ".csv", Encoding.UTF8); try { var parser = new CsvParser(sr); Dictionary <int, Dictionary <string, string> > m_Data = new Dictionary <int, Dictionary <string, string> >(); int nIndex = 1; List <string> header = new List <string>(); var headerrow = parser.Read(); if (headerrow != null) { foreach (string element in headerrow) { header.Add(element); } } m_DataHeader.Add(name, header); while (true) { var row = parser.Read(); if (row != null) { Dictionary <string, string> list = new Dictionary <string, string>(); int i = 0; foreach (string element in row) { list.Add(header[i], element); ++i; } m_Data.Add(nIndex, list); ++nIndex; } else { break; } } m_DataBase.Add(name, m_Data); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return; } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); SelectPath(true); LoadCsv(name); } }
/// <summary> /// Writes trace information, a formatted array of objects and event /// information to the listener specific output. /// </summary> /// <param name="eventCache"> /// A <see cref="System.Diagnostics.TraceEventCache" /> /// object that contains the current process ID, thread ID, and stack trace /// information. /// </param> /// <param name="source"> /// A name used to identify the output, typically the name of /// the application that generated the trace event. /// </param> /// <param name="eventType"> /// One of the /// <see cref="System.Diagnostics.TraceEventType" /> values specifying the /// type of event that has caused the trace. /// </param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="format"> /// A format string that contains zero or more format items, /// which correspond to objects in the <paramref name="args" /> array. /// </param> /// <param name="args"> /// An <see langword="object" /> array containing zero or more /// objects to format. /// </param> public override void TraceEvent( TraceEventCache eventCache , string source , TraceEventType eventType , int id , string format , params object[] args ) { var xmlDict = new Dictionary <string, string> ( ); var doOutput = true; for (var i = 0; i < args.Length - 1; i += 2) { var key = args[i] as string; var o = args[i + 1]; string desc = null; switch (o) { case RoutedEvent re: { if (!RoutedEvents.TryGetValue(re.Name, out var info)) { RoutedEvents[re.Name] = info = new Info(0); } info.Count += 1; if (re.Name == "ScrollChanged") { doOutput = false; } desc = re.Name; break; } case FrameworkElement fe: desc = $"{o.GetType ( ).Name}[{fe.Name}]"; break; case bool _: desc = o.GetType( ) + "[" + o + "]"; break; case RoutedEventArgs _: desc = o.GetType( ).ToString( ); break; } //d[ args[ i ].ToString ( ) ] = args[ i + 1 ] ; if (desc != null) { xmlDict[key] = desc; continue; } try { var b = new StringBuilder( ); XamlWriter.Save(args[i + 1], new StringWriter(b)); xmlDict[args[i].ToString( )] = b.ToString( ); } catch (Exception) { if (desc == null) { throw; } xmlDict[key] = desc; try { var serializer = new XmlSerializer(args[i + 1].GetType( )); var b = new StringBuilder( ); serializer.Serialize(new StringWriter(b), args[i + 1]); xmlDict[args[i].ToString( )] = b.ToString( ); } catch (Exception) { // ignored } } } if (!doOutput) { return; } Logger.Trace( string.Join( "; " , xmlDict.AsQueryable( ) .Select( (pair, i) => $"{pair.Key} = {pair.Value}" ) ) ); }
public IQueryable <KeyValuePair <string, IMessage> > Queryable() { return(_dataBase.AsQueryable()); }
/// <summary> /// Binds the attendees grid. /// </summary> private void BindAttendeesGrid( bool isExporting = false ) { // Get Group Type filter var groupTypes = this.GetSelectedGroupTypes(); if ( groupTypes == null || !groupTypes.Any() ) { return; } var groupTypeIdList = groupTypes.Select( t => t.Id ).ToList(); // Get the daterange filter var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( drpSlidingDateRange.DelimitedValues ); if ( dateRange.End == null ) { dateRange.End = RockDateTime.Now; } var start = dateRange.Start; var end = dateRange.End; // Get the group filter var groupIdList = new List<int>(); string groupIds = GetSelectedGroupIds().AsDelimited( "," ); if ( !string.IsNullOrWhiteSpace( groupIds ) ) { groupIdList = groupIds.Split( ',' ).AsIntegerList(); } // If campuses were included, filter attendances by those that have selected campuses // if 'null' is one of the campuses, treat that as a 'CampusId is Null' var includeNullCampus = clbCampuses.SelectedValues.Any( a => a.Equals( "null", StringComparison.OrdinalIgnoreCase ) ); var campusIdList = clbCampuses.SelectedValues.AsIntegerList(); campusIdList.Remove( 0 ); // remove 0 from the list, just in case it is there if ( !includeNullCampus && !campusIdList.Any() ) { campusIdList = null; } // If schedules were included, filter attendance by those that have the selected schedules var scheduleIdList = spSchedules.SelectedValues.AsIntegerList(); scheduleIdList.Remove( 0 ); if ( !scheduleIdList.Any() ) { scheduleIdList = null; } // we want to get the first 2 visits at a minimum so we can show the dates in the grid int nthVisitsTake = 2; int? byNthVisit = null; if ( radByVisit.Checked ) { // If we are filtering by nth visit, we might want to get up to first 5 byNthVisit = ddlNthVisit.SelectedValue.AsIntegerOrNull(); if ( byNthVisit.HasValue && byNthVisit > 2 ) { nthVisitsTake = byNthVisit.Value; } } bool showNonAttenders = byNthVisit.HasValue && byNthVisit.Value == 0; // Get any attendance pattern filters int? attendedMinCount = null; int? attendedMissedCount = null; DateRange attendedMissedDateRange = new DateRange(); if ( radByPattern.Checked ) { attendedMinCount = tbPatternXTimes.Text.AsIntegerOrNull(); if ( cbPatternAndMissed.Checked ) { attendedMissedCount = tbPatternMissedXTimes.Text.AsIntegerOrNull(); attendedMissedDateRange = new DateRange( drpPatternDateRange.LowerValue, drpPatternDateRange.UpperValue ); if ( !attendedMissedDateRange.Start.HasValue || !attendedMissedDateRange.End.HasValue ) { nbMissedDateRangeRequired.Visible = true; return; } } } nbMissedDateRangeRequired.Visible = false; // Determine how dates shold be grouped ChartGroupBy groupBy = hfGroupBy.Value.ConvertToEnumOrNull<ChartGroupBy>() ?? ChartGroupBy.Week; // Determine if parents or children are being included with results var includeParents = hfViewBy.Value.ConvertToEnumOrNull<ViewBy>().GetValueOrDefault( ViewBy.Attendees ) == ViewBy.ParentsOfAttendees; var includeChildren = hfViewBy.Value.ConvertToEnumOrNull<ViewBy>().GetValueOrDefault( ViewBy.Attendees ) == ViewBy.ChildrenOfAttendees; // Atttendance results var allAttendeeVisits = new Dictionary<int, AttendeeVisits>(); var allResults = new List<AttendeeResult>(); // Collection of async queries to run before assembling data var qryTasks = new List<Task>(); DataTable dtAttendeeLastAttendance = null; DataTable dtAttendees = null; DataTable dtAttendeeFirstDates = null; List<int> personIdsWhoDidNotMiss = null; if ( !showNonAttenders ) { // Call the stored procedure to get all the person ids and their attendance dates for anyone // whith attendance that matches the selected criteria. qryTasks.Add( Task.Run( () => { DataTable dtAttendeeDates = AttendanceService.GetAttendanceAnalyticsAttendeeDates( groupIdList, start, end, campusIdList, includeNullCampus, scheduleIdList ).Tables[0]; foreach ( DataRow row in dtAttendeeDates.Rows ) { int personId = (int)row["PersonId"]; allAttendeeVisits.AddOrIgnore( personId, new AttendeeVisits() ); var result = allAttendeeVisits[personId]; result.PersonId = personId; DateTime summaryDate = DateTime.MinValue; switch ( groupBy ) { case ChartGroupBy.Week: summaryDate = (DateTime)row["SundayDate"]; break; case ChartGroupBy.Month: summaryDate = (DateTime)row["MonthDate"]; break; case ChartGroupBy.Year: summaryDate = (DateTime)row["YearDate"]; break; } if ( !result.AttendanceSummary.Contains( summaryDate ) ) { result.AttendanceSummary.Add( summaryDate ); } } } ) ); // Call the stored procedure to get the last attendance qryTasks.Add( Task.Run( () => { dtAttendeeLastAttendance = AttendanceService.GetAttendanceAnalyticsAttendeeLastAttendance( groupIdList, start, end, campusIdList, includeNullCampus, scheduleIdList ).Tables[0]; } ) ); // Call the stored procedure to get the names/demographic info for attendess qryTasks.Add( Task.Run( () => { dtAttendees = AttendanceService.GetAttendanceAnalyticsAttendees( groupIdList, start, end, campusIdList, includeNullCampus, scheduleIdList, includeParents, includeChildren ).Tables[0]; } ) ); // If checking for missed attendance, get the people who missed that number of dates during the missed date range if ( attendedMissedCount.HasValue && attendedMissedDateRange.Start.HasValue && attendedMissedDateRange.End.HasValue ) { qryTasks.Add( Task.Run( () => { personIdsWhoDidNotMiss = new List<int>(); DataTable dtAttendeeDatesMissed = AttendanceService.GetAttendanceAnalyticsAttendeeDates( groupIdList, attendedMissedDateRange.Start.Value, attendedMissedDateRange.End.Value, campusIdList, includeNullCampus, scheduleIdList ).Tables[0]; var missedResults = new Dictionary<int, AttendeeResult>(); foreach ( DataRow row in dtAttendeeDatesMissed.Rows ) { int personId = (int)row["PersonId"]; missedResults.AddOrIgnore( personId, new AttendeeResult() ); var missedResult = missedResults[personId]; missedResult.PersonId = personId; DateTime summaryDate = DateTime.MinValue; switch ( groupBy ) { case ChartGroupBy.Week: summaryDate = (DateTime)row["SundayDate"]; break; case ChartGroupBy.Month: summaryDate = (DateTime)row["MonthDate"]; break; case ChartGroupBy.Year: summaryDate = (DateTime)row["YearDate"]; break; } if ( !missedResult.AttendanceSummary.Contains( summaryDate ) ) { missedResult.AttendanceSummary.Add( summaryDate ); } } var missedPossibleDates = GetPossibleAttendancesForDateRange( attendedMissedDateRange, groupBy ); int missedPossibleCount = missedPossibleDates.Count(); personIdsWhoDidNotMiss = missedResults .Where( m => missedPossibleCount - m.Value.AttendanceSummary.Count < attendedMissedCount.Value ) .Select( m => m.Key ) .ToList(); } ) ); } // Call the stored procedure to get the first five dates that any person attended this group type qryTasks.Add( Task.Run( () => { dtAttendeeFirstDates = AttendanceService.GetAttendanceAnalyticsAttendeeFirstDates( groupTypeIdList, groupIdList, start, end, campusIdList, includeNullCampus, scheduleIdList ).Tables[0]; } ) ); } else { qryTasks.Add( Task.Run( () => { DataSet ds = AttendanceService.GetAttendanceAnalyticsNonAttendees( groupTypeIdList, groupIdList, start, end, campusIdList, includeNullCampus, scheduleIdList, includeParents, includeChildren ); DataTable dtNonAttenders = ds.Tables[0]; dtAttendeeFirstDates = ds.Tables[1]; dtAttendeeLastAttendance = ds.Tables[2]; foreach ( DataRow row in dtNonAttenders.Rows ) { int personId = (int)row["Id"]; var result = new AttendeeResult(); result.PersonId = personId; var person = new PersonInfo(); person.NickName = row["NickName"].ToString(); person.LastName = row["LastName"].ToString(); person.Email = row["Email"].ToString(); person.Birthdate = row["BirthDate"] as DateTime?; person.Age = Person.GetAge( person.Birthdate ); person.ConnectionStatusValueId = row["ConnectionStatusValueId"] as int?; result.Person = person; if ( includeParents ) { result.ParentId = (int)row["ParentId"]; var parent = new PersonInfo(); parent.NickName = row["ParentNickName"].ToString(); parent.LastName = row["ParentLastName"].ToString(); parent.Email = row["ParentEmail"].ToString(); parent.Birthdate = row["ParentBirthDate"] as DateTime?; parent.Age = Person.GetAge( parent.Birthdate ); result.Parent = parent; } if ( includeChildren ) { var child = new PersonInfo(); result.ChildId = (int)row["ChildId"]; child.NickName = row["ChildNickName"].ToString(); child.LastName = row["ChildLastName"].ToString(); child.Email = row["ChildEmail"].ToString(); child.Birthdate = row["ChildBirthDate"] as DateTime?; child.Age = Person.GetAge( child.Birthdate ); result.Child = child; } allResults.Add( result ); } } ) ); } // If a dataview filter was included, find the people who match that criteria List<int> dataViewPersonIds = null; qryTasks.Add( Task.Run( () => { var dataViewId = dvpDataView.SelectedValueAsInt(); if ( dataViewId.HasValue ) { dataViewPersonIds = new List<int>(); var dataView = new DataViewService( _rockContext ).Get( dataViewId.Value ); if ( dataView != null ) { var errorMessages = new List<string>(); var dvPersonService = new PersonService( _rockContext ); ParameterExpression paramExpression = dvPersonService.ParameterExpression; Expression whereExpression = dataView.GetExpression( dvPersonService, paramExpression, out errorMessages ); SortProperty sort = null; var dataViewPersonIdQry = dvPersonService .Queryable().AsNoTracking() .Where( paramExpression, whereExpression, sort ) .Select( p => p.Id ); dataViewPersonIds = dataViewPersonIdQry.ToList(); } } } ) ); // Wait for all the queries to finish Task.WaitAll( qryTasks.ToArray() ); if ( !showNonAttenders ) { var attendees = allAttendeeVisits.AsQueryable(); // If dataview filter was included remove anyone not in that dataview if ( dataViewPersonIds != null ) { attendees = attendees.Where( p => dataViewPersonIds.Contains( p.Key ) ); } // If filter for number missed was included, remove anyone who did not match that filter if ( personIdsWhoDidNotMiss != null ) { attendees = attendees.Where( p => !personIdsWhoDidNotMiss.Contains( p.Key ) ); } // If filtering by minimum times attended if ( attendedMinCount.HasValue ) { attendees = attendees.Where( p => p.Value.AttendanceSummary.Count() >= attendedMinCount ); } // Force filter application allAttendeeVisits = attendees.ToDictionary( k => k.Key, v => v.Value ); // Add the First Visit information foreach ( DataRow row in dtAttendeeFirstDates.Rows ) { int personId = (int)row["PersonId"]; if ( allAttendeeVisits.ContainsKey( personId ) ) { allAttendeeVisits[personId].FirstVisits.Add( (DateTime)row["StartDate"] ); } } // If filtering based on visit time, only include those who visited the selected time during the date range if ( byNthVisit.HasValue ) { int skipCount = byNthVisit.Value - 1; allAttendeeVisits = allAttendeeVisits .Where( p => p.Value.FirstVisits.Skip( skipCount ).Take( 1 ).Any( d => d >= start && d < end ) ) .ToDictionary( k => k.Key, v => v.Value ); } // Add the Last Attended information if ( dtAttendeeLastAttendance != null ) { foreach ( DataRow row in dtAttendeeLastAttendance.Rows ) { int personId = (int)row["PersonId"]; if ( allAttendeeVisits.ContainsKey( personId ) ) { var result = allAttendeeVisits[personId]; if ( result.LastVisit == null ) { var lastAttendance = new PersonLastAttendance(); lastAttendance.CampusId = row["CampusId"] as int?; lastAttendance.GroupId = row["GroupId"] as int?; lastAttendance.GroupName = row["GroupName"].ToString(); lastAttendance.RoleName = row["RoleName"].ToString(); lastAttendance.InGroup = !string.IsNullOrWhiteSpace( lastAttendance.RoleName ); lastAttendance.ScheduleId = row["ScheduleId"] as int?; lastAttendance.StartDateTime = (DateTime)row["StartDateTime"]; lastAttendance.LocationId = row["LocationId"] as int?; lastAttendance.LocationName = row["LocationName"].ToString(); result.LastVisit = lastAttendance; } } } } // Add the Demographic information if ( dtAttendees != null ) { var newResults = new Dictionary<int, AttendeeResult>(); foreach ( DataRow row in dtAttendees.Rows ) { int personId = (int)row["Id"]; if ( allAttendeeVisits.ContainsKey( personId ) ) { var result = new AttendeeResult( allAttendeeVisits[personId] ); var person = new PersonInfo(); person.NickName = row["NickName"].ToString(); person.LastName = row["LastName"].ToString(); person.Email = row["Email"].ToString(); person.Birthdate = row["BirthDate"] as DateTime?; person.Age = Person.GetAge( person.Birthdate ); person.ConnectionStatusValueId = row["ConnectionStatusValueId"] as int?; result.Person = person; if ( includeParents ) { result.ParentId = (int)row["ParentId"]; var parent = new PersonInfo(); parent.NickName = row["ParentNickName"].ToString(); parent.LastName = row["ParentLastName"].ToString(); parent.Email = row["ParentEmail"].ToString(); parent.Birthdate = row["ParentBirthDate"] as DateTime?; parent.Age = Person.GetAge( parent.Birthdate ); result.Parent = parent; } if ( includeChildren ) { var child = new PersonInfo(); result.ChildId = (int)row["ChildId"]; child.NickName = row["ChildNickName"].ToString(); child.LastName = row["ChildLastName"].ToString(); child.Email = row["ChildEmail"].ToString(); child.Birthdate = row["ChildBirthDate"] as DateTime?; child.Age = Person.GetAge( child.Birthdate ); result.Child = child; } allResults.Add( result ); } } } } else { // If dataview filter was included remove anyone not in that dataview if ( dataViewPersonIds != null ) { allResults = allResults .Where( p => dataViewPersonIds.Contains( p.PersonId ) ) .ToList(); } // Add the first visit dates for people foreach ( DataRow row in dtAttendeeFirstDates.Rows ) { int personId = (int)row["PersonId"]; foreach ( var result in allResults.Where( r => r.PersonId == personId ) ) { result.FirstVisits.Add( (DateTime)row["StartDate"] ); } } // Add the Last Attended information if ( dtAttendeeLastAttendance != null ) { foreach ( DataRow row in dtAttendeeLastAttendance.Rows ) { int personId = (int)row["PersonId"]; foreach ( var result in allResults.Where( r => r.PersonId == personId ) ) { if ( result.LastVisit == null ) { var lastAttendance = new PersonLastAttendance(); lastAttendance.CampusId = row["CampusId"] as int?; lastAttendance.GroupId = row["GroupId"] as int?; lastAttendance.GroupName = row["GroupName"].ToString(); lastAttendance.RoleName = row["RoleName"].ToString(); lastAttendance.InGroup = !string.IsNullOrWhiteSpace( lastAttendance.RoleName ); lastAttendance.ScheduleId = row["ScheduleId"] as int?; lastAttendance.StartDateTime = (DateTime)row["StartDateTime"]; lastAttendance.LocationId = row["LocationId"] as int?; lastAttendance.LocationName = row["LocationName"].ToString(); result.LastVisit = lastAttendance; } } } } } // Begin formatting the columns var qryResult = allResults.AsQueryable(); var personUrlFormatString = ( (RockPage)this.Page ).ResolveRockUrl( "~/Person/{0}" ); var personHyperLinkField = gAttendeesAttendance.Columns.OfType<HyperLinkField>().FirstOrDefault( a => a.HeaderText == "Name" ); if ( personHyperLinkField != null ) { personHyperLinkField.DataNavigateUrlFormatString = personUrlFormatString; } var parentHyperLinkField = gAttendeesAttendance.Columns.OfType<HyperLinkField>().FirstOrDefault( a => a.HeaderText == "Parent" ); if ( parentHyperLinkField != null ) { parentHyperLinkField.Visible = includeParents; parentHyperLinkField.DataNavigateUrlFormatString = personUrlFormatString; } var parentField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Parent" ); if ( parentField != null ) { parentField.ExcelExportBehavior = includeParents ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude; } var parentEmailField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Parent Email" ); if ( parentEmailField != null ) { parentEmailField.ExcelExportBehavior = includeParents ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude; } var childHyperLinkField = gAttendeesAttendance.Columns.OfType<HyperLinkField>().FirstOrDefault( a => a.HeaderText == "Child" ); if ( childHyperLinkField != null ) { childHyperLinkField.Visible = includeChildren; childHyperLinkField.DataNavigateUrlFormatString = personUrlFormatString; } var childfield = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Child" ); if ( childfield != null ) { childfield.ExcelExportBehavior = includeChildren ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude; } var childEmailField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Child Email" ); if ( childEmailField != null ) { childEmailField.ExcelExportBehavior = includeChildren ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude; } var childAgeField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Child Age" ); if ( childAgeField != null ) { childAgeField.ExcelExportBehavior = includeChildren ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude; } SortProperty sortProperty = gAttendeesAttendance.SortProperty; if ( sortProperty != null ) { if ( sortProperty.Property == "AttendanceSummary.Count" ) { if ( sortProperty.Direction == SortDirection.Descending ) { qryResult = qryResult.OrderByDescending( a => a.AttendanceSummary.Count() ); } else { qryResult = qryResult.OrderBy( a => a.AttendanceSummary.Count() ); } } else if ( sortProperty.Property == "FirstVisit.StartDateTime" ) { if ( sortProperty.Direction == SortDirection.Descending ) { qryResult = qryResult.OrderByDescending( a => a.FirstVisits.Min() ); } else { qryResult = qryResult.OrderBy( a => a.FirstVisits.Min() ); } } else { qryResult = qryResult.Sort( sortProperty ); } } else { qryResult = qryResult.OrderBy( a => a.Person.LastName ).ThenBy( a => a.Person.NickName ); } var attendancePercentField = gAttendeesAttendance.Columns.OfType<RockTemplateField>().First( a => a.HeaderText.EndsWith( "Attendance %" ) ); attendancePercentField.HeaderText = string.Format( "{0}ly Attendance %", groupBy.ConvertToString() ); // Calculate all the possible attendance summary dates UpdatePossibleAttendances( dateRange, groupBy ); // pre-load the schedule names since FriendlyScheduleText requires building the ICal object, etc _scheduleNameLookup = new ScheduleService( _rockContext ).Queryable() .ToList() .ToDictionary( k => k.Id, v => v.FriendlyScheduleText ); if ( includeParents ) { gAttendeesAttendance.PersonIdField = "ParentId"; gAttendeesAttendance.DataKeyNames = new string[] { "ParentId", "PersonId" }; } else if ( includeChildren ) { gAttendeesAttendance.PersonIdField = "ChildId"; gAttendeesAttendance.DataKeyNames = new string[] { "ChildId", "PersonId" }; } else { gAttendeesAttendance.PersonIdField = "PersonId"; gAttendeesAttendance.DataKeyNames = new string[] { "PersonId" }; } // Create the dynamic attendance grid columns as needed CreateDynamicAttendanceGridColumns(); try { nbAttendeesError.Visible = false; gAttendeesAttendance.SetLinqDataSource( qryResult ); var currentPageItems = gAttendeesAttendance.DataSource as List<AttendeeResult>; if ( currentPageItems != null ) { var currentPagePersonIds = new List<int>(); if ( includeParents ) { currentPagePersonIds = currentPageItems.Select( i => i.ParentId ).ToList(); gAttendeesAttendance.PersonIdField = "ParentId"; gAttendeesAttendance.DataKeyNames = new string[] { "ParentId", "PersonId" }; } else if ( includeChildren ) { currentPagePersonIds = currentPageItems.Select( i => i.ChildId ).ToList(); gAttendeesAttendance.PersonIdField = "ChildId"; gAttendeesAttendance.DataKeyNames = new string[] { "ChildId", "PersonId" }; } else { currentPagePersonIds = currentPageItems.Select( i => i.PersonId ).ToList(); gAttendeesAttendance.PersonIdField = "PersonId"; gAttendeesAttendance.DataKeyNames = new string[] { "PersonId" }; } LoadCurrentPageObjects( currentPagePersonIds ); } _currentlyExporting = isExporting; gAttendeesAttendance.DataBind(); _currentlyExporting = false; } catch ( Exception exception ) { LogAndShowException( exception ); } }
public static List <Pokemon> GetPokemonByIncompleteName(Dictionary <char, int> dict, int length) { var context = new AppDbContext(); var pokes = context.Pokemon.AsEnumerable().Where(p => p.Name.Length == length).ToList().Where(p => dict.AsQueryable().ToArray().All(d => char.ToLower(p.Name[d.Value]) == char.ToLower(d.Key)) == true).ToList(); return(pokes); }
public static string Post(string url, Dictionary <string, string> postData, string referer = "", string accept = "", string contentType = "", ResponeType type = ResponeType.String, string fileSavePath = "", Action <string> action = null, Func <Dictionary <string, string> > fun = null) { var result = ""; //var cookie = new CookieContainer(); StringBuilder strPostData = new StringBuilder(); if (postData != null) { postData.AsQueryable().ToList().ForEach(a => { strPostData.AppendFormat("{0}={1}&", a.Key, a.Value); }); } byte[] byteArray = Encoding.UTF8.GetBytes(strPostData.ToString().TrimEnd('&')); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.CookieContainer = cookie2; webRequest.Method = "POST"; if (string.IsNullOrEmpty(accept)) { webRequest.Accept = "application/json, text/javascript, */*;"; } else { webRequest.Accept = accept; } if (!string.IsNullOrEmpty(referer)) { webRequest.Referer = referer; } if (string.IsNullOrEmpty(contentType)) { webRequest.ContentType = "application/x-www-form-urlencoded"; } else { webRequest.ContentType = contentType; } if (strPostData.Length > 0) { webRequest.ContentLength = byteArray.Length; } //请求 Stream newStream = webRequest.GetRequestStream(); newStream.Write(byteArray, 0, byteArray.Length); newStream.Close(); HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); var responSteam = response.GetResponseStream(); if (type == ResponeType.String) { StreamReader strRespon = new StreamReader(responSteam, Encoding.UTF8); result = strRespon.ReadToEnd(); } else { BinaryReader br = new BinaryReader(responSteam); byte[] byteArr = br.ReadBytes(200000); FileStream fs = new FileStream(fileSavePath, FileMode.OpenOrCreate); fs.Write(byteArr, 0, byteArr.Length); fs.Dispose(); fs.Close(); result = "OK"; } if (action != null) { action.Invoke(result); } if (fun != null) { Dictionary <string, string> dic = new Dictionary <string, string>(); foreach (var item in cookie2.GetCookies(webRequest.RequestUri)) { var c = item as Cookie; dic.Add(c.Name, c.Value); } fun = () => { return(dic); }; } return(result); }