Link class augments the base LinkAttributes class with abilities to: - create HttpRequestMessage - attach link hints - attach response handling behaviour - support for URI templates This class can be subclassed with attributes and behaviour that is specific to a particular link relation
Inheritance: LinkAttributes, IRequestFactory
示例#1
0
        public void UseAllowHintToSetRequestMethodOnLink()
        {
            // Arrange
            var hint = new AllowHint();
            hint.AddMethod(HttpMethod.Post);
            hint.ConfigureRequest = (h, r) =>
                {
                    // Really not sure if this is a good idea to allow hints to actually change the request.
                    // Should they just validate the current request?
                    // How do we know if someone has explicitly set link.method or if it is just a default Get.
                    var allowHint = ((AllowHint)h);
                    if ( !allowHint.Methods.Contains(r.Method))
                    {
                        r.Method = allowHint.Methods.First();
                    }
                    return r;
                };

            var link = new Link();
            link.AddHint(hint);
            
            // Act
            var request = link.CreateRequest();

            //Asset
            Assert.Equal(HttpMethod.Post,request.Method);            

        }
        //[Fact]
        public void UploadFileToSkyDrive()
        {

            ServicePointManager.Expect100Continue = false;
            
            var content = new StreamContent(new FileStream("C:\\Users\\Darrel\\Pictures\\868.jpg",FileMode.Open));

            var link = new Link {
                Template = new UriTemplate("https://apis.live.net/v5.0/me/skydrive/files/{filename}{?access_token}"), 
            };

            link.Template.AddParameters(new 
            {
                access_token = "EwAwAq1DBAAUGCCXc8wU/zFu9QnLdZXy+YnElFkAAS/+qh/DHgp3W+UIGoihj9+udq6NrLD+s8hQ51NxPcii0QKiV0Vcd/n8w01XHFxpqboQblkhywILJ+CgOdsg0e8UgzPPjt4pmhWoRShFaGrANtUHzzfxmonXTZ8QGPBU9wGmqmfBpEe1KH51q/UiAEGP4t/twPyu3m68Q8ANh0FBlORNmQXAmkIhImuEHbQm+K5Xfi0EoZ2bLdimY1OwCQnUgSlVPj4raodooGOH0ZlkyUrd3VfH0Jwc90HkiOLfxWvspaA/px5NDLwBxb8Xo1B6Y7VMhA6poaPn1jf+y2sfFi0I7ToklBb+n7GTQJ9EiWfxf0mDX2hj1PbvLsYffGkDZgAACKqqGYH2n911AAHEORFJ5DYFe4zF1V4lcljDsWvil0CWOmbOsCsWMHGCs29qFIu/ZJzkAHYZk7Lg5meFsnQVdAnEWO2j7NEJJuI118VuBNasJfkV208nq4K/B5K/QrM/ZxqYG9IjMHnGbpcZSisKT8TkPK4z7yvR6f+ap6Zx9cGLjwS0WajHGCBjyiNPDV7UoP3Rmnr1fzwivdplydgQg9aE4BV9hYn/2nBX3e6c0OfFDFQzinJukJesc/2zgYf4tR9b8L4qmtXDYCp0d7akVxmzdXFb/b71gLZmHFHCrPSv8t4f0NIllKhCBhiFyitOGu3iBRpSy6jPgkaSp2NwBu/WICrgae1wEITrAAA=",
                filename = "868.jpg"}
            );

            link.Method = HttpMethod.Put;
            link.Content = content;

            var req = link.CreateRequest();            

            var client = new HttpClient();

            var response = client.SendAsync(req).Result;

            var body = response.Content.ReadAsStringAsync().Result;

        }
示例#3
0
         private static ShellModel CreateMazeModel(CompositionContainer container) {
             EscapeMaze escapeMaze = CreateEscapeMazeMission();

             var mazeLink = new Link() {Target = new Uri("http://amundsen.com/examples/mazes/2d/five-by-five/")};
             

             var restAgent = new RestAgent();
			 MazeSemanticsProvider.RegisterSemantics(restAgent.SemanticsRegistry);
             restAgent.SemanticsRegistry.RegisterFormatter(new XmlFormatter("application/vnd.amundsen.maze+xml"));
             
             restAgent.SemanticsRegistry.RegisterFormatter(new HtmlFormatter());
             restAgent.SemanticsRegistry.RegisterLinkExtractor(new HtmlLinkExtractor());

             //restAgent.SetAcceptedMediaTypes(new List<MediaTypeWithQualityHeaderValue>(){ new MediaTypeWithQualityHeaderValue("application/vnd.amundsen.maze+xml")});
             restAgent.SetAcceptedMediaTypes(new List<MediaTypeWithQualityHeaderValue>() { new MediaTypeWithQualityHeaderValue("text/html") });

             restAgent.NavigateTo(mazeLink);
           

             return new ShellModel {
                                       Container = container,
                                       DefaultMission = escapeMaze,
                                       RestAgent = restAgent
                                   };
         }
