private void Enrich(TodoRepresentation todo, UrlHelper url)
 {
     var selfUrl = url.Link("DefaultApi", new { controller = "todos", todo.id });
     todo.AddLink(new SelfLink(selfUrl));
     todo.AddLink(new EditLink(selfUrl));
     todo.AddLink(new DeleteLink(selfUrl));
 }
        public IEnumerable<StudentV2BaseModel> Get(int page = 0, int pageSize = 10)
        {
            IQueryable<Student> query;

            query = TheRepository.GetAllStudentsWithEnrollments().OrderBy(c => c.LastName);

            var totalCount = query.Count();
            var totalPages = Math.Ceiling((double)totalCount / pageSize);

            var urlHelper = new UrlHelper(Request);
            var prevLink = page > 0 ? urlHelper.Link("Students", new { page = page - 1, pageSize = pageSize }) : "";
            var nextLink = page < totalPages - 1 ? urlHelper.Link("Students", new { page = page + 1, pageSize = pageSize }) : "";

            var paginationHeader = new
            {
                TotalCount = totalCount,
                TotalPages = totalPages,
                PrevPageLink = prevLink,
                NextPageLink = nextLink
            };

            System.Web.HttpContext.Current.Response.Headers.Add("X-Pagination",
                                                                 Newtonsoft.Json.JsonConvert.SerializeObject(paginationHeader));

            var results = query
                        .Skip(pageSize * page)
                        .Take(pageSize)
                        .ToList()
                        .Select(s => TheModelFactory.CreateV2Summary(s));

            return results;
        }
Exemplo n.º 3
0
        public object Get(int contactgroupid, int contactId = 0, int page = 0)
        {
            var userName = _identityService.CurrentUser;

            var baseQuery = TheRepository.GetContactGroupContacts(_identityService.CurrentUser,contactgroupid)
                .OrderByDescending(c => c.FirstName);

            var totalCount = baseQuery.Count();
            var totalPages = Math.Ceiling((double)totalCount / PAGE_SIZE);

            var helper = new UrlHelper(Request);
            var preUrl = page > 0 ? helper.Link("Contacts", new { page = page - 1 }) : "";
            var newUrl = page < totalPages - 1 ? helper.Link("Contacts", new { page = page + 1 }) : "";

            var results = baseQuery
                .Skip(PAGE_SIZE * page)
                .Take(PAGE_SIZE)
                .ToList()
                .Select(c => TheModelFactory.Create(c));

            return new
            {
                TotalCount = totalCount,
                TotalPages = totalPages,
                PrevPageUrl = preUrl,
                NextPageUrl = newUrl,
                Results = results,
            };
        }
 public IHttpActionResult Get(int expenseGroupId, string fields = null, string sort = "Date", int page = 1, int pageSize = maxPageSize)
 {
     try
     {
         IQueryable<Expense> expenses = _repository.GetExpenses(expenseGroupId);
         if (expenses == null)
         {
             return NotFound();
         }
         List<string> listOfFields = new List<string>();
         if (fields != null)
         {
             listOfFields = fields.Split(',').ToList();
         }
         if (pageSize > maxPageSize)
         {
             pageSize = maxPageSize;
         }
         int totalCount = expenses.Count();
         int totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
         UrlHelper urlHelper = new UrlHelper(Request);
         string prevLink = page > 1 ? urlHelper.Link("ExpensesForGroup",
             new
             {
                 page = page - 1,
                 pageSize = pageSize,
                 expenseGroupId = expenseGroupId,
                 sort = sort
             }) : "";
         var nextLink = page < totalPages ? urlHelper.Link("ExpensesForGroup",
             new
             {
                 page = page + 1,
                 pageSize = pageSize,
                 expenseGroupId = expenseGroupId,
                 sort = sort
             }) : "";
         var paginationHeader = new
         {
             currentPage = page,
             pageSize = pageSize,
             totalCount = totalCount,
             totalPages = totalPages,
             previousPageLink = prevLink,
             nextPageLink = nextLink
         };
         HttpContext.Current.Response.Headers.Add("X-Pagination", Newtonsoft.Json.JsonConvert.SerializeObject(paginationHeader));
         var expensesResult = expenses
             .ApplySort(sort)
             .Skip(pageSize * (page - 1))
             .Take(pageSize)
             .ToList()
             .Select(exp => _expenseFactory.CreateDataShapedObject(exp, listOfFields));
         return Ok(expensesResult);
     }
     catch (Exception exception)
     {
         return InternalServerError();
     }
 }
        public Object Get(int page = 0, int pageSize = 10)
        {
            IQueryable<Course> query;

            query = TheRepository.GetAllCourses().OrderBy(c => c.CourseSubject.Id);
            var totalCount = query.Count();
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

            var urlHelper = new UrlHelper(Request);
            var prevLink = page > 0 ? urlHelper.Link("Courses", new { page = page - 1, pageSize = pageSize }) : "";
            var nextLink = page < totalPages - 1 ? urlHelper.Link("Courses", new { page = page + 1, pageSize = pageSize }) : "";

            var results = query
                          .Skip(pageSize * page)
                          .Take(pageSize)
                          .ToList()
                          .Select(s => TheModelFactory.Create(s));

            return new
            {
                TotalCount = totalCount,
                TotalPages = totalPages,
                PrevPageLink = prevLink,
                NextPageLink = nextLink,
                Results = results
            };

        }
