/// <summary> /// Example call - https://www.googleapis.com/books/v1/volumes?q=dragon /// </summary> /// <param name="searchTerm"></param> /// <param name="page"></param> /// <returns></returns> public PagedResults<Models.Book> Search(string searchTerm, int page = 1) { string url = "https://www.googleapis.com/books/v1"; var client = new RestClient(url); var request = new RestRequest("volumes", Method.GET); request.AddParameter("q", searchTerm); request.AddParameter("maxResults", pageSize); request.AddParameter("startIndex", (page - 1) * pageSize); request.AddParameter("orderBy", "relevance"); request.AddHeader("Content-Type", "application/json"); var response = client.Execute<Google.Messages.BookList>(request); var books = AutoMapper.Mapper.Map<List<Models.Book>>(response.Data.Items); var returnValue = new PagedResults<Models.Book> { Results = books ?? new List<Models.Book>(), TotalItems = response.Data.TotalItems > maxTotal ? maxTotal : response.Data.TotalItems, PageSize = pageSize, SearchTerm = searchTerm, CurrentPage = page }; return returnValue; }
/// <summary> /// Gets the paged results by applying the requested paging parameters. You must have applied your sort before calling this method. /// </summary> /// <param name="pagingOptions"></param> /// <param name="queryable"></param> public static PagedResults <T2> GetPagedResults <T, T2>(PagingOptions pagingOptions, IQueryable <T> queryable) { var results = new PagedResults <T2> { PagingOptions = pagingOptions }; int totalCount = queryable.Count(); results.Count = totalCount; results.PageCount = (totalCount / pagingOptions.PageSize) + ((totalCount % pagingOptions.PageSize == 0) ? 0 : 1); var items = queryable.Skip(pagingOptions.RecordsToSkip()).Take(pagingOptions.PageSize).ToList(); results.Items = Mapper.Map <List <T2> >(items); return(results); }
public async Task <PagedResults> GetFileInformationsAsync(int pageSize = 100, string searchPattern = null, CancellationToken cancellationToken = default) { this.Initialize(); var folder = this.share.GetRootDirectoryReference(); if (pageSize <= 0) { return(PagedResults.EmptyResults); } var result = new PagedResults(() => this.GetFiles(folder, searchPattern, 1, pageSize, cancellationToken)); await result.NextPageAsync().AnyContext(); return(result); }
// public string OrgUrl { get { return _apiUrl; } } //public User GetOktaUserById(string oktaId) //{ // User oktaUser = null; // try // { // oktaUser = _usersClient.Get(oktaId); // } // catch (Exception ex) // { // _logger.Error(string.Format("Error searching for Okta user in Okta. Okta Id: {0}.", oktaId), ex); // } // return oktaUser; //} //public CustomUser GetCustomUser(string oktaId) //{ // User oktaUser = null; // CustomUser customUser = null; // try // { // oktaUser = _usersClient.Get(oktaId); // customUser = new CustomUser(oktaUser); // customUser.extProfile = new CustomUserProfile(); // List<string> customAttributes = oktaUser.Profile.GetUnmappedPropertyNames(); // foreach (var item in customAttributes) // { // PropertyInfo tempProp = customUser.extProfile.GetType().GetProperty(item); // if (tempProp != null) // { // object myValue = oktaUser.Profile.GetProperty(item); // if (tempProp.CanWrite) // { // tempProp.SetValue(customUser.extProfile, myValue, null); // } // } // else // { // _logger.Debug("unmapped okta attribute " + item + " is not defined as an extention"); // } // } // } // catch (Exception ex) // { // _logger.Error(string.Format("Error searching for Okta user in Okta. Okta Id: {0}.", oktaId), ex); // } // return customUser; //} public PagedResults <User> ListBasicUsers(Uri nextPage = null) { PagedResults <User> oktaUserList = null; try { oktaUserList = _usersClient.GetList(nextPage, pageSize: 200); } catch (Exception ex) { _logger.Error("Error searching for Okta user in Okta. "); } return(oktaUserList); }
public async Task <PagedResults <Author> > GetAllAuthors(int page, int pageSize, string orderBy, bool ascending) { PagedResults <Author> result = null; IQueryable <AuthorPostgreSql> authorsQueryResult = db.Authors.AsQueryable(); PagedResults <AuthorPostgreSql> authorPagedResult = await pagination.CreatePagedResultsAsync(authorsQueryResult, page, pageSize, orderBy, ascending); if (authorPagedResult != null) { PostgreSqlDataConvert.InitData(authorPagedResult); result = PostgreSqlDataConvert.GetFormatedPagedResults(); } return(result); }
/// <summary> /// main method for handling requests send to this handler /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { // get data string xml = new StreamReader(context.Request.InputStream).ReadToEnd(); XDocument doc = XDocument.Load(new StringReader(xml)); XNamespace xns = XNamespace.Get("http://schemas.xmlsoap.org/soap/envelope/"); AuthHeader header = GetSoapHeader(doc.Descendants(xns + "Header").First().FirstNode); PricingRequest body = GetSoapBody(doc.Descendants(xns + "Body").First().FirstNode); // process pricing ProductReturn returnedPrices = new ProductReturn(); IUserProfileLogic profileLogic = _scope.GetService(typeof(IUserProfileLogic)) as IUserProfileLogic; UserProfileReturn profileLogicReturn = profileLogic.GetUserProfile(header.UserName, false); if (profileLogicReturn.UserProfiles.Count > 0) { UserProfile profile = profileLogicReturn.UserProfiles[0]; PagedResults <Customer> customers = profileLogic.CustomerSearch(profile, body.customerNumber, new Core.Models.Paging.PagingModel(), string.Empty, CustomerSearchType.Customer); if (customers.TotalResults > 0) { returnedPrices.Products.AddRange(GetItemPricing(customers.Results[0].CustomerBranch, body.customerNumber, body.products, ConvertEffectiveDate(body.effDate))); } } // return results SoapEnvelope soap = new SoapEnvelope(); soap.Body.Response.Results = GetProductString(returnedPrices); XmlSerializer serializer = new XmlSerializer(soap.GetType()); XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); namespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema"); namespaces.Add("soap", "http://schemas.xmlsoap.org/soap/envelope/"); serializer.Serialize(context.Response.OutputStream, soap, namespaces); context.Response.ContentType = "text/xml"; }
public async Task GetAllEventsExcel_StateUnderTest_ExpectedBehavior() { // Arrange var unitUnderTest = this.CreateEventsController(); this.mockAuthorizationService.Setup( r => r.AuthorizeAsync(It.IsAny <ClaimsPrincipal>(), It.IsAny <string>(), It.IsAny <string>()) ).ReturnsAsync(AuthorizationResult.Success()); PagedResults <EventReport> sampleResult = new PagedResults <EventReport> { Items = Enumerable.Empty <EventReport>() }; this.mockEventBusiness.Setup(r => r.GetAllForExcelAsync( It.IsAny <PagingOptions>(), It.IsAny <SortOptions <Event, EventEntity> >(), It.IsAny <SearchOptions <Event, EventEntity> >(), It.IsAny <long>(), It.IsAny <CancellationToken>()) ).ReturnsAsync(sampleResult); bool report = false; PagingOptions pagingOptions = new PagingOptions() { Limit = 1, Offset = 1 }; SortOptions <Event, EventEntity> sortOptions = new SortOptions <Event, EventEntity>() { OrderBy = new string[] { "" } }; SearchOptions <Event, EventEntity> searchOptions = new SearchOptions <Event, EventEntity>() { Search = new string[] { "" } }; CancellationToken ct = new CancellationToken(); // Act var result = await unitUnderTest.GetAllEventsExcel( report, pagingOptions, sortOptions, searchOptions, ct); // Assert Assert.IsType <FileContentResult>(result); }
public async Task <ActionResult <PagedResults> > GetAllUsers([ModelBinder(BinderType = typeof(JsonQueryBinder), Name = "params")] CommonQueryParameters qp = null) { var queryParameters = qp ?? new CommonQueryParameters(); var userId = User.GetLoggedInUserId <string>(); var user = await _userBusinessInstance.GetAllUsers(); var r = _commonQueryService.Filter(user, queryParameters).AsPagedResults(queryParameters); if (user == null) { throw new AppException("No User found for: " + userId); } var result = new PagedResults(r.Data, r.Pagination.Total); return(Ok(result)); }
public async Task <PagedResults <ProductDto> > HandleAsync(BrowseProductsQuery query) { var pagedResult = await _productsRepository.BrowseAsync(query); var products = pagedResult.Items.Select(p => new ProductDto() { Id = p.Id, Name = p.Name, Description = p.Description, Vendor = p.Vendor, Price = p.Price, Quantity = p.Quantity }).ToList(); return(PagedResults <ProductDto> .From(pagedResult, products)); }
/// <summary> /// Turns a string containing a Role Name into a native Okta Group object /// </summary> /// <param name="groupName">The name of a "role" or group</param> /// <returns>Okta Group object</returns> public Group GetOktaGroupByRoleName(string groupName) { Group group = new Group(); PagedResults <Group> groups = okta.groups.GetList(); foreach (Group oktaGroup in groups.Results) { if (oktaGroup.Profile.Name == groupName) { group = oktaGroup; break; } var id = oktaGroup.Id; } return(group); }
public async Task <PagedResults <Opening> > GetOpeningsAsync(CancellationToken ct, PagingOptions pagingOptions) { var rooms = await _context.Rooms.ToArrayAsync(); var allOpenings = new List <Opening>(); foreach (var room in rooms) { // Generate a sequence of raw opening slots var allPossibleOpenings = _dateLogicService.GetAllSlots( DateTimeOffset.UtcNow, _dateLogicService.FurthestPossibleBooking(DateTimeOffset.UtcNow)) .ToArray(); var conflictedSlots = await GetConflictingSlots( room.Id, allPossibleOpenings.First().StartAt, allPossibleOpenings.Last().EndAt, ct); // Remove the slots that have conflicts and project var openings = allPossibleOpenings .Except(conflictedSlots, new BookingRangeComparer()) .Select(slot => new OpeningEntity { RoomId = room.Id, Rate = room.Rate, StartAt = slot.StartAt, EndAt = slot.EndAt }) .Select(model => Mapper.Map <Opening>(model)); allOpenings.AddRange(openings); } var pagedOpenings = allOpenings .Skip(pagingOptions.Offset.Value) .Take(pagingOptions.Limit.Value); var result = new PagedResults <Opening> { Items = pagedOpenings, TotalSize = allOpenings.Count }; return(result); }
public async Task <ActionResult <Collection <EventStatus> > > GetAllEventStatus( [FromQuery] PagingOptions pagingOptions, [FromQuery] SortOptions <Event, EventEntity> sortOptions, [FromQuery] SearchOptions <Event, EventEntity> searchOptions, CancellationToken ct) { pagingOptions.Offset = pagingOptions.Offset ?? _defaultPagingOptions.Offset; pagingOptions.Limit = pagingOptions.Limit ?? _defaultPagingOptions.Limit; var events = new PagedResults <EventStatus> { Items = Enumerable.Empty <EventStatus>() }; if (User.Identity.IsAuthenticated) { var canSeeAllEvents = await _authzService.AuthorizeAsync( User, "ViewAllEventsPolicy"); if (canSeeAllEvents.Succeeded) { events = await _report.GetAllAsync(pagingOptions, sortOptions, searchOptions, ct); } else { var userId = await _user.GetUserIdAsync(User); events = await _report.GetAllByPocAsync(pagingOptions, sortOptions, searchOptions, Convert.ToInt64(User.Identity.Name.Split('@')[0]), ct); } } var collection = PagedCollection <EventStatus> .Create <EventStatusResponse>( Link.ToCollection(nameof(GetAllEventStatus)), events.Items.ToArray(), events.TotalSize, pagingOptions); //TODO collection.EventsQuery = FormMetadata.FromResource <EventStatus>( Link.ToForm( nameof(GetAllEventStatus), null, Link.GetMethod, Form.QueryRelation)); return(collection); }
public async Task GetElectricityStandingChargesSucceedsAsync() { var from = DateTimeOffset.UtcNow.AddDays(-2); var to = DateTimeOffset.UtcNow.AddDays(-1); var productCode = "A123Z"; var tariffCode = "J0123456K"; var charges = new PagedResults <Charge> { Results = new List <Charge> { new Charge { ValidFrom = from, ValidTo = to, ValueExcludingVAT = 20m, ValueIncludingVAT = 20m * 1.2m }, new Charge { ValidFrom = from.AddDays(1), ValidTo = to.AddDays(1), ValueExcludingVAT = 30m, ValueIncludingVAT = 30m * 1.2m }, }, Count = 1, Next = null, Previous = null }; var uri = OctopusEnergyClient.ComposeGetElectricityStandingChargesUri(productCode, tariffCode, from, to); var client = TestHelper.CreateClient(uri, charges); var charges1 = await client.GetElectricityStandingChargesAsync(productCode, tariffCode, from, to); Assert.AreEqual(charges.Results.Count(), charges1.Count()); var firstExpected = charges.Results.First(); var firstActual = charges1.First(); Assert.AreEqual(firstExpected.ValidFrom, firstActual.ValidFrom); Assert.AreEqual(firstExpected.ValidFromUTC, firstActual.ValidFromUTC); Assert.AreEqual(firstExpected.ValidTo, firstActual.ValidTo); Assert.AreEqual(firstExpected.ValidToUTC, firstActual.ValidToUTC); Assert.AreEqual(firstExpected.ValueIncludingVAT, firstActual.ValueIncludingVAT); Assert.AreEqual(firstExpected.ValueExcludingVAT, firstActual.ValueExcludingVAT); }
public async Task <PagedResults <EventStatus> > GetAllByPocAsync( PagingOptions pagingOptions, SortOptions <Event, EventEntity> sortOptions, SearchOptions <Event, EventEntity> searchOptions, long pocId, CancellationToken ct) { var events = await _eventService.GetAllByByPocAsync(pagingOptions, sortOptions, searchOptions, pocId, ct); var eventReport = new List <EventStatus>(); foreach (var eventInfo in events.Items) { var eventStatus = _mapper.Map <EventStatus>(eventInfo); eventStatus.TotalParticipants = eventInfo.Participant.Count(); eventStatus.TotalAttended = eventInfo.Participant.Count(p => p.Attended); eventStatus.TotalUnregistered = eventInfo.Participant.Count(p => p.Unregistered); eventStatus.TotalNotAttended = eventInfo.Participant.Count(p => p.NotAttended); eventStatus.TotalFeedbackReceived = eventInfo.Feedback.Count(); eventStatus.TotalAttendedFeedback = eventInfo.Participant.Count(p => p.Attended && p.IsFeedbackReceived); eventStatus.TotalUnregisteredFeedback = eventInfo.Participant.Count(p => p.Unregistered && p.IsFeedbackReceived); eventStatus.TotalNotAttendedFeedback = eventInfo.Participant.Count(p => p.NotAttended && p.IsFeedbackReceived); var fiveRating = eventInfo.Feedback.Count(x => x.Rating.Equals(5)); var fourRating = eventInfo.Feedback.Count(x => x.Rating.Equals(4)); var threeRating = eventInfo.Feedback.Count(x => x.Rating.Equals(3)); var twoRating = eventInfo.Feedback.Count(x => x.Rating.Equals(2)); var oneRating = eventInfo.Feedback.Count(x => x.Rating.Equals(1)); var totalCount = fiveRating + fourRating + threeRating + twoRating + oneRating; if (totalCount != 0) { var averageRating = (decimal)((fiveRating * 5) + (fourRating * 4) + (threeRating * 3) + (twoRating * 2) + oneRating) / totalCount; eventStatus.AverageRating = averageRating; } eventReport.Add(eventStatus); } var pagedResult = new PagedResults <EventStatus> { Items = eventReport, TotalSize = events.TotalSize }; return(pagedResult); }
public async Task <IActionResult> GetVisibleBookings( PagingOptions pagingOptions, SortOptions <BookingResource, BookingEntity> sortOptions, SearchOptions <BookingResource, BookingEntity> searchOptions, CancellationToken ct) { if (!ModelState.IsValid) { return(BadRequest(new ApiError(ModelState))); } pagingOptions.Offset = pagingOptions.Offset ?? _defaultPagingOptions.Offset; pagingOptions.Limit = pagingOptions.Limit ?? _defaultPagingOptions.Limit; var bookings = new PagedResults <BookingResource>(); if (User.Identity.IsAuthenticated) { var userCanSeeAllBookings = await _authzService.AuthorizeAsync(User, "ViewAllBookingsPolicy"); if (userCanSeeAllBookings) { bookings = await _bookingService.GetBookingsAsync( pagingOptions, sortOptions, searchOptions, ct); } else { var userId = await _userService.GetUserIdAsync(User); if (userId != null) { bookings = await _bookingService.GetBookingsForUserIdAsync( userId.Value, pagingOptions, sortOptions, searchOptions, ct); } } } var collectionLink = Link.ToCollection(nameof(GetVisibleBookings)); var collection = PagedCollection <BookingResource> .Create( collectionLink, bookings.Items.ToArray(), bookings.TotalSize, pagingOptions); return(Ok(collection)); }
public async Task <IActionResult> Get(string searchTerm, int?level, bool?leafOnly, int pageIndex, int itemsPerPage, string orderBy) { var serviceModel = new GetCategoriesServiceModel { Level = level, Language = CultureInfo.CurrentCulture.Name, SearchTerm = searchTerm, LeafOnly = leafOnly, PageIndex = pageIndex, ItemsPerPage = itemsPerPage, OrderBy = orderBy }; var validator = new GetCategoriesModelValidator(); var validationResult = await validator.ValidateAsync(serviceModel); if (validationResult.IsValid) { var categories = await this.categoryService.GetAsync(serviceModel); if (categories != null) { var response = new PagedResults <IEnumerable <CategoryResponseModel> >(categories.Total, categories.PageSize) { Data = categories.Data.OrEmptyIfNull().Select(x => new CategoryResponseModel { Id = x.Id, IsLeaf = x.IsLeaf, Level = x.Level, Name = x.Name, Order = x.Order, ParentId = x.ParentId, ThumbnailMediaId = x.ThumbnailMediaId, ParentCategoryName = x.ParentCategoryName, LastModifiedDate = x.LastModifiedDate, CreatedDate = x.CreatedDate }) }; return(this.StatusCode((int)HttpStatusCode.OK, response)); } } throw new CustomException(string.Join(ErrorConstants.ErrorMessagesSeparator, validationResult.Errors.Select(x => x.ErrorMessage)), (int)HttpStatusCode.UnprocessableEntity); }
public async Task <ActionResult <Collection <Icon> > > GetStringIcons() { PagedResults <Icon> icons = await _iconRepository.GetStringIconsAsync(); PagingOptions pagingOptions = new PagingOptions(); var collection = PagedCollection <Icon> .Create <IconsResponse>( Link.ToCollection(nameof(GetStringIcons)), icons.Items.ToArray(), icons.TotalSize, pagingOptions) as IconsResponse; collection.IconsQuery = FormMetadata.FromResource <TreasureMap>( Link.ToForm(nameof(GetStringIcons), null, Link.GetMethod, Form.QueryRelation)); return(collection); }
private void BindResults() { string searchQuery = SearchQuery.Text; if (!string.IsNullOrEmpty(searchQuery)) { List <PageData> results = FindPagesContainSearchQuery(searchQuery); /*ResultsRepeater.DataSource = results; * ResultsRepeater.DataBind();*/ PagedResults.DataSource = results; PagedResults.DataBind(); ReplaceLabel.Text = string.Format("Replace \"{0}\" with", searchQuery); } }
/// <summary> /// 返回分页后信息 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="pagedResults">数据</param> /// <param name="format">自定义的格式</param> /// <returns>Json数据</returns> protected JsonResult JsonForGridPaging <T>(PagedResults <T> pagedResults, string format) { return(new JsonResultExtension { Data = new { total = pagedResults.PagerInfo.PageCount, page = pagedResults.PagerInfo.Page, records = pagedResults.PagerInfo.RecordCount, rows = pagedResults.Data }, ContentType = "application/json", Format = format }); }
/// <summary> /// 返回分页后信息 /// </summary> /// <param name="pagedResults"></param> /// <returns></returns> protected JsonResult JsonForGridPaging(PagedResults pagedResults) { return(new JsonResultExtension { Data = new { total = pagedResults.PagerInfo.PageCount, page = pagedResults.PagerInfo.Page, records = pagedResults.PagerInfo.RecordCount, rows = pagedResults.Data, ExtraDatas = pagedResults.ExtraDatas }, ContentType = "application/json", Format = "yyyy-MM-dd HH:mm:ss" }); }
public async Task <IActionResult> Get( Guid?productAttributeId, string searchTerm, int pageIndex, int itemsPerPage, string orderBy) { var serviceModel = new GetProductAttributeItemsServiceModel { ProductAttributeId = productAttributeId, PageIndex = pageIndex, ItemsPerPage = itemsPerPage, SearchTerm = searchTerm, OrderBy = orderBy, Language = CultureInfo.CurrentCulture.Name }; var validator = new GetProductAttributeItemsModelValidator(); var validationResult = await validator.ValidateAsync(serviceModel); if (validationResult.IsValid) { var productAttributes = await this.productAttributesService.GetProductAttributeItemsAsync(serviceModel); if (productAttributes != null) { var response = new PagedResults <IEnumerable <ProductAttributeItemResponseModel> >(productAttributes.Total, productAttributes.PageSize) { Data = productAttributes.Data.OrEmptyIfNull().Select(x => new ProductAttributeItemResponseModel { Id = x.Id, Name = x.Name, Order = x.Order, LastModifiedDate = x.LastModifiedDate, CreatedDate = x.CreatedDate }) }; return(this.StatusCode((int)HttpStatusCode.OK, response)); } } throw new CustomException(string.Join(ErrorConstants.ErrorMessagesSeparator, validationResult.Errors.Select(x => x.ErrorMessage)), (int)HttpStatusCode.UnprocessableEntity); }
public async Task <IActionResult> GetScribesAsync( [FromQuery] PagingOptions pagingOptions, [FromQuery] SortOptions <User, UserEntity> sortOptions, [FromQuery] SearchOptions <User, UserEntity> searchOptions, [FromBody] SearchTermsForm searchTerms, CancellationToken ct) { if (!ModelState.IsValid) { return(BadRequest(new ApiError(ModelState))); } pagingOptions.Offset = pagingOptions.Offset ?? _defaultPagingOptions.Offset; pagingOptions.Limit = pagingOptions.Limit ?? _defaultPagingOptions.Limit; var users = new PagedResults <User>(); if (User.Identity.IsAuthenticated) { var canSeeEveryone = await _authService .AuthorizeAsync(User, "IsAdminOrTimer"); if (canSeeEveryone.Succeeded) { users = await _userService.GetScribesAsync( pagingOptions, sortOptions, searchOptions, searchTerms.SearchTerms, ct); } else { var myself = await _userService.GetUserAsync(User); users.Items = new[] { myself }; users.TotalSize = 1; } } var collection = PagedCollection <User> .Create( Link.To(nameof(GetVisibleUsersAsync)), users.Items.ToArray(), users.TotalSize, pagingOptions); return(Ok(collection)); }
public async Task <PagedResults <Flight> > Get(string airportCode, int page = 1, int pageSize = 10) { var results = new PagedResults <Flight>(); using (var connection = new SqlConnection(_connectionString)) { await connection.OpenAsync(); var query = @" SELECT f.*, sf.* FROM Flight f INNER JOIN ScheduledFlight sf ON f.ScheduledFlightId = sf.Id INNER JOIN Airport a ON sf.ArrivalAirportId = a.Id INNER JOIN Airport d ON sf.DepartureAirportId = d.Id WHERE a.Code = @AirportCode OR d.Code = @AirportCode ORDER BY f.Day, sf.FlightNumber OFFSET @Offset ROWS FETCH NEXT @PageSize ROWS ONLY; SELECT COUNT(*) FROM Flight f INNER JOIN ScheduledFlight sf ON f.ScheduledFlightId = sf.Id INNER JOIN Airport a ON sf.ArrivalAirportId = a.Id INNER JOIN Airport d ON sf.DepartureAirportId = d.Id WHERE a.Code = @AirportCode OR d.Code = @AirportCode "; using (var multi = await connection.QueryMultipleAsync(query, new { AirportCode = airportCode, Offset = (page - 1) * pageSize, PageSize = pageSize })) { results.Items = multi.Read <Flight, ScheduledFlight, Flight>((f, sf) => { f.ScheduledFlight = sf; return(f); }).ToList(); results.TotalCount = multi.ReadFirst <int>(); } } return(results); }
public async Task <ActionResult <PagedCollection <User> > > GetVisibleUsers( [FromQuery] PagingOptions pagingOptions, [FromQuery] SortOptions <User, UserEntity> sortOptions, [FromQuery] SearchOptions <User, UserEntity> searchOptions) { pagingOptions.Offset = pagingOptions.Offset ?? _defaultPagingOptions.Offset; pagingOptions.Limit = pagingOptions.Limit ?? _defaultPagingOptions.Limit; var users = new PagedResults <User> { Items = Enumerable.Empty <User>() }; if (User.Identity.IsAuthenticated) { var canSeeEveryone = await _authzService.AuthorizeAsync( User, "ViewAllUsersPolicy"); if (canSeeEveryone.Succeeded) { users = await _userService.GetUsersAsync( pagingOptions, sortOptions, searchOptions); } else { var myself = await _userService.GetUserAsync(User); users.Items = new[] { myself }; users.TotalSize = 1; } } var collection = PagedCollection <User> .Create <UsersResponse>( Link.ToCollection(nameof(GetVisibleUsers)), users.Items.ToArray(), users.TotalSize, pagingOptions); collection.Me = Link.To(nameof(UserinfoController.Userinfo)); collection.Register = FormMetadata.FromModel( new RegisterForm(), Link.ToForm(nameof(RegisterUser), relations: Form.CreateRelation)); return(collection); }
public virtual bool IsFactorSetup(string factorId) { bool bNotSetup = false; PagedResults <Models.Factor> factors = this.GetList(); foreach (Models.Factor f in factors.Results) { if (f.Id == factorId) { if (f.Status == "NOT_SETUP") { bNotSetup = true; } break; } } return(!bNotSetup); }
public async Task <PagedResults <Author> > GetAllAuthors(int page, int pageSize, string orderBy, bool ascending) { PagedResults <Author> result = null; var builder = Builders <AuthorMongoDb> .Filter; IEnumerable <AuthorMongoDb> CollectionResult = db.Authors.Find(builder.Empty).ToEnumerable(); IQueryable <AuthorMongoDb> authorsQueryResult = CollectionResult.AsQueryable(); PagedResults <AuthorMongoDb> authorPagedResult = await pagination.CreatePagedResultsAsync(authorsQueryResult, page, pageSize, orderBy, ascending); if (authorPagedResult != null) { mongoDbDataConvert.InitData(authorPagedResult); result = mongoDbDataConvert.GetFormatedPagedResults(); } return(result); }
async public Task <PagedResults <User> > GetAllUserAsync(int pagenumber, int rowcount) { if (rowcount <= 0 || pagenumber <= 0) { return(null); } // await Task.WhenAll(userRepository.GetTotalUserCount(), userRepository.GetAllUserAsync(pagenumber, rowcount)); Task <int> totalCount = userRepository.GetTotalUserCount(); Task <List <User> > userList = userRepository.GetAllUserAsync(pagenumber, rowcount); PagedResults <User> userListResult = new PagedResults <User>(); userListResult.PageNumber = pagenumber; userListResult.PageSize = rowcount; userListResult.TotalRecordCount = await totalCount; userListResult.Results = await userList; return(userListResult); }
public async Task <PagedResults <IEnumerable <ProductAttributeServiceModel> > > GetAsync(GetProductAttributesServiceModel model) { var productAttributes = this.context.ProductAttributes.Where(x => x.IsActive); if (!string.IsNullOrWhiteSpace(model.SearchTerm)) { productAttributes = productAttributes.Where(x => x.ProductAttributeTranslations.Any(x => x.Name.StartsWith(model.SearchTerm) && x.IsActive)); } productAttributes = productAttributes.ApplySort(model.OrderBy); var pagedProductAttributes = productAttributes.PagedIndex(new Pagination(productAttributes.Count(), model.ItemsPerPage), model.PageIndex); var pagedProductAttributeServiceModels = new PagedResults <IEnumerable <ProductAttributeServiceModel> >(pagedProductAttributes.Total, pagedProductAttributes.PageSize); var productAttributeServiceModels = new List <ProductAttributeServiceModel>(); foreach (var pagedProductAttribute in pagedProductAttributes.Data.ToList()) { var productAttributeServiceModel = new ProductAttributeServiceModel { Id = pagedProductAttribute.Id, Order = pagedProductAttribute.Order, LastModifiedDate = pagedProductAttribute.LastModifiedDate, CreatedDate = pagedProductAttribute.CreatedDate }; var productAttributeTranslations = pagedProductAttribute.ProductAttributeTranslations.FirstOrDefault(x => x.Language == model.Language && x.IsActive); if (productAttributeTranslations == null) { productAttributeTranslations = pagedProductAttribute.ProductAttributeTranslations.FirstOrDefault(x => x.IsActive); } productAttributeServiceModel.Name = productAttributeTranslations?.Name; productAttributeServiceModels.Add(productAttributeServiceModel); } pagedProductAttributeServiceModels.Data = productAttributeServiceModels; return(pagedProductAttributeServiceModels); }
private PagedResults <T2> GetPagedResults <T1, T2>(IQueryable <T1> query, PagedRequest request, Func <T1, T2> transform) { var response = new PagedResults <T2>(); response.Filter = request.Filter; response.FilterValues = request.FilterValues; response.TotalCount = query.Count(); response.Order = request.Order; response.PerPage = request.PerPage; response.Page = response.TotalPages < request.Page ? response.TotalPages : request.Page; response.Results = query .Skip((response.Page - 1) * response.PerPage) .Take(response.PerPage) .ToList() .Select(transform) .ToList(); return(response); }
private PagedResults <Models.User> GetActiveUsers(SearchType type, string strAttribute, string strEqualToValue) { string strEx = string.Empty; PagedResults <Models.User> results = null; try { var usersClient = oktaClient.GetUsersClient(); FilterBuilder filter = new FilterBuilder(); filter.Where(strAttribute); filter.EqualTo(strEqualToValue); results = usersClient.GetList(filter: filter, searchType: type); } catch (OktaException e) { strEx = string.Format("Error Code: {0} - Summary: {1} - Message: {2}", e.ErrorCode, e.ErrorSummary, e.Message); } return(results); }
public async Task GetGasConsumptionSucceedsAsync() { var from = DateTimeOffset.UtcNow.AddDays(-2); var to = DateTimeOffset.UtcNow.AddDays(-1); var mprn = "A123Z"; var serialNumber = "J0123456K"; var interval = Interval.Hour; var consumption = new PagedResults <Consumption> { Results = new List <Consumption> { new Consumption { Start = from, End = from.AddMinutes(30), Quantity = 0.5m }, new Consumption { Start = from.AddMinutes(30), End = from.AddMinutes(60), Quantity = 0.75m }, }, Count = 1, Next = null, Previous = null }; var uri = OctopusEnergyClient.ComposeGetGasConsumptionUri(mprn, serialNumber, from, to, interval); var client = TestHelper.CreateClient(uri, consumption); var consumption1 = await client.GetGasConsumptionAsync("key", mprn, serialNumber, from, to, Interval.Hour); Assert.AreEqual(consumption.Results.Count(), consumption1.Count()); var firstExpected = consumption.Results.First(); var firstActual = consumption1.First(); Assert.AreEqual(firstExpected.Start, firstActual.Start); Assert.AreEqual(firstExpected.End, firstActual.End); Assert.AreEqual(firstExpected.Quantity, firstActual.Quantity); }
private void InitialiseMembers() { AvailableMarketReviews = new PagedResults<MarketReview>(); }
public PagedResults<UserDataItem> FdpUserGetMany(UserFilter filter) { PagedResults<UserDataItem> retVal; using (var conn = DbHelper.GetDBConnection()) { try { var para = new DynamicParameters(); var totalRecords = 0; var totalDisplayRecords = 0; if (!string.IsNullOrEmpty(filter.CDSId)) { para.Add("@CDSId", filter.CDSId, DbType.String); } if (!string.IsNullOrEmpty(filter.FilterMessage)) { para.Add("@FilterMessage", filter.FilterMessage, DbType.String); } if (filter.HideInactiveUsers.HasValue) { para.Add("@HideInactiveUsers", filter.HideInactiveUsers, DbType.Boolean); } if (filter.PageIndex.HasValue) { para.Add("@PageIndex", filter.PageIndex.Value, DbType.Int32); } if (filter.PageSize.HasValue) { para.Add("@PageSize", filter.PageSize.Value, DbType.Int32); } if (filter.SortIndex.HasValue) { para.Add("@SortIndex", filter.SortIndex.Value, DbType.Int32); } if (filter.SortDirection != SortDirection.NotSet) { var direction = filter.SortDirection == SortDirection.Descending ? "DESC" : "ASC"; para.Add("@SortDirection", direction, DbType.String); } para.Add("@TotalPages", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalDisplayRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); var results = conn.Query<UserDataItem>("dbo.Fdp_User_GetMany", para, commandType: CommandType.StoredProcedure); var enumerable = results as IList<UserDataItem> ?? results.ToList(); if (enumerable.Any()) { totalRecords = para.Get<int>("@TotalRecords"); totalDisplayRecords = para.Get<int>("@TotalDisplayRecords"); } retVal = new PagedResults<UserDataItem> { PageIndex = filter.PageIndex ?? 1, TotalRecords = totalRecords, TotalDisplayRecords = totalDisplayRecords, PageSize = filter.PageSize ?? totalRecords }; var currentPage = enumerable.ToList(); retVal.CurrentPage = currentPage; } catch (Exception ex) { Log.Error(ex); throw; } } return retVal; }
static void Main() { // get OAuth token using Client Credentials string tenantName = "GraphDir1.onMicrosoft.com"; string authString = "https://login.windows.net/" + tenantName; AuthenticationContext authenticationContext = new AuthenticationContext(authString,false); // Config for OAuth client credentials string clientId = "118473c2-7619-46e3-a8e4-6da8d5f56e12"; string clientSecret = "hOrJ0r0TZ4GQ3obp+vk3FZ7JBVP+TX353kNo6QwNq7Q="; ClientCredential clientCred = new ClientCredential(clientId, clientSecret); string resource = "https://graph.windows.net"; string token; try { AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resource, clientCred); token = authenticationResult.AccessToken; } catch (AuthenticationException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message); if (ex.InnerException != null) { //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx //InnerException Message will contain the HTTP error status codes mentioned in the link above Console.WriteLine("Error detail: {0}", ex.InnerException.Message); } Console.ResetColor(); Console.ReadKey(); return; } // record start DateTime of execution string CurrentDateTime = DateTime.Now.ToUniversalTime().ToString(); //********************************************************************* // setup Graph connection //********************************************************************* Guid ClientRequestId = Guid.NewGuid(); GraphSettings graphSettings = new GraphSettings(); graphSettings.ApiVersion = "2013-11-08"; graphSettings.GraphDomainName = "graph.windows.net"; GraphConnection graphConnection = new GraphConnection(token, ClientRequestId,graphSettings); VerifiedDomain initialDomain = new VerifiedDomain(); VerifiedDomain defaultDomain = new VerifiedDomain(); //********************************************************************* // Get Tenant Details // Note: update the string tenantId with your TenantId. // This can be retrieved from the login Federation Metadata end point: // https://login.windows.net/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml // Replace "GraphDir1.onMicrosoft.com" with any domain owned by your organization // The returned value from the first xml node "EntityDescriptor", will have a STS URL // containing your tenantId e.g. "https://sts.windows.net/4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34/" is returned for GraphDir1.onMicrosoft.com //********************************************************************* string tenantId = "4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34"; GraphObject tenant = graphConnection.Get(typeof(TenantDetail), tenantId); if (tenant == null) { Console.WriteLine("Tenant not found"); } else { TenantDetail tenantDetail = (TenantDetail)tenant; Console.WriteLine("Tenant Display Name: " + tenantDetail.DisplayName); // Get the Tenant's Verified Domains initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value); Console.WriteLine("Initial Domain Name: " + initialDomain.Name); defaultDomain = tenantDetail.VerifiedDomains.First(x => x.Default.HasValue && x.Default.Value); Console.WriteLine("Default Domain Name: " + defaultDomain.Name); foreach (string techContact in tenantDetail.TechnicalNotificationMails) { Console.WriteLine("Tenant Tech Contact: " + techContact); } } //********************************************************************* // Demonstrate Getting a list of Users with paging (get 4 users), sort by displayName //********************************************************************* Console.WriteLine("\n Retrieving Users"); FilterGenerator userFilter = new FilterGenerator(); userFilter.Top = 4; userFilter.OrderByProperty = GraphProperty.DisplayName; PagedResults<User> users = graphConnection.List<User>(null, userFilter); foreach (User user in users.Results) { Console.WriteLine("UserObjectId: {0} UPN: {1}", user.ObjectId, user.UserPrincipalName); } // if there are more users to retrieve, get the rest of the users, and specify maximum page size 999 do { userFilter.Top = 999; if (users.PageToken != null) { users = graphConnection.List<User>(users.PageToken, userFilter); Console.WriteLine("\n Next page of results"); } foreach (User user in users.Results) { Console.WriteLine("DisplayName: {0} UPN: {1}", user.DisplayName, user.UserPrincipalName); } } while (users.PageToken != null); // search for a single user by UPN string searchString = "adam@" + initialDomain.Name; FilterGenerator filter = new FilterGenerator(); Expression filterExpression = ExpressionHelper.CreateEqualsExpression(typeof(User), GraphProperty.UserPrincipalName, searchString ); filter.QueryFilter = filterExpression; User retrievedUser = new User(); PagedResults<User> pagedUserResults = graphConnection.List<User>(null, filter); // should only find one user with the specified UPN if (pagedUserResults.Results.Count == 1) { retrievedUser = pagedUserResults.Results[0] as User; } else { Console.WriteLine("User not found {0}", searchString); } if (retrievedUser.UserPrincipalName != null) { Console.WriteLine("\n Found User: "******" UPN: " + retrievedUser.UserPrincipalName); // get the user's Manager int count = 0; PagedResults<GraphObject> managers = graphConnection.GetLinkedObjects(retrievedUser, LinkProperty.Manager, null); foreach (GraphObject managerObject in managers.Results) { if (managerObject.ODataTypeName.Contains("User")) { User manager = (User)managers.Results[count]; Console.WriteLine(" Manager: {0} UPN: {1}", manager.DisplayName, manager.UserPrincipalName); } count++; } //********************************************************************* // get the user's Direct Reports //********************************************************************* int top = 99; PagedResults<GraphObject> directReportObjects = graphConnection.GetLinkedObjects(retrievedUser, LinkProperty.DirectReports, null, top); foreach (GraphObject graphObject in directReportObjects.Results) { if (graphObject.ODataTypeName.Contains("User")) { User User = (User)graphObject; Console.WriteLine(" DirectReport {0}: {1} UPN: {2}", User.ObjectType, User.DisplayName, User.UserPrincipalName); } if (graphObject.ODataTypeName.Contains("Contact")) { Contact Contact = (Contact)graphObject; Console.WriteLine(" DirectReport {0}: {1} Mail: {2} ", Contact.ObjectType, Contact.DisplayName, Contact.Mail); } } //********************************************************************* // get a list of Group IDs that the user is a member of //********************************************************************* Console.WriteLine("\n {0} is a member of the following Groups (IDs)", retrievedUser.DisplayName); bool securityGroupsOnly = false; IList<string> usersGroupMembership = graphConnection.GetMemberGroups(retrievedUser, securityGroupsOnly); foreach (String groupId in usersGroupMembership) { Console.WriteLine("Member of Group ID: "+ groupId); } //********************************************************************* // get the User's Group and Role membership, getting the complete set of objects //********************************************************************* PagedResults<GraphObject> memberOfObjects = graphConnection.GetLinkedObjects(retrievedUser, LinkProperty.MemberOf, null, top); foreach (GraphObject graphObject in memberOfObjects.Results) { if (graphObject.ODataTypeName.Contains("Group")) { Group Group = (Group)graphObject; Console.WriteLine(" Group: {0} Description: {1}", Group.DisplayName, Group.Description); } if (graphObject.ODataTypeName.Contains("Role")) { Role Role = (Role)graphObject; Console.WriteLine(" Role: {0} Description: {1}", Role.DisplayName, Role.Description); } } } //********************************************************************* // People picker // Search for a user using text string "ad" match against userPrincipalName, proxyAddresses, displayName, giveName, surname //********************************************************************* searchString = "ad"; Console.WriteLine("\nSearching for any user with string {0} in UPN,ProxyAddresses,DisplayName,First or Last Name", searchString); FilterGenerator userMatchFilter = new FilterGenerator(); userMatchFilter.Top = 19; Expression firstExpression = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.UserPrincipalName, searchString); Expression secondExpression = ExpressionHelper.CreateAnyExpression(typeof(User), GraphProperty.ProxyAddresses, "smtp:" + searchString); userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(firstExpression, secondExpression, ExpressionType.Or); Expression thirdExpression = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.DisplayName, searchString); userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(userMatchFilter.QueryFilter, thirdExpression, ExpressionType.Or); Expression fourthExpression = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.GivenName, searchString); userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(userMatchFilter.QueryFilter, fourthExpression, ExpressionType.Or); Expression fifthExpression = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.Surname, searchString); userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(userMatchFilter.QueryFilter, fifthExpression, ExpressionType.Or); PagedResults<User> serachResults = graphConnection.List<User>(null, userMatchFilter); if (serachResults.Results.Count > 0) { foreach (User User in serachResults.Results) { Console.WriteLine("User DisplayName: {0} UPN: {1}", User.DisplayName, User.UserPrincipalName); } } else { Console.WriteLine("User not found"); } //********************************************************************* // Search for a group using a startsWith filter (displayName property) //********************************************************************* Group retrievedGroup = new Group(); searchString = "Wash"; filter.QueryFilter = ExpressionHelper.CreateStartsWithExpression(typeof(Group), GraphProperty.DisplayName, searchString); filter.Top = 99; PagedResults<Group> pagedGroupResults = graphConnection.List<Group>(null, filter); if (pagedGroupResults.Results.Count > 0) { retrievedGroup = pagedGroupResults.Results[0] as Group; } else { Console.WriteLine("Group Not Found"); } if (retrievedGroup.ObjectId != null) { Console.WriteLine("\n Found Group: " + retrievedGroup.DisplayName + " " + retrievedGroup.Description); //********************************************************************* // get the groups' membership using GetAllDirectLinks - // Note this method retrieves ALL links in one request - please use this method with care - this // may return a very large number of objects //********************************************************************* GraphObject graphObj = (GraphObject)retrievedGroup; IList<GraphObject> members = graphConnection.GetAllDirectLinks(graphObj, LinkProperty.Members); if (members.Count > 0) { Console.WriteLine(" Members:"); foreach (GraphObject graphObject in members) { if (graphObject.ODataTypeName.Contains("User")) { User User = (User)graphObject; Console.WriteLine("User DisplayName: {0} UPN: {1}", User.DisplayName, User.UserPrincipalName); } if (graphObject.ODataTypeName.Contains("Group")) { Group Group = (Group)graphObject; Console.WriteLine("Group DisplayName: {0}", Group.DisplayName); } if (graphObject.ODataTypeName.Contains("Contact")) { Contact Contact = (Contact)graphObject; Console.WriteLine("Contact DisplayName: {0}", Contact.DisplayName); } } } } //********************************************************************* // Search for a Role by displayName //********************************************************************* searchString = "Company Administrator"; filter.QueryFilter = ExpressionHelper.CreateStartsWithExpression(typeof(Role), GraphProperty.DisplayName, searchString); PagedResults<Role> pagedRoleResults = graphConnection.List<Role>(null, null); if (pagedRoleResults.Results.Count > 0) { foreach (GraphObject graphObject in pagedRoleResults.Results) { Role role = graphObject as Role; if (role.DisplayName == searchString.Trim()) { Console.WriteLine("\n Found Role: {0} {1} {2} ", role.DisplayName, role.Description, role.ObjectId); } } } else { Console.WriteLine("Role Not Found {0}",searchString); } //********************************************************************* // get the Service Principals //********************************************************************* filter.Top = 999; filter.QueryFilter = null; PagedResults<ServicePrincipal> servicePrincipals = new PagedResults<ServicePrincipal>(); do { servicePrincipals = graphConnection.List<ServicePrincipal>(servicePrincipals.PageToken, filter); if (servicePrincipals != null) { foreach (ServicePrincipal servicePrincipal in servicePrincipals.Results) { Console.WriteLine("Service Principal AppId: {0} Name: {1}", servicePrincipal.AppId, servicePrincipal.DisplayName); } } } while (servicePrincipals.PageToken != null); //********************************************************************* // get the Application objects //********************************************************************* filter.Top = 999; PagedResults<Application> applications = new PagedResults<Application>(); do { applications = graphConnection.List<Application>(applications.PageToken, filter); if (applications != null) { foreach (Application application in applications.Results) { Console.WriteLine("Application AppId: {0} Name: {1}", application.AppId, application.DisplayName); } } }while (applications.PageToken != null); string targetAppId = applications.Results[0].ObjectId; //******************************************************************************************** // We'll now switch to Authenticating using OAuth Authorization Code Grant // which includes user Authentication/Delegation //********************************************************************************************* var redirectUri = new Uri("https://localhost"); string clientIdForUserAuthn = "66133929-66a4-4edc-aaee-13b04b03207d"; AuthenticationResult userAuthnResult = null; try { userAuthnResult = authenticationContext.AcquireToken(resource, clientIdForUserAuthn, redirectUri, PromptBehavior.Always); token = userAuthnResult.AccessToken; Console.WriteLine("\n Welcome " + userAuthnResult.UserInfo.GivenName + " " + userAuthnResult.UserInfo.FamilyName); } catch (AuthenticationException ex) { string message = ex.Message; if (ex.InnerException != null) message += "InnerException : " + ex.InnerException.Message; Console.WriteLine(message); Console.ReadKey(); return; } // re-establish Graph connection using the new token graphConnection = new GraphConnection(token, ClientRequestId, graphSettings); //********************************************************************************************* // Create a new User with a temp password //********************************************************************************************* User userToBeAdded = new User(); userToBeAdded.DisplayName = "Sample App Demo User"; userToBeAdded.UserPrincipalName = "SampleAppDemoUser@" + defaultDomain.Name; userToBeAdded.AccountEnabled = true; userToBeAdded.MailNickname = "SampleAppDemoUser"; userToBeAdded.PasswordProfile = new PasswordProfile(); userToBeAdded.PasswordProfile.Password = "******"; userToBeAdded.PasswordProfile.ForceChangePasswordNextLogin = true; userToBeAdded.UsageLocation = "US"; User newlyCreatedUser = new User(); try { newlyCreatedUser = graphConnection.Add<User>(userToBeAdded); Console.WriteLine("\nNew User {0} was created", userToBeAdded.DisplayName); } catch (GraphException graphException) { Console.WriteLine("\nError creating new user {0} {1}", graphException.Code, graphException.Message); } //********************************************************************************************* // update the newly created user's Password, PasswordPolicies and City //********************************************************************************************* if (newlyCreatedUser.ObjectId != null) { string userObjectId = newlyCreatedUser.ObjectId; // update User's city and reset their User's password User updateUser = graphConnection.Get<User>(userObjectId); updateUser.City = "Seattle"; PasswordProfile passwordProfile = new PasswordProfile(); passwordProfile.Password = "******"; passwordProfile.ForceChangePasswordNextLogin = false; updateUser.PasswordProfile = passwordProfile; updateUser.PasswordPolicies = "DisablePasswordExpiration, DisableStrongPassword"; try { graphConnection.Update(updateUser); Console.WriteLine("\nUser {0} was updated", updateUser.DisplayName); } catch (GraphException graphException) { Console.WriteLine("\nError Updating the user {0} {1}", graphException.Code, graphException.Message); } //********************************************************************************************* // Add, then retrieve a thumbnailPhoto for the newly created user //********************************************************************************************* Bitmap thumbnailPhoto = new Bitmap(20, 20); thumbnailPhoto.SetPixel(5, 5, Color.Beige); thumbnailPhoto.SetPixel(5, 6, Color.Beige); thumbnailPhoto.SetPixel(6, 5, Color.Beige); thumbnailPhoto.SetPixel(6, 6, Color.Beige); using (MemoryStream ms = new MemoryStream()) { thumbnailPhoto.Save(ms, ImageFormat.Jpeg); graphConnection.SetStreamProperty(newlyCreatedUser, GraphProperty.ThumbnailPhoto, ms, "image/jpeg"); // graphConnection.SetStreamProperty(newlyCreatedUser, "thumbnailPhoto", ms, "image/jpeg"); } using (Stream ms = graphConnection.GetStreamProperty(newlyCreatedUser, GraphProperty.ThumbnailPhoto, "image/jpeg")) { Image jpegImage = Image.FromStream(ms); } //********************************************************************************************* // User License Assignment - assign EnterprisePack license to new user, and disable SharePoint service // first get a list of Tenant's subscriptions and find the "Enterprisepack" one // Enterprise Pack includes service Plans for ExchangeOnline, SharePointOnline and LyncOnline // validate that Subscription is Enabled and there are enough units left to assign to users //********************************************************************************************* PagedResults<SubscribedSku> skus = graphConnection.List<SubscribedSku>(null, null); foreach (SubscribedSku sku in skus.Results) { if (sku.SkuPartNumber == "ENTERPRISEPACK") if ((sku.PrepaidUnits.Enabled.Value > sku.ConsumedUnits) && (sku.CapabilityStatus == "Enabled")) { // create addLicense object and assign the Enterprise Sku GUID to the skuId // AssignedLicense addLicense = new AssignedLicense(); addLicense.SkuId = sku.SkuId.Value; // find plan id of SharePoint Service Plan foreach (ServicePlanInfo servicePlan in sku.ServicePlans) { if (servicePlan.ServicePlanName.Contains("SHAREPOINT")) { addLicense.DisabledPlans.Add(servicePlan.ServicePlanId.Value); break; } } IList<AssignedLicense> licensesToAdd = new AssignedLicense[] { addLicense }; IList<Guid> licensesToRemove = new Guid[] { }; // attempt to assign the license object to the new user try { graphConnection.AssignLicense(newlyCreatedUser, licensesToAdd, licensesToRemove); Console.WriteLine("\n User {0} was assigned license {1}", newlyCreatedUser.DisplayName, addLicense.SkuId); } catch (GraphException graphException) { Console.WriteLine("\nLicense assingment failed {0} {1}", graphException.Code, graphException.Message); } } } //********************************************************************************************* // Add User to the "WA" Group //********************************************************************************************* if (retrievedGroup.ObjectId != null) { try { graphConnection.AddLink(retrievedGroup, newlyCreatedUser, LinkProperty.Members); Console.WriteLine("\nUser {0} was added to Group {1}", newlyCreatedUser.DisplayName, retrievedGroup.DisplayName); } catch (GraphException graphException) { Console.WriteLine("\nAdding user to group failed {0} {1}", graphException.Code, graphException.Message); } } //********************************************************************************************* // Create a new Group //********************************************************************************************* Group CaliforniaEmployees = new Group(); CaliforniaEmployees.DisplayName = "California Employees"; CaliforniaEmployees.Description = "Employees in the state of California"; CaliforniaEmployees.MailNickname = "CalEmployees"; CaliforniaEmployees.MailEnabled = false; CaliforniaEmployees.SecurityEnabled = true; Group newGroup = null; try { newGroup = graphConnection.Add<Group>(CaliforniaEmployees); Console.WriteLine("\nNew Group {0} was created", newGroup.DisplayName); } catch (GraphException graphException) { Console.WriteLine("\nError creating new Group {0} {1}", graphException.Code, graphException.Message); } //********************************************************************************************* // Add the new User member to the new Group //********************************************************************************************* if (newGroup.ObjectId != null) { try { graphConnection.AddLink(newGroup, newlyCreatedUser, LinkProperty.Members); Console.WriteLine("\nUser {0} was added to Group {1}", newlyCreatedUser.DisplayName, newGroup.DisplayName); } catch (GraphException graphException) { Console.WriteLine("\nAdding user to group failed {0} {1}", graphException.Code, graphException.Message); } } //********************************************************************************************* // Delete the user that we just created //********************************************************************************************* if (newlyCreatedUser.ObjectId != null) { try { graphConnection.Delete(newlyCreatedUser); Console.WriteLine("\nUser {0} was deleted", newlyCreatedUser.DisplayName); } catch (GraphException graphException) { Console.WriteLine("Deleting User failed {0} {1}", graphException.Code, graphException.Message); } } //********************************************************************************************* // Delete the Group that we just created //********************************************************************************************* if (newGroup.ObjectId != null) { try { graphConnection.Delete(newGroup); Console.WriteLine("\nGroup {0} was deleted", newGroup.DisplayName); } catch (GraphException graphException) { Console.WriteLine("Deleting Group failed: {0} {1}", graphException.Code, graphException.Message); } } } //********************************************************************************************* // Get a list of Mobile Devices from tenant //********************************************************************************************* Console.WriteLine("\nGetting Devices"); FilterGenerator deviceFilter = new FilterGenerator(); deviceFilter.Top = 999; PagedResults<Device> devices = graphConnection.List<Device>(null, deviceFilter); foreach(Device device in devices.Results) { if (device.ObjectId !=null) { Console.WriteLine("Device ID: {0}, Type: {1}", device.DeviceId, device.DeviceOSType); foreach (GraphObject owner in device.RegisteredOwners) { Console.WriteLine("Device Owner ID: " + owner.ObjectId); } } } //********************************************************************************************* // Create a new Application object //********************************************************************************************* Application appObject = new Application(); appObject.DisplayName = "Test-Demo App"; appObject.IdentifierUris.Add("https://localhost/demo/" + Guid.NewGuid().ToString()); appObject.ReplyUrls.Add("https://localhost/demo"); // created Keycredential object for the new App object KeyCredential KeyCredential = new KeyCredential(); KeyCredential.StartDate = DateTime.UtcNow; KeyCredential.EndDate = DateTime.UtcNow.AddYears(1); KeyCredential.Type = "Symmetric"; KeyCredential.Value = Convert.FromBase64String("g/TMLuxgzurjQ0Sal9wFEzpaX/sI0vBP3IBUE/H/NS4="); KeyCredential.Usage = "Verify"; appObject.KeyCredentials.Add(KeyCredential); GraphObject newApp = null; try { newApp = graphConnection.Add(appObject); Console.WriteLine("New Application created: " + newApp.ObjectId); } catch (GraphException graphException) { Console.WriteLine("Application Creation execption: {0} {1}", graphException.Code, graphException.Message); } // Get the application object that was just created if (newApp != null) { GraphObject app = graphConnection.Get(typeof(Application), newApp.ObjectId); Application retrievedApp = (Application)app; //********************************************************************************************* // create a new Service principal //********************************************************************************************* ServicePrincipal newServicePrincpal = new ServicePrincipal(); newServicePrincpal.DisplayName = "Test-Demo App"; newServicePrincpal.AccountEnabled = true; newServicePrincpal.AppId = retrievedApp.AppId; GraphObject newSP = null; try { newSP = graphConnection.Add<ServicePrincipal>(newServicePrincpal); // newSP = graphConnection.Add(newServicePrincpal); Console.WriteLine("New Service Principal created: " + newSP.ObjectId); } catch (GraphException graphException) { Console.WriteLine("Service Principal Creation execption: {0} {1}", graphException.Code, graphException.Message); } //********************************************************************************************* // get all Permission Objects //********************************************************************************************* Console.WriteLine("\n Getting Permissions"); filter.Top = 999; PagedResults<Permission> permissions = new PagedResults<Permission>(); do { try { permissions = graphConnection.List<Permission>(permissions.PageToken, filter); } catch (GraphException graphException) { Console.WriteLine("Error: {0} {1}", graphException.Code, graphException.Message); break; } foreach (Permission permission in permissions.Results) { Console.WriteLine("Permission: {0} Name: {1}", permission.ClientId, permission.Scope); } } while (permissions.PageToken != null); //********************************************************************************************* // Create new permission object //********************************************************************************************* Permission permissionObject = new Permission(); permissionObject.ConsentType = "AllPrincipals"; permissionObject.Scope = "user_impersonation"; permissionObject.StartTime = DateTime.Now; permissionObject.ExpiryTime = (DateTime.Now).AddMonths(12); // resourceId is objectId of the resource, in this case objectId of AzureAd (Graph API) permissionObject.ResourceId = "dbf73c3e-e80b-495b-a82f-2f772bb0a417"; //ClientId = objectId of servicePrincipal permissionObject.ClientId = newSP.ObjectId; GraphObject newPermission = null; try { newPermission = graphConnection.Add(permissionObject); Console.WriteLine("New Permission object created: " + newPermission.ObjectId); } catch (GraphException graphException) { Console.WriteLine("Permission Creation exception: {0} {1}", graphException.Code, graphException.Message); } //********************************************************************************************* // Delete Application Objects //********************************************************************************************* if (retrievedApp.ObjectId != null) { try { graphConnection.Delete(retrievedApp); Console.WriteLine("Deleting Application object: " + retrievedApp.ObjectId); } catch (GraphException graphException) { Console.WriteLine("Application Deletion execption: {0} {1}", graphException.Code, graphException.Message); } } } //********************************************************************************************* // Show Batching with 3 operators. Note: up to 5 operations can be in a batch //********************************************************************************************* // get users Console.WriteLine("\n Executing Batch Request"); BatchRequestItem firstItem = new BatchRequestItem( "GET", false, Utils.GetListUri<User>(graphConnection, null, new FilterGenerator()), null, String.Empty); // get members of a Group Uri membersUri = Utils.GetRequestUri<Group>(graphConnection, retrievedGroup.ObjectId, "members"); BatchRequestItem secondItem = new BatchRequestItem( "GET", false, new Uri(membersUri.ToString()), null, String.Empty); // update an existing group's Description property retrievedGroup.Description = "New Employees in Washington State"; BatchRequestItem thirdItem = new BatchRequestItem( "Patch", true, Utils.GetRequestUri<Group>(graphConnection,retrievedGroup.ObjectId), null, retrievedGroup.ToJson(true)); // Execute the batch requst IList<BatchRequestItem> batchRequest = new BatchRequestItem[] { firstItem, secondItem, thirdItem }; IList<BatchResponseItem> batchResponses = graphConnection.ExecuteBatch(batchRequest); int responseCount = 0; foreach (BatchResponseItem responseItem in batchResponses) { if (responseItem.Failed) { Console.WriteLine("Failed: {0} {1}", responseItem.Exception.Code, responseItem.Exception.ErrorMessage); } else { Console.WriteLine("Batch Item Result {0} succeeded {1}", responseCount++, !responseItem.Failed); } } // this next section shows how to access the signed-in user's mailbox. // First we get a new token for Office365 Exchange Online Resource // using the multi-resource refresh token tha was included when the previoius // token was acquired. // We can now request a new token for Office365 Exchange Online. // string office365Emailresource = "https://outlook.office365.com/"; string office365Token = null; if (userAuthnResult.IsMultipleResourceRefreshToken) { userAuthnResult = authenticationContext.AcquireTokenByRefreshToken(userAuthnResult.RefreshToken, clientIdForUserAuthn, office365Emailresource); office365Token = userAuthnResult.AccessToken; // // Call the Office365 API and retrieve the top item from the user's mailbox. // string requestUrl = "https://outlook.office365.com/EWS/OData/Me/Inbox/Messages?$top=1"; WebRequest getMailboxRequest; getMailboxRequest = WebRequest.Create(requestUrl); getMailboxRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + office365Token); Console.WriteLine("\n Getting the User's Mailbox Contents \n"); // // Read the contents of the user's mailbox, and display to the console. // Stream objStream = null; try { objStream = getMailboxRequest.GetResponse().GetResponseStream(); StreamReader objReader = new StreamReader(objStream); string sLine = ""; int i = 0; while (sLine != null) { i++; sLine = objReader.ReadLine(); if (sLine != null) { Console.WriteLine("{0}:{1}", i, sLine); } } } catch (Exception ex) { Console.WriteLine("\n Error Getting User's Mailbox: {0} \n", ex.Message); } } //********************************************************************************************* // End of Demo Console App //********************************************************************************************* Console.WriteLine("\nCompleted at {0} \n ClientRequestId: {1}", CurrentDateTime, ClientRequestId); Console.ReadKey(); return; }
public PagedResults<FdpTrimMapping> FdpTrimMappingGetMany(TrimFilter filter) { PagedResults<FdpTrimMapping> retVal = null; using (IDbConnection conn = DbHelper.GetDBConnection()) { try { var para = DynamicParameters.FromCDSId(CurrentCDSID); var totalRecords = 0; var totalDisplayRecords = 0; if (!string.IsNullOrEmpty(filter.CarLine)) { para.Add("@CarLine", filter.CarLine, DbType.String); } if (!string.IsNullOrEmpty(filter.ModelYear)) { para.Add("@ModelYear", filter.ModelYear, DbType.String); } if (!string.IsNullOrEmpty(filter.Gateway)) { para.Add("@Gateway", filter.Gateway, DbType.String); } para.Add("@DocumentId", filter.DocumentId, DbType.Int32); if (!string.IsNullOrEmpty(filter.Dpck)) { para.Add("@DPCK", filter.Dpck, DbType.String); } if (filter.IncludeAllTrim) { para.Add("@IncludeAllTrim", filter.IncludeAllTrim, DbType.Boolean); } if (filter.OxoTrimOnly) { para.Add("@OxoTrimOnly", filter.OxoTrimOnly, DbType.Boolean); } if (filter.IgnoreBMC) { para.Add("@IgnoreBMC", filter.IgnoreBMC, DbType.Boolean); } if (filter.PageIndex.HasValue) { para.Add("@PageIndex", filter.PageIndex.Value, DbType.Int32); } if (filter.PageSize.HasValue) { para.Add("@PageSize", filter.PageSize.HasValue ? filter.PageSize.Value : 10, DbType.Int32); } if (filter.SortIndex.HasValue) { para.Add("@SortIndex", filter.SortIndex.Value, DbType.Int32); } if (filter.SortDirection != SortDirection.NotSet) { var direction = filter.SortDirection == SortDirection.Descending ? "DESC" : "ASC"; para.Add("@SortDirection", direction, DbType.String); } para.Add("@TotalPages", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalDisplayRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); var results = conn.Query<FdpTrimMapping>("dbo.Fdp_TrimMapping_GetMany", para, commandType: CommandType.StoredProcedure); if (results.Any()) { totalRecords = para.Get<int>("@TotalRecords"); totalDisplayRecords = para.Get<int>("@TotalDisplayRecords"); } retVal = new PagedResults<FdpTrimMapping> { PageIndex = filter.PageIndex.HasValue ? filter.PageIndex.Value : 1, TotalRecords = totalRecords, TotalDisplayRecords = totalDisplayRecords, PageSize = filter.PageSize.HasValue ? filter.PageSize.Value : totalRecords }; var currentPage = results.ToList(); retVal.CurrentPage = currentPage; } catch (Exception ex) { Log.Error(ex); throw; } } return retVal; }
public PagedResults<Publish> FdpPublishGetMany(TakeRateFilter filter) { using (var conn = DbHelper.GetDBConnection()) { PagedResults<Publish> retVal; try { var para = DynamicParameters.FromCDSId(CurrentCDSID); var totalRecords = 0; var totalDisplayRecords = 0; if (filter.TakeRateId.HasValue) { para.Add("@FdpVolumeHeaderId", filter.TakeRateId, DbType.Int32); } if (filter.MarketId.HasValue) { para.Add("@MarketId", filter.MarketId, DbType.Int32); } if (!string.IsNullOrEmpty(filter.FilterMessage)) { para.Add("@FilterMessage", filter.FilterMessage, DbType.String, size: 50); } if (filter.PageIndex.HasValue) { para.Add("@PageIndex", filter.PageIndex.Value, DbType.Int32); } if (filter.PageSize.HasValue) { para.Add("@PageSize", filter.PageSize.Value, DbType.Int32); } if (filter.SortIndex.HasValue) { para.Add("@SortIndex", filter.SortIndex.Value, DbType.Int32); } if (filter.SortDirection != SortDirection.NotSet) { var direction = filter.SortDirection == SortDirection.Descending ? "DESC" : "ASC"; para.Add("@SortDirection", direction, DbType.String); } para.Add("@TotalPages", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalDisplayRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); var results = conn.Query<Publish>("dbo.Fdp_Publish_GetMany", para, commandType: CommandType.StoredProcedure); var publishedList = results as IList<Publish> ?? results.ToList(); if (publishedList.Any()) { totalRecords = para.Get<int>("@TotalRecords"); totalDisplayRecords = para.Get<int>("@TotalDisplayRecords"); } retVal = new PagedResults<Publish> { PageIndex = filter.PageIndex ?? 1, TotalRecords = totalRecords, TotalDisplayRecords = totalDisplayRecords, PageSize = filter.PageSize ?? totalRecords, CurrentPage = publishedList.ToList() }; } catch (Exception ex) { Log.Error(ex); throw; } return retVal; } }
public PagedResults<OxoDerivative> FdpOxoDerivativeGetMany(DerivativeMappingFilter filter) { PagedResults<FdpDerivativeMapping> interimResults; using (var conn = DbHelper.GetDBConnection()) { try { var para = DynamicParameters.FromCDSId(CurrentCDSID); var totalRecords = 0; var totalDisplayRecords = 0; if (!string.IsNullOrEmpty(filter.CarLine)) { para.Add("@CarLine", filter.CarLine, DbType.String); } if (!string.IsNullOrEmpty(filter.ModelYear)) { para.Add("@ModelYear", filter.ModelYear, DbType.String); } if (!string.IsNullOrEmpty(filter.Gateway)) { para.Add("@Gateway", filter.Gateway, DbType.String); } if (filter.PageIndex.HasValue) { para.Add("@PageIndex", filter.PageIndex.Value, DbType.Int32); } if (filter.PageSize.HasValue) { para.Add("@PageSize", filter.PageSize.Value, DbType.Int32); } if (filter.SortIndex.HasValue) { para.Add("@SortIndex", filter.SortIndex.Value, DbType.Int32); } if (filter.SortDirection != SortDirection.NotSet) { var direction = filter.SortDirection == SortDirection.Descending ? "DESC" : "ASC"; para.Add("@SortDirection", direction, DbType.String); } if (filter.IncludeAllDerivatives) { para.Add("@IncludeAllDerivatives", true, DbType.Boolean); } if (filter.OxoDerivativesOnly) { para.Add("@OxoDerivativesOnly", filter.OxoDerivativesOnly, DbType.Boolean); } para.Add("@DocumentId", filter.DocumentId, DbType.Int32); para.Add("@TotalPages", DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalRecords", DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalDisplayRecords", DbType.Int32, direction: ParameterDirection.Output); var dbResults = conn.Query<FdpDerivativeMapping>("dbo.Fdp_OxoDerivative_GetMany", para, commandType: CommandType.StoredProcedure); var fdpDerivativeMappings = dbResults as IList<FdpDerivativeMapping> ?? dbResults.ToList(); if (fdpDerivativeMappings.Any()) { totalRecords = para.Get<int>("@TotalRecords"); totalDisplayRecords = para.Get<int>("@TotalDisplayRecords"); } interimResults = new PagedResults<FdpDerivativeMapping> { PageIndex = filter.PageIndex ?? 1, TotalRecords = totalRecords, TotalDisplayRecords = totalDisplayRecords, PageSize = filter.PageSize ?? totalRecords }; var currentPage = fdpDerivativeMappings.ToList(); interimResults.CurrentPage = currentPage; } catch (Exception ex) { Log.Error(ex); throw; } } var page = interimResults.CurrentPage.Select(result => new OxoDerivative(result)).ToList(); return new PagedResults<OxoDerivative> { PageIndex = interimResults.PageIndex, PageSize = interimResults.PageSize, TotalDisplayRecords = interimResults.TotalDisplayRecords, TotalFail = interimResults.TotalFail, TotalRecords = interimResults.TotalRecords, TotalSuccess = interimResults.TotalSuccess, CurrentPage = page }; }
private void InitialiseMembers() { IdentifierPrefix = "Page"; Forecast = new EmptyForecast(); Forecasts = new PagedResults<ForecastSummary>(); }
private void InitialiseMembers() { AvailableFiles = new PagedResults<Publish>(); }
public PagedResults<FdpSpecialFeatureMapping> FdpSpecialFeatureMappingGetMany(SpecialFeatureMappingFilter filter) { PagedResults<FdpSpecialFeatureMapping> retVal = null; using (IDbConnection conn = DbHelper.GetDBConnection()) { try { var para = DynamicParameters.FromCDSId(CurrentCDSID); var totalRecords = 0; var totalDisplayRecords = 0; if (!string.IsNullOrEmpty(filter.CarLine)) { para.Add("@CarLine", filter.CarLine, DbType.String); } if (!string.IsNullOrEmpty(filter.ModelYear)) { para.Add("@ModelYear", filter.ModelYear, DbType.String); } if (!string.IsNullOrEmpty(filter.Gateway)) { para.Add("@Gateway", filter.Gateway, DbType.String); } if (filter.PageIndex.HasValue) { para.Add("@PageIndex", filter.PageIndex.Value, DbType.Int32); } if (filter.PageSize.HasValue) { para.Add("@PageSize", filter.PageSize.HasValue ? filter.PageSize.Value : 10, DbType.Int32); } if (filter.SortIndex.HasValue) { para.Add("@SortIndex", filter.SortIndex.Value, DbType.Int32); } if (filter.SortDirection != SortDirection.NotSet) { var direction = filter.SortDirection == SortDirection.Descending ? "DESC" : "ASC"; para.Add("@SortDirection", direction, DbType.String); } para.Add("@TotalPages", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalDisplayRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); var results = conn.Query<FdpSpecialFeatureMapping>("dbo.Fdp_SpecialFeatureMapping_GetMany", para, commandType: CommandType.StoredProcedure); if (results.Any()) { totalRecords = para.Get<int>("@TotalRecords"); totalDisplayRecords = para.Get<int>("@TotalDisplayRecords"); } retVal = new PagedResults<FdpSpecialFeatureMapping> { PageIndex = filter.PageIndex.HasValue ? filter.PageIndex.Value : 1, TotalRecords = totalRecords, TotalDisplayRecords = totalDisplayRecords, PageSize = filter.PageSize.HasValue ? filter.PageSize.Value : totalRecords }; var currentPage = new List<FdpSpecialFeatureMapping>(); foreach (var result in results) { currentPage.Add(result); } retVal.CurrentPage = currentPage; } catch (Exception ex) { Log.Error(ex); throw; } } return retVal; }
public PagedResults<ImportQueue> ImportQueueGetMany(ImportQueueFilter filter) { PagedResults<ImportQueue> retVal = null; using (IDbConnection conn = DbHelper.GetDBConnection()) { try { var para = new DynamicParameters(); var totalRecords = 0; var totalDisplayRecords = 0; if (filter.PageIndex.HasValue) { para.Add("@PageIndex", filter.PageIndex.Value, DbType.Int32); } if (filter.PageSize.HasValue) { para.Add("@PageSize", filter.PageSize.Value, DbType.Int32); } if (filter.ImportStatus != enums.ImportStatus.NotSet) { para.Add("@FdpImportStatusId", (int)filter.ImportStatus, DbType.Int32); } if (!string.IsNullOrEmpty(filter.FilterMessage)) { para.Add("@FilterMessage", filter.FilterMessage, DbType.String, size: 50); } //if (filter.SortIndex.HasValue) //{ // para.Add("@SortIndex", filter.SortIndex.Value, dbType: DbType.Int32); //} para.Add("@SortIndex", filter.SortIndex.GetValueOrDefault(), DbType.Int32); if (filter.SortDirection != enums.SortDirection.NotSet) { var direction = filter.SortDirection == enums.SortDirection.Descending ? "DESC" : "ASC"; para.Add("@SortDirection", direction, DbType.String); } else { para.Add("@SortDirection", "DESC", DbType.String); } para.Add("@TotalPages", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalDisplayRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); var results = conn.Query<ImportQueueDataItem>("dbo.Fdp_ImportQueue_GetMany", para, commandType: CommandType.StoredProcedure); if (results.Any()) { totalRecords = para.Get<int>("@TotalRecords"); totalDisplayRecords = para.Get<int>("@TotalDisplayRecords"); } retVal = new PagedResults<ImportQueue> { PageIndex = filter.PageIndex ?? 1, TotalRecords = totalRecords, TotalDisplayRecords = totalDisplayRecords, PageSize = filter.PageSize ?? totalRecords }; var currentPage = new List<ImportQueue>(); foreach (var result in results) { result.ImportType = ImportTypeDataItem.ToImportType(result); result.ImportStatus = ImportStatusDataItem.ToImportStatus(result); //HydrateImportErrors(result, conn); currentPage.Add(ImportQueueDataItem.ToImportQueue(result)); } retVal.CurrentPage = currentPage; } catch (Exception ex) { Log.Error(ex); throw; } } return retVal; }
private void InitialiseMembers() { TakeRate = new EmptyTakeRateSummary(); TakeRates = new PagedResults<TakeRateSummary>(); Statuses = Enumerable.Empty<TakeRateStatus>(); CurrentTakeRateDataItem = new EmptyTakeRateDataItem(); CurrentAction = TakeRateDataItemAction.NotSet; IdentifierPrefix = "Page"; Document = new EmptyTakeRateDocument(); MarketReviewStatus = MarketReviewStatus.NotSet; }
public PagedResults<ImportError> ImportErrorGetMany(ImportQueueFilter filter) { PagedResults<ImportError> retVal = null; using (IDbConnection connection = DbHelper.GetDBConnection()) { try { var para = new DynamicParameters(); var totalRecords = 0; var totalDisplayRecords = 0; var totalImportedRecords = 0; var totalFailedRecords = 0; para.Add("@FdpImportQueueId", filter.ImportQueueId.Value, DbType.Int32); if (filter.ExceptionType != enums.ImportExceptionType.NotSet) { para.Add("@FdpImportExceptionTypeId", (int)filter.ExceptionType, DbType.Int32); } if (!string.IsNullOrEmpty(filter.FilterMessage)) { para.Add("@FilterMessage", filter.FilterMessage, DbType.String, size: 50); } if (filter.PageIndex.HasValue) { para.Add("@PageIndex", filter.PageIndex.Value, DbType.Int32); } para.Add("@PageSize", filter.PageSize.HasValue ? filter.PageSize.Value : 100, DbType.Int32); if (filter.SortIndex.HasValue) { para.Add("@SortIndex", filter.SortIndex.Value, DbType.Int32); } if (filter.SortIndex.HasValue) { para.Add("@SortIndex", filter.SortIndex.GetValueOrDefault(), DbType.Int32); } if (filter.SortDirection != enums.SortDirection.NotSet) { var direction = filter.SortDirection == enums.SortDirection.Descending ? "DESC" : "ASC"; para.Add("@SortDirection", direction, DbType.String); } para.Add("@TotalPages", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalDisplayRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalImportedRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalFailedRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); var results = connection.Query<ImportError>("dbo.Fdp_ImportError_GetMany", para, commandType: CommandType.StoredProcedure); if (results.Any()) { totalRecords = para.Get<int>("@TotalRecords"); totalDisplayRecords = para.Get<int>("@TotalDisplayRecords"); totalImportedRecords = para.Get<int>("@TotalImportedRecords"); totalFailedRecords = para.Get<int>("@TotalFailedRecords"); } retVal = new PagedResults<ImportError> { PageIndex = filter.PageIndex.HasValue ? filter.PageIndex.Value : 1, TotalRecords = totalRecords, TotalDisplayRecords = totalDisplayRecords, TotalSuccess = totalImportedRecords, TotalFail = totalFailedRecords, PageSize = filter.PageSize.HasValue ? filter.PageSize.Value : totalRecords }; retVal.CurrentPage = results; } catch (Exception ex) { Log.Error(ex); throw; } } return retVal; }
public PagedResults<ForecastSummary> ForecastGetMany(ForecastFilter filter) { PagedResults<ForecastSummary> retVal; using (var conn = DbHelper.GetDBConnection()) { try { var para = new DynamicParameters(); var totalRecords = 0; var totalDisplayRecords = 0; if (filter.ForecastId.HasValue) { para.Add("@ForecastId", filter.ForecastId.Value, DbType.Int32); } if (!string.IsNullOrEmpty(filter.FilterMessage)) { para.Add("@FilterMessage", filter.FilterMessage, DbType.String, size: 50); } if (filter.PageIndex.HasValue) { para.Add("@PageIndex", filter.PageIndex.Value, DbType.Int32); } if (filter.PageSize.HasValue) { para.Add("@PageSize", filter.PageSize.Value, DbType.Int32); } if (filter.SortIndex.HasValue) { para.Add("@SortIndex", filter.SortIndex.Value, DbType.Int32); } if (filter.SortDirection != Model.Enumerations.SortDirection.NotSet) { var direction = filter.SortDirection == Model.Enumerations.SortDirection.Descending ? "DESC" : "ASC"; para.Add("@SortDirection", direction, DbType.String); } // TODO implement the CDSId to get only those forecasts the user has permissions for para.Add("@CDSId", CurrentCDSID, DbType.String); para.Add("@TotalPages", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalDisplayRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); var results = conn.Query<ForecastSummary>("dbo.Fdp_Forecast_GetMany", para, commandType: CommandType.StoredProcedure); var forecastSummaries = results as IList<ForecastSummary> ?? results.ToList(); if (forecastSummaries.Any()) { totalRecords = para.Get<int>("@TotalRecords"); totalDisplayRecords = para.Get<int>("@TotalDisplayRecords"); } retVal = new PagedResults<ForecastSummary>() { PageIndex = filter.PageIndex ?? 1, TotalRecords = totalRecords, TotalDisplayRecords = totalDisplayRecords, PageSize = filter.PageSize ?? totalRecords }; var currentPage = new List<ForecastSummary>(); foreach (var result in forecastSummaries) { currentPage.Add(result); } retVal.CurrentPage = currentPage; } catch (Exception ex) { AppHelper.LogError("ForecastDataStore.ForecastGetMany", ex.Message, CurrentCDSID); throw; } } return retVal; }
public JsonResult GetFinishedEvents(EventsQueryParam param) { PagedResults<Events> results = new PagedResults<Events>(); results.Data = new List<Events>(); results.PagerInfo = new PagerInfo(new PageParam() { }); if (param.PersonsId.HasValue) { param.SortName = "DateModified"; param.SortOrder = "desc"; param.HasFinished = true; results = eventsModel.AdvQuery(param); } return JsonForGrid(results); }
public PagedResults<TakeRateSummary> FdpTakeRateHeaderGetManyByUsername(TakeRateFilter filter) { using (var conn = DbHelper.GetDBConnection()) { PagedResults<TakeRateSummary> retVal; try { var para = new DynamicParameters(); var totalRecords = 0; var totalDisplayRecords = 0; if (filter.DocumentId.HasValue) { para.Add("@DocumentId", filter.DocumentId, DbType.Int32); } if (filter.TakeRateId.HasValue) { para.Add("@FdpVolumeHeaderId", filter.TakeRateId, DbType.Int32); } if (!string.IsNullOrEmpty(filter.FilterMessage)) { para.Add("@FilterMessage", filter.FilterMessage, DbType.String, size: 50); } if (filter.TakeRateStatusId.HasValue) { para.Add("@FdpTakeRateStatusId", filter.TakeRateStatusId, DbType.Int32); } if (filter.PageIndex.HasValue) { para.Add("@PageIndex", filter.PageIndex.Value, DbType.Int32); } if (filter.PageSize.HasValue) { para.Add("@PageSize", filter.PageSize.Value, DbType.Int32); } if (filter.SortIndex.HasValue) { para.Add("@SortIndex", filter.SortIndex.Value, DbType.Int32); } if (filter.SortDirection != SortDirection.NotSet) { var direction = filter.SortDirection == SortDirection.Descending ? "DESC" : "ASC"; para.Add("@SortDirection", direction, DbType.String); } // TODO implement the CDSId to get only those forecasts the user has permissions for para.Add("@CDSId", CurrentCDSID, DbType.String); para.Add("@TotalPages", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); para.Add("@TotalDisplayRecords", dbType: DbType.Int32, direction: ParameterDirection.Output); var results = conn.Query<TakeRateSummary>("dbo.Fdp_TakeRateHeader_GetManyByUsername", para, commandType: CommandType.StoredProcedure); var takeRateSummaries = results as IList<TakeRateSummary> ?? results.ToList(); if (takeRateSummaries.Any()) { totalRecords = para.Get<int>("@TotalRecords"); totalDisplayRecords = para.Get<int>("@TotalDisplayRecords"); } retVal = new PagedResults<TakeRateSummary> { PageIndex = filter.PageIndex ?? 1, TotalRecords = totalRecords, TotalDisplayRecords = totalDisplayRecords, PageSize = filter.PageSize ?? totalRecords }; var currentPage = takeRateSummaries.ToList(); retVal.CurrentPage = currentPage; } catch (Exception ex) { Log.Error(ex); throw; } return retVal; } }