示例#4
0
        public void DefaultLinkShouldCreateAGetRequest()
        {
            var link = new Link() { Target = new Uri("Http://localhost") };

            var request = link.CreateRequest();

            Assert.Equal(HttpMethod.Get,request.Method);
        }
示例#5
0
        public void UseURITemplateAsLinkSource()
        {
            var link = new Link { Target = new Uri("Http://localhost") }; 
            var client = new HttpClient(new FakeMessageHandler());

            var response = client.SendAsync(link.CreateRequest()).Result;

            Assert.Equal("http://localhost/", response.RequestMessage.RequestUri.AbsoluteUri);
        }
示例#6
0
        public void UseLinkToMakeRequest()
        {
            var link = new Link { Target = new Uri("Http://localhost") };
            var client = new HttpClient(new FakeMessageHandler());

            var response = client.SendAsync(link.CreateRequest()).Result;

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
        public override void HandleResponseStart(Link link, HttpResponseMessage response)
        {

            _model.CurrentMediaType = response.Content.Headers.ContentType.MediaType;

            _model.CurrentLocation = link;

            _model.FireOnContentChanging();
        }
示例#8
0
        public void CreateEmptyLink()
        {
            //Arrange

            //Act
            var link = new Link();

            //Assert
            Assert.IsNotNull(link);
        }
示例#9
0
        public void AddParameterToLinkMultipleTimes()
        {
            var link = new Link() { Target = new Uri("http://localhost/{?foo}") };
            link.SetParameter("foo", "bar");
            link.SetParameter("foo", "blah");

            var request = link.CreateRequest();

            Assert.Equal("http://localhost/?foo=blah", request.RequestUri.AbsoluteUri);
        }
示例#10
0
        public Task Test()
        {
            var link = new Link(){Target = new Uri("http://localhost")};

            link.HttpResponseHandler = new NotFoundHandler(new OkHandler(null));

            var client = new HttpClient(new FakeHandler() {Response = new HttpResponseMessage() {StatusCode = HttpStatusCode.NotFound}});

            return client.FollowLinkAsync(link);
        }
示例#11
0
        public void AddParameterToLink()
        {
            var link = new Link(){ Target = new Uri("http://localhost/{?foo}")};
            link.SetParameter("foo","bar");

            var client = new HttpClient(new FakeMessageHandler());

            var response = client.SendAsync(link.CreateRequest()).Result;

            Assert.Equal("http://localhost/?foo=bar", response.RequestMessage.RequestUri.AbsoluteUri);
        }
示例#12
0
        public void InitializeLinkWithString()
        {
            //Arrange

            //Act

            var link = new Link() { Target = new Uri("http://example.org/")};

            //Assert
            Assert.AreEqual(link.Target.ToString(), "http://example.org/");
        }
        public virtual Task<HttpResponseMessage> HandleAsync(Link link, HttpResponseMessage responseMessage)
        {
            if (InnerResponseHandler != null)
            {
                return InnerResponseHandler.HandleAsync(link, responseMessage);
            }

            var tcs = new TaskCompletionSource<HttpResponseMessage>();
            tcs.SetResult(responseMessage);
            return tcs.Task;
        }
示例#14
0
        public void AddMultipleParametersToLink()
        {
            var link = new Link() { Target = new Uri("http://localhost/api/{dataset}/customer{?foo,bar,baz}") };
            link.SetParameter("foo", "bar");
            link.SetParameter("baz", "99");
            link.SetParameter("dataset", "bob");

            var uri = link.GetResolvedTarget();

            Assert.Equal("http://localhost/api/bob/customer?foo=bar&baz=99", uri.AbsoluteUri);
        }
示例#15
0
        public void AddParameter()
        {
            //Arrange
            var link = new Link() { Target = new Uri("http://localtmserver:8700/api/locweldlocal/Assemblies?RootAssembly=true{&workorder}") };

            //Act
            link.SetParameter("workorder","W1542");

            var req = link.CreateRequest();
            //Assert
            Assert.AreEqual("http://localtmserver:8700/api/locweldlocal/Assemblies?RootAssembly=true&workorder=W1542".ToLowerInvariant(), req.RequestUri.ToString().ToLowerInvariant());
        }
 public static Task<HttpResponseMessage> FollowLinkAsync(this HttpClient httpClient, Link link)
 {
     return httpClient.SendAsync(link.CreateRequest())
         .ContinueWith(t =>
         {
             if (t.IsCompleted && link.HttpResponseHandler != null)
             {
                 return link.HandleResponseAsync(t.Result);
             }
             return t; 
         }).Unwrap();
 }
示例#17
0
        public void Add_no_parameters_to_uri()
        {
            var link = new Link()
            {
                Target = new Uri("http://example/customer")
            };

            link.AddParametersAsTemplate();

            var resolvedTarget = link.GetResolvedTarget().OriginalString;
            Assert.Equal("http://example/customer", resolvedTarget);
        }
示例#18
0
        public void SettingContentShouldBePassedToTheRequest()
        {
            var link = new Link
            {
                Target = new Uri("Http://localhost"),
                Method = HttpMethod.Post,
                Content = new StringContent("Hello World")
            };

            var request = link.CreateRequest();

            Assert.Equal(request.Content.ReadAsStringAsync().Result, "Hello World");
        }
        public async Task Test()
        {
            var link = new Link(){Target = new Uri("http://localhost")};

            var notFoundHandler = new NotFoundHandler(new OkHandler(null));
            var machine = new HttpResponseMachine();
            machine.AddResponseHandler(notFoundHandler.HandleResponseAsync, HttpStatusCode.NotFound);

            var client = new HttpClient(new FakeHandler() {Response = new HttpResponseMessage() {StatusCode = HttpStatusCode.NotFound}});

            await client.FollowLinkAsync(link,machine);

            Assert.True(notFoundHandler.NotFound);
        }
示例#20
0
        private static ShellModel CreateTestServerModel(CompositionContainer container)
        {
            var rootLink = new Link() {Target = new Uri("http://graphite:9000")};


            var restAgent = new RestAgent();
            restAgent.NavigateTo(rootLink);


            return new ShellModel {
                Container = container,
                RestAgent = restAgent
            };
        }
示例#21
0
 public override Task<HttpResponseMessage> HandleAsync(Link link, HttpResponseMessage responseMessage)
 {
     if (responseMessage.StatusCode == HttpStatusCode.OK)
     {
         Console.WriteLine("OK!");
         var tcs = new TaskCompletionSource<HttpResponseMessage>();
         tcs.SetResult(responseMessage);
         return tcs.Task;
     }
     else
     {
         return base.HandleAsync(link, responseMessage);
     }
 }
示例#22
0
        public void Add_parameters_to_uri_with_query_string()
        {
            var link = new Link()
            {
                Target = new Uri("http://example/customer?view=true")
            };

            link.SetParameter("id", 99);

            link.AddParametersAsTemplate();

            var resolvedTarget = link.GetResolvedTarget().OriginalString;
            Assert.Equal("http://example/customer?view=true&id=99", resolvedTarget);
        }
示例#23
0
        public void Add_multiple_parameters_to_uri()
        {
            var link = new Link()
            {
                Target = new Uri("http://example/customer")
            };

            link.SetParameter("id", 99);
            link.SetParameter("view", false);

            link.AddParametersAsTemplate();

            var resolvedTarget = link.GetResolvedTarget().OriginalString;
            Assert.Equal("http://example/customer?id=99&view=False", resolvedTarget);
        }
        public async Task FollowAndApplyInDistinctSteps()
        {
            var link = new Link() {Target = new Uri("http://example.org/")};

            var client = new HttpClient(new FakeHandler() { Response = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.NotFound
            } });
            
            var clientState = new ClientApplicationState();

            await client.FollowLinkAsync(link)
                        .ApplyRepresentationToAsync(clientState);

            Assert.Equal(HttpStatusCode.NotFound, clientState.StatusCode);
        }