Exemplo n.º 6
0
        public object Get(int page , int pageSize)
        {
            IQueryable<Course> query;

            query = TheRepository.GetAllCourses().OrderBy(c => c.Name);

            var totalCount = query.Count();
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

            var urlHelper = new UrlHelper(Request);
            var prevLink = page > 0 ? urlHelper.Link("Courses", new { page = page - 1, pageSize = pageSize }) : "";
            var nextLink = page < totalPages - 1 ? urlHelper.Link("Courses", new { page = page + 1, pageSize = pageSize }) : "";

            var paginationHeader = new
            {
            TotalCount = totalCount,
            TotalPages = totalPages,
            PrevPageLink = prevLink,
            NextPageLink = nextLink
            };

            System.Web.HttpContext.Current.Response.Headers.Add("X-Pagination",
            Newtonsoft.Json.JsonConvert.SerializeObject(paginationHeader));

            var results = query
            .Skip(pageSize * page)
            .Take(pageSize)
            .ToList()
            .Select(s => TheModelFactory.Create(s));

            return results;
        }
        public void SetUp()
        {

            var config = new HttpConfiguration();
            var request = new HttpRequestMessage(HttpMethod.Post, "http://dragonapi.devjakobsen.dk/api/player");
            var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
            var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "player" } });


            playerController = new PlayerController();
            UrlHelper urlHelper = new UrlHelper(request);
            playerController.ControllerContext = new HttpControllerContext(config, routeData, request);
            playerController.Request = request;
            playerController.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            playerController.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
            playerController.Url = urlHelper;



            var response = teamController.Get(1);
            var contentResult = response as OkNegotiatedContentResult<DTOTeam>;
            DTOTeam DtoTeam = contentResult.Content;
            Team teamFromDb = new Team();
            teamFromDb.Name = DtoTeam.Name;
            teamFromDb.Id = DtoTeam.Id;
            List<Team> teams = new List<Team>() { teamFromDb };

            player = new Player() { Name = "Integration Test Player", Teams = teams };

        }
Exemplo n.º 8
0
        public PageLinkBuilder(UrlHelper urlHelper, string routeName, object routeValues, int pageNo, int pageSize, long totalRecordCount)
        {
            // Determine total number of pages
            var pageCount = totalRecordCount > 0
                ? (int) Math.Ceiling(totalRecordCount/(double) pageSize)
                : 0;

            // Create them page links
            FirstPage = new Uri(urlHelper.Link(routeName, new HttpRouteValueDictionary(routeValues)
            {
                {"pageNo", 1},
                {"pageSize", pageSize}
            }));
            LastPage = new Uri(urlHelper.Link(routeName, new HttpRouteValueDictionary(routeValues)
            {
                {"pageNo", pageCount},
                {"pageSize", pageSize}
            }));
            if (pageNo > 1)
            {
                PreviousPage = new Uri(urlHelper.Link(routeName, new HttpRouteValueDictionary(routeValues)
                {
                    {"pageNo", pageNo - 1},
                    {"pageSize", pageSize}
                }));
            }
            if (pageNo < pageCount)
            {
                NextPage = new Uri(urlHelper.Link(routeName, new HttpRouteValueDictionary(routeValues)
                {
                    {"pageNo", pageNo + 1},
                    {"pageSize", pageSize}
                }));
            }
        }
        public object Get(int userid,int notificationid = 0, int page = 0)
        {
            var userName = _identityService.CurrentUser;

            var baseQuery = TheRepository.GetOrganizationNotifications(userName)
                .OrderByDescending( c => c.DateAdded);

            var totalCount = baseQuery.Count();
            var totalPages = Math.Ceiling((double) totalCount/PAGE_SIZE);

            var helper = new UrlHelper(Request);
            var preUrl = page > 0 ? helper.Link("Notifications", new {page = page - 1}) : "";
            var newUrl = page < totalPages - 1 ? helper.Link("Notifications", new { page = page + 1 }): "";

            var results = baseQuery
                .Skip(PAGE_SIZE * page)
                .Take(PAGE_SIZE)
                .ToList()
                .Select(c => TheModelFactory.Create(c));

            return new
            {
                TotalCount = totalCount,
                TotalPages = totalPages,
                PrevPageUrl = preUrl,
                NextPageUrl = newUrl,
               Results = results,
            };
        }
Exemplo n.º 10
0
        public static OptionResponse ToResponse(this Option<Team> option, UrlHelper urlHelper = null)
        {
            var response = new OptionResponse
                {
                    CutOff = option.CutOff,
                    GameId = option.GameId,
                    GroupId = option.GroupId,
                    Id = option.Id,
                    IsPastCutOff = option.IsPastCutOff,
                    IsWinner = option.IsWinner,
                    Outcome = option.Outcome,
                    Team = option.Team,
                    Type = option.Type,
                    Value = option.Value
                };

            if (option.Pick != null && urlHelper != null)
            {
                response.Pick = option.Pick.ToResponse(urlHelper, response.IsPastCutOff);
            }

            if (urlHelper != null && !response.IsPastCutOff)
            {
                response.Actions.Add("pick", urlHelper.Route("DefaultNfl", new { controller = "picks", id = option.Id }));
            }

            return response;
        }
Exemplo n.º 11
0
        public IQueryable<EventDTO> GetAllPaging(int page, int pageSize)
        {
            var list = _service.GetAllPaging(page, pageSize);

            if (list != null)
            {
                var totalCount = _service.GetTotalResults();
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

                var urlHelper = new UrlHelper(Request);
                var prevLink = page > 1 ? urlHelper.Link("GetAllPagingRoute", new { page = page - 1, pageSize = pageSize }) : "";
                var nextLink = page < totalPages ? urlHelper.Link("GetAllPagingRoute", new { page = page + 1, pageSize = pageSize }) : "";
                var firstLink = page != 1 ? urlHelper.Link("GetAllPagingRoute", new { page = 1, pageSize = pageSize }) : "";
                var lastLink = page != totalPages ? urlHelper.Link("GetAllPagingRoute", new { page = totalPages, pageSize = pageSize }) : "";

                var paginationHeader = new
                {
                    TotalCount = totalCount,
                    TotalPages = totalPages,
                    PrevPageLink = prevLink,
                    NextPageLink = nextLink,
                    FirstPageLink = firstLink,
                    LastPageLink = lastLink
                };

                System.Web.HttpContext.Current.Response.Headers.Add("X-Pagination",
                    Newtonsoft.Json.JsonConvert.SerializeObject(paginationHeader));
            }

            return Queryable.AsQueryable(list);
        }
        public ODataFeedSerializerTests()
        {
            _model = SerializationTestsHelpers.SimpleCustomerOrderModel();
            _customerSet = _model.FindDeclaredEntityContainer("Default.Container").FindEntitySet("Customers");
            _customers = new[] {
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 10,
                },
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 42,
                }
            };

            _customersType = new EdmCollectionTypeReference(
                    new EdmCollectionType(
                        new EdmEntityTypeReference(
                            _customerSet.ElementType,
                            isNullable: false)),
                    isNullable: false);

            _urlHelper = new Mock<UrlHelper>(new HttpRequestMessage()).Object;
            _writeContext = new ODataSerializerWriteContext(new ODataResponseContext()) { EntitySet = _customerSet, UrlHelper = _urlHelper };
        }