示例#25
0
        static void Main(string[] args) {

            
            var restagent = new RestAgent();
            MazeSemanticsProvider.RegisterSemantics(restagent.SemanticsRegistry);
			restagent.SetAcceptedMediaTypes( new[] { new MediaTypeWithQualityHeaderValue("application/vnd.amundsen.maze+xml") });

            var link = new Link() {Target = new Uri("http://amundsen.com/examples/mazes/2d/five-by-five/")};
            
            restagent.NavigateTo(link);

            var startlink = restagent.CurrentContent.GetLink<StartLink>();
            restagent.NavigateTo(startlink);

            // Pick first available door
            var firstlink = (from lk in restagent.CurrentContent.GetLinks() where !(lk is CurrentLink || lk is StartLink) select lk).First();
            restagent.NavigateTo((Link)firstlink);

            var linkfrom = firstlink;

            while (restagent.CurrentContent.GetLink<ExitLink>() == null) {

                Link chosenLink = null;
                var availablelinks = (from lk in restagent.CurrentContent.GetLinks() select lk).ToDictionary(lk => lk.Relation);

                switch(linkfrom.Relation) {
                    case "east":
                        chosenLink = ChooseDoor(availablelinks, "south", "east", "north", "west");
                        break;
                    case "west":
                        chosenLink = ChooseDoor(availablelinks, "north", "west", "south", "east");
                        break;
                    case "south":
                        chosenLink = ChooseDoor(availablelinks, "west", "south", "east", "north");
                        break;
                    case "north":
                        chosenLink = ChooseDoor(availablelinks, "east", "north", "west", "south");
                        break;

                }
                Console.WriteLine("Going : " + chosenLink.Relation);
                restagent.NavigateTo((Link)chosenLink);
                linkfrom = chosenLink;
            }
            Console.WriteLine("Complete"); 
            Console.ReadLine();
        }