Exemplo n.º 13
0
        public static GameResponse ToResponse(this Game game, UrlHelper urlHelper = null)
        {
            var response = new GameResponse
                {
                    AwayTeam = game.AwayTeam,
                    AwayTeamScore = game.AwayTeamScore,
                    GameTime = game.GameTime,
                    HomeTeam = game.HomeTeam,
                    HomeTeamScore = game.HomeTeamScore,
                    Id = game.Id,
                    IsGameOver = game.IsGameOver,
                    Season = game.Season,
                    SeasonType = game.SeasonType,
                    Week = game.Week,
                    WinningTeamId = game.WinningTeamId
                };

            if (game.Options != null)
            {
                response.Options = game.Options.ToResponse(urlHelper);

                if (urlHelper != null)
                {
                    var canModifyPicks = game.Options.Any(option => option.Pick != null && !option.IsPastCutOff);

                    if (canModifyPicks)
                    {
                        response.Actions.Add("deletePicks", urlHelper.Route("DeletePicksForGame", new { id = game.Id }));
                    }
                }
            }

            return response;
        }
Exemplo n.º 14
0
        public void SetUp()
        {

            var config = new HttpConfiguration();
            var request = new HttpRequestMessage(HttpMethod.Post, "http://dragonapi.devjakobsen.dk/api/game");
            var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
            var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "game" } });


            gameController = new GameController();
            UrlHelper urlHelper = new UrlHelper(request);
            gameController.ControllerContext = new HttpControllerContext(config, routeData, request);
            gameController.Request = request;
            gameController.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            gameController.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
            gameController.Url = urlHelper;
            genreController = new GenreController();
            var response = genreController.Get(1);
            var contentResult = response as OkNegotiatedContentResult<DTOGenre>;

            DTOGenre DtoGenre = contentResult.Content;
            genrefromDb = new Genre();
            genrefromDb.Name = DtoGenre.Name;
            genrefromDb.Id = DtoGenre.Id;
            game = new Game() { Name = "Integration Test Game", Genre = genrefromDb };
        }
        internal static EastFive.Api.Resources.Adapter GetResource(EastFive.Azure.Synchronization.Connection connection,
                                                                   System.Web.Http.Routing.UrlHelper url)
        {
            var adapter = connection.adapterInternal;

            return(GetResource(adapter, url));
        }
        //[EnableCors("*", "*", "GET")]
        public HttpResponseMessage Get(int page = 0, int pageSize = 10)
        {
            IQueryable<Course> query;

            Learning.Data.LearningContext ctx = new Learning.Data.LearningContext();

            Learning.Data.ILearningRepository repo = new Learning.Data.LearningRepository(ctx);

            query = repo.GetAllCourses().OrderBy(c => c.CourseSubject.Id);
            var totalCount = query.Count();
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

            var urlHelper = new UrlHelper(Request);
            var prevLink = page > 0 ? urlHelper.Link("CoursesRoute", new { page = page - 1, pageSize = pageSize }) : "";
            var nextLink = page < totalPages - 1 ? urlHelper.Link("CoursesRoute", new { page = page + 1, pageSize = pageSize }) : "";

            var results = query
                          .Skip(pageSize * page)
                          .Take(pageSize)
                          .ToList();

            var result = new
            {
                TotalCount = totalCount,
                TotalPages = totalPages,
                PrevPageLink = prevLink,
                NextPageLink = nextLink,
                Results = results
            };

            return Request.CreateResponse(HttpStatusCode.OK, result);

        }
        public void GenerateLinkDirectly_ReturnsNull_IfHelperRequestHasNoConfiguration()
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/vpath/prefix/Customers");
            UrlHelper urlHelper = new UrlHelper(request);

            Assert.Null(urlHelper.GenerateLinkDirectly("OData", "odataPath"));
        }