示例#26
0
        public HttpResponseMessage Get(HttpRequestMessage requestMessage)
        {
            var homeDocument = new HomeDocument();


            var fooLink = new Link()
                {
                    Relation = "http://example.org/rels/foo", 
                    Target = new Uri("foo", UriKind.Relative)
                };
            var allowHint = new AllowHint();
            allowHint.AddMethod(HttpMethod.Get);
            allowHint.AddMethod(HttpMethod.Post);
            fooLink.AddHint(allowHint);
            homeDocument.AddResource(fooLink);


            var barLink = new Link()
            {
                Relation = "http://example.org/rels/bar",
                Target = new Uri("bar", UriKind.Relative)
            };
            var allowHint2 = new AllowHint();
            allowHint2.AddMethod(HttpMethod.Get);
            barLink.AddHint(allowHint2);
            homeDocument.AddResource(barLink);


            var bar2Link = new Link()
            {
                Relation = "http://example.org/rels/bar2",
                Target = new Uri("bar/{id}", UriKind.Relative)
            };
         //   bar2Link.SetParameter("id","",new Uri("template/params/id", UriKind.Relative));
            homeDocument.AddResource(bar2Link);


            var ms = new MemoryStream();
            homeDocument.Save(ms);
            ms.Position = 0;
            var streamContent = new StreamContent(ms);
            return new HttpResponseMessage()
                {
                    Content = streamContent
                };
        }
 private static Dictionary<string, ParameterInfo> GetBindingProperties(Link link)
 {
     var props = link.GetType()
         .GetTypeInfo()
         .DeclaredProperties 
         .Select(p => new ParameterInfo()
         {
             PropertyInfo = p,
             Attribute =  p.GetCustomAttributes<LinkParameterAttribute>()
             .FirstOrDefault()
         })
         .ToDictionary(pi =>
         {
             return pi.Attribute == null ? pi.PropertyInfo.Name.ToLowerInvariant() : pi.Attribute.Name;
         }, pr => pr);
     return props;
 }
示例#28
0
        public void SettingAnAcceptHeaderShouldBePassedToTheRequest()
        {
            var link = new Link
            {
                Target = new Uri("Http://localhost"),
                
            };
            link.AddRequestBuilder(new InlineRequestBuilder((r) =>
            {
                r.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.hal"));
                r.Headers.UserAgent.Add(new ProductInfoHeaderValue("foo", "1.1"));
                return r;
            }));


            var request = link.CreateRequest();

            Assert.True(request.Headers.Accept.Any(h => h.MediaType == "application/vnd.hal"));
        }
        public ApiHomeController()
        {
            Document = new HomeDocument();

            // Series
            var series = new Link()
            {
                Relation = Relations.SERIES_SINGLE,                
                Target = new Uri("series/{id}", UriKind.Relative)
            };
            series.SetParameter("id", "", Parameters.SERIES_ID);

            var allowedMethods = new AllowHint();
            allowedMethods.AddMethod(HttpMethod.Get);
            allowedMethods.AddMethod(HttpMethod.Post);
            series.AddHint(allowedMethods);

            Document.AddResource(series);
        }
示例#30
0
        public void SpecifyHandlerForAllowhint()
        {
            var foo = false;

            var registry = new HintFactory();
            registry.SetHandler<AllowHint>((h, r) =>
                { foo = true;
                    return r;
                });

            var hint = registry.CreateHint<AllowHint>();

            var link = new Link();
            link.AddHint(hint);

            // Act
            var request = link.CreateRequest();

            Assert.Equal(foo,true);
        }