Exemplo n.º 18
0
        public HttpResponseMessage Get(int size, int page)
        {
            var helper = new UrlHelper(Request);
            if (size > 100) size = 10;
            int offset = page * size;
            int next_page = page;
            int prev_page = page;
            //need to count max pages from total results and implement that
            if (page < 1) { prev_page = 0; } else { prev_page--; }
            next_page++;

            var prev = helper.Link("QuestionApi", new { size = size, page = prev_page }).ToString();
            var next = helper.Link("QuestionApi", new { size = size, page = next_page });

            var response = Request
                .CreateResponse(
                HttpStatusCode.OK,
                _questionRepository
                .GetAllQuestions(size, offset)
                .Select(question => ModelFactory.Create(question)))
                ;
            response.Headers.Add("next-page", next);
            response.Headers.Add("prev-page", prev);
            return response;
        }
Exemplo n.º 19
0
        public IEnumerable<Product> Get(string sort = "ProductId", int page = 1, int pageSize = maxPageSize)
        {
            try
            {
                IProductDetailDao repository = new ProductDetailDao();

                var products= repository.GetAllProducts(sort);

                // ensure the page size isn't larger than the maximum.
                if (pageSize > maxPageSize)
                {
                    pageSize = maxPageSize;
                }

                // calculate data for metadata
                var totalCount = products.Count();
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

                var urlHelper = new UrlHelper(Request);
                var prevLink = page > 1 ? urlHelper.Link("ProductListing",
                    new
                    {
                        page = page - 1,
                        pageSize = pageSize,
                        sort = sort
                    }) : "";
                var nextLink = page < totalPages ? urlHelper.Link("ProductListing",
                    new
                    {
                        page = page + 1,
                        pageSize = pageSize,
                        sort = sort
                    }) : "";

                var paginationHeader = new
                {
                    currentPage = page,
                    pageSize = pageSize,
                    totalCount = totalCount,
                    totalPages = totalPages,
                    previousPageLink = prevLink,
                    nextPageLink = nextLink
                };

                HttpContext.Current.Response.Headers.Add("X-Pagination",
                   Newtonsoft.Json.JsonConvert.SerializeObject(paginationHeader));

                // return result
                return (products
                    .Skip(pageSize * (page - 1))
                    .Take(pageSize)
                    .ToList());

            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 20
0
 public LegacyTreeController(XmlTreeNode xmlTreeNode, string treeAlias, string currentSection, UrlHelper urlHelper)
 {
     _xmlTreeNode = xmlTreeNode;
     _treeAlias = treeAlias;
     _currentSection = currentSection;
     _rootDisplay = xmlTreeNode.Text;
     Url = urlHelper;
 }
Exemplo n.º 21
0
        private void Enrich(Car car, UrlHelper url) {

            string selfUrl = url.Link(
                Constants.DefaultHttpRoute, 
                new { controller = "cars", id = car.Id });

            car.AddLink(new SelfLink(selfUrl));
        }
Exemplo n.º 22
0
 public CreatedNegotiatedContentResult<IEnumerable<Figure>> GetCreatedNegotiatedContentResult()
 {
     UrlHelper helper = new UrlHelper(Request);
     IDictionary<string, object> route = new Dictionary<string, object>();
     route["controller"] = "Figure";
     route["action"] = "GetAll";
     return new CreatedNegotiatedContentResult<IEnumerable<Figure>>(new Uri(helper.Link("DefaultApi", route)), FigureManager.Figures, this);
 }
Exemplo n.º 23
0
        public object Get(bool includeReviews = true, int page = 1)
        {
            IQueryable<Restaurant> query;

            if (includeReviews)
            {
                query = Repository.GetAllRestaurantsWithReviewes();
            }
            else
            {
                query = Repository.GetAllRestaurants();
            }

            var baseQuery = query.OrderBy(r => r.Name);
            var totalCount = baseQuery.Count();
            var totalPages = (int)Math.Ceiling((double) totalCount/PAGE_SIZE);

            var helper = new UrlHelper(Request);

            var links = new List<LinkModel>();

            if (page > 1)
                links.Add(ModelFactory.CreateLink(helper.Link("restaurants", new { page = page - 1 }), "prevPage"));

            if (page < totalPages)
                links.Add(ModelFactory.CreateLink(helper.Link("restaurants", new { page = page + 1 }), "nextPage"));

            /*
            var prevUrl = page > 1 ? helper.Link("restaurants", new { includeReviews = includeReviews, page = page - 1 }) : "";

            var nextUrl = page < totalPages ? helper.Link("restaurants", new { includeReviews = includeReviews, page = page + 1 }) : "";
            */

            var results = baseQuery
                .Skip(PAGE_SIZE*(page - 1))
                .Take(PAGE_SIZE)
                .ToList()
                .Select(r => ModelFactory.Create(r));

            return new
            {
                TotalCount = totalCount,
                TotalPages = totalPages,
                Links   = links,
                Results = results,
            };

            /*
            return new
                {
                    TotalCount = totalCount,
                    TotalPages = totalPages,
                    PrevPageUrl = prevUrl.ToLower(),
                    NextPageUrl = nextUrl.ToLower(),
                    Results = results,
                };
            */
        }
Exemplo n.º 24
0
        public static GamesResponse ToResponse(this IEnumerable<Game> games, UrlHelper urlHelper = null)
        {
            var response = new GamesResponse
                {
                    Games = games.Select(game => game.ToResponse(urlHelper)).OrderBy(game => game.GameTime).ToList()
                };

            return response;
        }
        /// <summary>
        /// Gets the list of links for salutations for entry.
        /// </summary>
        /// <param name="urlHelper">Url helper</param>
        /// <returns>Returns the list of <see cref="Link" /> objects.</returns>
        public static IEnumerable<Link> FindLinks(UrlHelper urlHelper)
        {
            var links = new List<Link>()
                            {
                                new Link() { Rel = "salutations", Href = urlHelper.Route(SalutationsRouteName, new { }) },
                            };

            return links;
        }
        public void BuildsAbsoluteUriToPackageDownload()
        {
            var result = serializer.BuildLinkForStreamProperty(new ODataPackage { Id = "Sample", Version = "1.0" }, context);

            Assert.That(result.IsAbsoluteUri, Is.True, "IsAbsoluteUri");

            var expected = new UrlHelper(request).Link(RouteNames.Packages.Download, new { Id = "Sample", Version = "1.0" });
            Assert.That(result.GetComponents(UriComponents.AbsoluteUri, UriFormat.SafeUnescaped), Is.EqualTo(expected));
        }
Exemplo n.º 27
0
 public QuestionModel(UrlHelper urlHelper, Question question)
 {
     Url = urlHelper.Link("questions", new { id = question.Id});
     Id = question.Id;
     QuestionText = question.QuestionText;
     QuestionCategoryId = question.CategoryId;
     ImageBytes = question.Image;
     IsDeprecated = question.Deprecated;
 }
Exemplo n.º 28
0
 protected virtual Uri GetRedirectUri(HttpRequestMessage request)
 {
     var url = new UrlHelper(request).Link(routeName, routeValues);
     if (AppendTrailingSlash && !url.EndsWith("/"))
     {
         url = url + "/";
     }
     return new Uri(url);
 }
Exemplo n.º 29
0
 public HttpResponseMessage Post([FromBody] VoteModel model )
 {
     var helper = new UrlHelper(Request);
     var vote = ModelFactory.Parse(model);
     _votesRepository.Insert(vote);
     return Request.CreateResponse(
         HttpStatusCode.Created
         , ModelFactory.Create(vote));
 }
Exemplo n.º 30
0
 public HttpResponseMessage Post([FromBody] PostModel model)
 {
     var helper = new UrlHelper(Request);
     var post = ModelFactory.Parse(model);
     _postRepository.Add(post);
     return Request.CreateResponse(
         HttpStatusCode.Created
         , ModelFactory.Create(post));
 }
        public void GenerateLinkDirectly_ReturnsNull_IfRouteTemplateHasParameterInPrefix()
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/vpath/prefix/Customers");
            HttpConfiguration config = new HttpConfiguration(new HttpRouteCollection("http://localhost/vpath"));
            config.Routes.MapHttpRoute("OData", "{prefix}/{*odataPath}");
            request.SetConfiguration(config);
            UrlHelper urlHelper = new UrlHelper(request);

            Assert.Null(urlHelper.GenerateLinkDirectly("OData", "odataPath"));
        }
Exemplo n.º 32
0
        internal static EastFive.Api.Resources.Connection GetResource(Connection connection,
                                                                      System.Web.Http.Routing.UrlHelper url)
        {
            var resource = new EastFive.Api.Resources.Connection()
            {
                Id          = url.GetWebId <ConnectionController>(connection.connector.connectorId),
                Connector   = ConnectorController.GetResource(connection.connector, url),
                Source      = AdapterController.GetResource(connection.adapterInternal, url),
                Destination = AdapterController.GetResource(connection.adapterExternal, url),
            };

            return(resource);
        }
        internal static EastFive.Api.Resources.Connector GetResource(Connector connector,
                                                                     System.Web.Http.Routing.UrlHelper url)
        {
            var resource = new EastFive.Api.Resources.Connector()
            {
                Id   = url.GetWebId <ConnectorController>(connector.connectorId),
                Flow = Enum.GetName(typeof(Connector.SynchronizationMethod), connector.synchronizationMethod),

                Source      = url.GetWebId <Controllers.AdapterController>(connector.adapterInternalId),
                Destination = url.GetWebId <Controllers.AdapterController>(connector.adapterExternalId),
            };

            return(resource);
        }
        internal static EastFive.Api.Resources.Adapter GetResource(EastFive.Azure.Synchronization.Adapter adapter,
                                                                   System.Web.Http.Routing.UrlHelper url)
        {
            var resource = new EastFive.Api.Resources.Adapter()
            {
                Id           = url.GetWebId <AdapterController>(adapter.adapterId),
                ResourceType = adapter.resourceType,

                //ResourceId = ServiceConfiguration.ResourceControllerLookup(adapter.resourceType,
                //    controllerType => url.GetWebId(controllerType, adapter.key),
                //    () => default(BlackBarLabs.Api.Resources.WebId)),
                ResourceKey = adapter.key,
                Name        = adapter.name,
                Keys        = adapter.identifiers.NullToEmpty().SelectKeys().ToArray(),
                Values      = adapter.identifiers.NullToEmpty().SelectValues().ToArray(),
                Integration = url.GetWebId <IntegrationController>(adapter.integrationId),
                Connectors  = adapter.connectorIds.NullToEmpty().Select(connectionId => url.GetWebId <ConnectorController>(connectionId)).ToArray(),
            };

            return(resource);
        }
Exemplo n.º 35
0
 public ModelFactory(HttpRequestMessage request, ILearningRepository repo)
 {
     _urlHelper = new UrlHelper(request);
     _repo      = repo;
 }
Exemplo n.º 36
0
 public ModelFactory(HttpRequestMessage request)
 {
     _UrlHelper = new System.Web.Http.Routing.UrlHelper(request);
 }
Exemplo n.º 37
0
 public ModelFactory(System.Net.Http.HttpRequestMessage request, ApplicationUserManager appUserManager)
 {
     _UrlHelper      = new System.Web.Http.Routing.UrlHelper(request);
     _AppUserManager = appUserManager;
 }
        internal static Attempt <MenuItemCollection> TryGetMenuFromLegacyTreeNode(this ApplicationTree appTree, string parentId, string nodeId, FormDataCollection formCollection, UrlHelper urlHelper)
        {
            var xTreeAttempt = appTree.TryGetXmlTree(parentId, formCollection);

            if (xTreeAttempt.Success == false)
            {
                return(Attempt <MenuItemCollection> .Fail(xTreeAttempt.Exception));
            }

            var currentSection = formCollection.GetRequiredString("section");

            var result = LegacyTreeDataConverter.ConvertFromLegacyMenu(nodeId, xTreeAttempt.Result, currentSection);

            if (result == null)
            {
                return(Attempt <MenuItemCollection> .Fail(new ApplicationException("Could not find the node with id " + nodeId + " in the collection of nodes contained with parent id " + parentId)));
            }
            return(Attempt.Succeed(result));
        }
        internal static Attempt <MenuItemCollection> TryGetMenuFromLegacyTreeRootNode(this ApplicationTree appTree, FormDataCollection formCollection, UrlHelper urlHelper)
        {
            var rootAttempt = appTree.TryGetRootXmlNodeFromLegacyTree(formCollection, urlHelper);

            if (rootAttempt.Success == false)
            {
                return(Attempt <MenuItemCollection> .Fail(rootAttempt.Exception));
            }

            var currentSection = formCollection.GetRequiredString("section");

            var result = LegacyTreeDataConverter.ConvertFromLegacyMenu(rootAttempt.Result, currentSection);

            return(Attempt.Succeed(result));
        }
        internal static Attempt <TreeNodeCollection> TryLoadFromLegacyTree(this ApplicationTree appTree, string id, FormDataCollection formCollection, UrlHelper urlHelper, string currentSection)
        {
            var xTreeAttempt = appTree.TryGetXmlTree(id, formCollection);

            if (xTreeAttempt.Success == false)
            {
                return(Attempt <TreeNodeCollection> .Fail(xTreeAttempt.Exception));
            }
            return(Attempt.Succeed(LegacyTreeDataConverter.ConvertFromLegacy(id, xTreeAttempt.Result, urlHelper, currentSection, formCollection)));
        }
        internal static Attempt <XmlTreeNode> TryGetRootXmlNodeFromLegacyTree(this ApplicationTree appTree, FormDataCollection formCollection, UrlHelper urlHelper)
        {
            var treeDefAttempt = appTree.TryGetLegacyTreeDef();

            if (treeDefAttempt.Success == false)
            {
                return(Attempt <XmlTreeNode> .Fail(treeDefAttempt.Exception));
            }
            var treeDef    = treeDefAttempt.Result;
            var bTree      = treeDef.CreateInstance();
            var treeParams = new LegacyTreeParams(formCollection);

            bTree.SetTreeParameters(treeParams);

            var xmlRoot = bTree.RootNode;

            return(Attempt.Succeed(xmlRoot));
        }
        internal static Attempt <TreeNode> TryGetRootNodeFromLegacyTree(this ApplicationTree appTree, FormDataCollection formCollection, UrlHelper urlHelper, string currentSection)
        {
            var xmlTreeNodeAttempt = TryGetRootXmlNodeFromLegacyTree(appTree, formCollection, urlHelper);

            if (xmlTreeNodeAttempt.Success == false)
            {
                return(Attempt <TreeNode> .Fail(xmlTreeNodeAttempt.Exception));
            }

            //the root can potentially be null, in that case we'll just return a null success which means it won't be included
            if (xmlTreeNodeAttempt.Result == null)
            {
                return(Attempt <TreeNode> .Succeed(null));
            }

            var legacyController = new LegacyTreeController(xmlTreeNodeAttempt.Result, appTree.Alias, currentSection, urlHelper);
            var newRoot          = legacyController.GetRootNode(formCollection);

            return(Attempt.Succeed(newRoot));
        }