Exemplo n.º 1
0
        public void ParseGoToBranchLinkWithHash()
        {
            string expected = "gitext://gotobranch/PR#23";
            string actual   = LinkFactory.ParseLink("PR#23#gitext://gotobranch/PR#23");

            Assert.That(actual, Is.EqualTo(expected));
        }
Exemplo n.º 2
0
        public Task SpecifyHandlerChainForAboutLink()
        {
            var foo = false;
            var bar = false;
            var baz = false;

            var registry = new LinkFactory();
            var grh      = new InlineResponseHandler((rel, hrm) => baz = true,
                                                     new InlineResponseHandler((rel, hrm) => foo = true,
                                                                               new InlineResponseHandler((rel, hrm) => bar = true)));

            var machine = new HttpResponseMachine();

            machine.AddResponseHandler(grh.HandleResponseAsync, System.Net.HttpStatusCode.OK);


            var link = registry.CreateLink <AboutLink>();

            link.Target = new Uri("http://example.org");
            var httpClient = new HttpClient(new FakeHandler()
            {
                Response = new HttpResponseMessage()
            });

            return(httpClient.FollowLinkAsync(link, machine).ContinueWith(t =>
            {
                Assert.True(foo);
                Assert.True(bar);
                Assert.True(baz);
            }));
        }
        public Task SpecifyHandlerChainForAboutLink()
        {
            var foo = false;
            var bar = false;
            var baz = false;
  
            var registry = new LinkFactory();
            var grh = new InlineResponseHandler((rel,hrm) => baz = true,
                new InlineResponseHandler((rel, hrm) => foo = true,
                    new InlineResponseHandler((rel, hrm) => bar = true)));

            var machine = new HttpResponseMachine();
            machine.AddResponseHandler(grh.HandleResponseAsync, System.Net.HttpStatusCode.OK);
            

            var link = registry.CreateLink<AboutLink>();
            link.Target = new Uri("http://example.org");
            var httpClient = new HttpClient(new FakeHandler() { Response = new HttpResponseMessage()});

            return httpClient.FollowLinkAsync(link,machine).ContinueWith(t =>
                {
                    Assert.True(foo);
                    Assert.True(bar);
                    Assert.True(baz);
                });

        }
Exemplo n.º 4
0
        public void ParseMailTo()
        {
            string expected = "mailto:[email protected]";
            string actual   = LinkFactory.ParseLink("Janusz Białobrzewski <*****@*****.**>#mailto:[email protected]");

            Assert.That(actual, Is.EqualTo(expected));
        }
Exemplo n.º 5
0
        public void ParseInvalidLink(string link)
        {
            var linkFactory = new LinkFactory();

            Assert.False(linkFactory.ParseLink(link, out var actualUri));
            Assert.That(actualUri, Is.Null);
        }
Exemplo n.º 6
0
        public void ParseLinkHeaders3()
        {
            var linkRegistry = new LinkFactory();
            var response     = new HttpResponseMessage();

            response.RequestMessage = new HttpRequestMessage()
            {
                RequestUri = new Uri("http://example.org/")
            };
            var list = new List <ILink>()
            {
                new AboutLink()
                {
                    Target = new Uri("http://example.org/about")
                },
                new HelpLink()
                {
                    Target = new Uri("http://example.org/help")
                }
            };

            response.Headers.AddLinkHeaders(list);

            var links = response.ParseLinkHeaders(linkRegistry);

            Assert.NotNull(links.Where(l => l is AboutLink).FirstOrDefault());
            Assert.NotNull(links.Where(l => l is HelpLink).FirstOrDefault());
        }
Exemplo n.º 7
0
        private static HomeDocument Parse(JObject jObject, LinkFactory linkFactory = null)
        {
            if (linkFactory == null)
            {
                linkFactory = new LinkFactory();
            }


            var doc       = new HomeDocument();
            var resources = jObject["resources"] as JObject;

            if (resources != null)
            {
                foreach (var resourceProp in resources.Properties())
                {
                    var link = linkFactory.CreateLink(resourceProp.Name);

                    var resource = resourceProp.Value as JObject;

                    var hrefProp = resource.Property("href");
                    if (hrefProp != null)
                    {
                        link.Target = new Uri(hrefProp.Value.Value <string>(), UriKind.RelativeOrAbsolute);
                    }
                    else
                    {
                        link.Target = new Uri((String)resource["href-template"], UriKind.RelativeOrAbsolute);
                        var hrefvars = resource.Value <JObject>("href-vars");
                        foreach (var hrefvar in hrefvars.Properties())
                        {
                            var hrefUri = (string)hrefvar;
                            if (string.IsNullOrEmpty(hrefUri))
                            {
                                link.SetParameter(hrefvar.Name, null);
                            }
                            else
                            {
                                link.SetParameter(hrefvar.Name, null, new Uri(hrefUri, UriKind.RelativeOrAbsolute));
                            }
                        }
                    }

                    var hintsProp = resource.Property("hints");
                    if (hintsProp != null)
                    {
                        var hintsObject = hintsProp.Value as JObject;
                        foreach (var hintProp in hintsObject.Properties())
                        {
                            var hint = linkFactory.HintFactory.CreateHint(hintProp.Name);
                            hint.Content = hintProp.Value;
                            link.AddHint(hint);
                        }
                    }

                    doc.AddResource(link);
                }
            }

            return(doc);
        }
Exemplo n.º 8
0
        private async void Window_Opened(object sender, EventArgs e)
        {
            this.AddHandler(Button.ClickEvent, Button_Click);

            async Task <IClient> CreateClient()
            {
                var exists       = File.Exists(SettingsPath);
                var settingsFile = exists ? Some(SettingsPath) : None <string>();
                var storage      = new SqliteStorage($"{nameof(Chatter)}.db");
                var dispatcher   = new SynchronizationDispatcher(Dispatcher.UIThread);
                var result       = await TryAsync(() => LinkFactory.CreateClientAsync(dispatcher, storage, settingsFile)).NoticeOnErrorAsync();

                var client = result.UnwrapOrDefault();

                if (exists == false && client != null)
                {
                    client.Profile.Name = $"{Environment.UserName}@{Environment.MachineName}";
                }
                if (result.IsError())
                {
                    this.Close();
                }
                return(client);
            }

            this.IsEnabled = false;
            using var _0   = Disposable.Create(() => this.IsEnabled = true);

            client = App.CurrentClient ?? await CreateClient();

            DataContext = client?.Profile;
        }
Exemplo n.º 9
0
        private string GetBranchesWhichContainsThisCommit(string revision, bool showBranchesAsLinks)
        {
            const string remotesPrefix = "remotes/";
            // Include local branches if explicitly requested or when needed to decide whether to show remotes
            bool getLocal = Settings.CommitInfoShowContainedInBranchesLocal ||
                            Settings.CommitInfoShowContainedInBranchesRemoteIfNoLocal;
            // Include remote branches if requested
            bool getRemote = Settings.CommitInfoShowContainedInBranchesRemote ||
                             Settings.CommitInfoShowContainedInBranchesRemoteIfNoLocal;
            var  branches    = CommitInformation.GetAllBranchesWhichContainGivenCommit(Module, revision, getLocal, getRemote);
            var  links       = new List <string>();
            bool allowLocal  = Settings.CommitInfoShowContainedInBranchesLocal;
            bool allowRemote = getRemote;

            foreach (var branch in branches)
            {
                string noPrefixBranch = branch;
                bool   branchIsLocal;
                if (getLocal && getRemote)
                {
                    // "git branch -a" prefixes remote branches with "remotes/"
                    // It is possible to create a local branch named "remotes/origin/something"
                    // so this check is not 100% reliable.
                    // This shouldn't be a big problem if we're only displaying information.
                    branchIsLocal = !branch.StartsWith(remotesPrefix);
                    if (!branchIsLocal)
                    {
                        noPrefixBranch = branch.Substring(remotesPrefix.Length);
                    }
                }
                else
                {
                    branchIsLocal = !getRemote;
                }

                if ((branchIsLocal && allowLocal) || (!branchIsLocal && allowRemote))
                {
                    string branchText;
                    if (showBranchesAsLinks)
                    {
                        branchText = LinkFactory.CreateBranchLink(noPrefixBranch);
                    }
                    else
                    {
                        branchText = WebUtility.HtmlEncode(noPrefixBranch);
                    }
                    links.Add(branchText);
                }

                if (branchIsLocal && Settings.CommitInfoShowContainedInBranchesRemoteIfNoLocal)
                {
                    allowRemote = false;
                }
            }
            if (links.Any())
            {
                return(Environment.NewLine + WebUtility.HtmlEncode(containedInBranches.Text) + " " + links.Join(", "));
            }
            return(Environment.NewLine + WebUtility.HtmlEncode(containedInNoBranch.Text));
        }
            private FeedEntry BuildFeedEntry(CorrelatedResSyncInfo correlation, IFeedEntryEntityWrapper wrapper)
            {
                // create a new empty Feed Entry
                //ISyncSourceResourceFeedEntry feedEntry = FeedComponentFactory.Create<ISyncSourceResourceFeedEntry>();
                // get resource payload container from data store
                FeedEntry feedEntry = wrapper.GetSyncSourceFeedEntry(correlation);


                // create and set SyncState
                feedEntry.SyncState          = new SyncState();
                feedEntry.SyncState.EndPoint = correlation.ResSyncInfo.EndPoint;
                feedEntry.SyncState.Tick     = (correlation.ResSyncInfo.Tick > 0) ? correlation.ResSyncInfo.Tick : 1;
                feedEntry.SyncState.Stamp    = correlation.ResSyncInfo.ModifiedStamp;

                // set the id tag
                feedEntry.Id = feedEntry.Uri;
                // set the title tag
                feedEntry.Title = String.Format("{0}: {1}", _parentPerformer._requestContext.ResourceKind.ToString(), feedEntry.Key);
                // set the updated tag
                feedEntry.Updated = correlation.ResSyncInfo.ModifiedStamp.ToLocalTime();

                // set resource dependent  links (self, edit, schema, template, post, service)
                feedEntry.Links.AddRange(LinkFactory.CreateEntryLinks(_parentPerformer._requestContext, feedEntry));


                return(feedEntry);
            }
Exemplo n.º 11
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.Action == "add")
            {
                LinkModel info = new LinkModel();
                info.possymbol  = possymbol;
                info.includepic = this.txtincludepic.Text.Trim();
                info.linkurl    = this.txtlinkurl.Text.Trim();
                info.orderno    = Int32.Parse(this.txtorderno.Text.Trim());
                info.linkname   = this.txttitle.Text.Trim();
                info.createtime = DateTime.Now;

                LinkFactory.Add(info);

                ClientScript.RegisterStartupScript(this.GetType(), "AddEditTips", "<script language=\"javascript\">alert('添加成功!');window.location='linklist.aspx?pb=" + possymbol + "';</script>");
            }
            else if (this.Action == "edit")
            {
                int       linkid = HYRequest.GetInt("linkid", 0);
                LinkModel info   = LinkFactory.Get(linkid);

                info.includepic = this.txtincludepic.Text.Trim();
                info.linkurl    = this.txtlinkurl.Text.Trim();
                info.orderno    = Int32.Parse(this.txtorderno.Text.Trim());
                info.linkname   = this.txttitle.Text.Trim();

                LinkFactory.Update(info);
                ClientScript.RegisterStartupScript(this.GetType(), "AddEditTips", "<script language=\"javascript\">alert('修改成功!');window.location='linklist.aspx?pb=" + possymbol + "';</script>");
            }
        }
Exemplo n.º 12
0
        public void Add_accept_header_to_stylesheet_link()
        {
            var linkFactory = new LinkFactory();

            var builders = new List <DelegatingRequestBuilder>()
            {
                new AcceptHeaderRequestBuilder(new[] { new MediaTypeWithQualityHeaderValue("text/css") }),
                new InlineRequestBuilder(r =>
                {
                    r.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
                    return(r);
                })
            };

            linkFactory.SetRequestBuilder <StylesheetLink>(builders);

            var aboutlink = linkFactory.CreateLink <StylesheetLink>();

            aboutlink.Target = new Uri("http://example.org/about");

            var request = aboutlink.CreateRequest();

            Assert.Equal("text/css", request.Headers.Accept.ToString());
            Assert.Equal("gzip", request.Headers.AcceptEncoding.ToString());
        }
Exemplo n.º 13
0
        private void Init()
        {
            if (Document.DocumentMode == DocumentMode.Auto)
            {
                List <Node> nodes = NodeFactory.CreateNodes(30);
                ContentControl.PopulateNodes(nodes);
                LinkFactory.Nodes = nodes;
                ContentControl.PopulateLinks(LinkFactory.CreateLinks(60));
            }

            Canvas target = ContentControl.ContentCanvas;

            zoom     = new MapZoom(target);
            pan      = new Pan(target, zoom);
            rectZoom = new RectangleSelectionGesture(target, zoom, ModifierKeys.Control);
            rectZoom.ZoomSelection = true;
            autoScroll             = new AutoScroll(target, zoom);
            zoom.ZoomChanged      += new EventHandler(OnZoomChanged);

            ContentControl.VisualsChanged += new EventHandler <VisualChangeEventArgs>(OnVisualsChanged);
            //ZoomSlider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(OnZoomSliderValueChanged);

            ContentControl.Scale.Changed     += new EventHandler(OnScaleChanged);
            ContentControl.Translate.Changed += new EventHandler(OnScaleChanged);

            //ContentControl.Background = new SolidColorBrush(Color.FromRgb(0xd0, 0xd0, 0xd0));
            ContentControl.Background = new SolidColorBrush(Colors.White);
            ContentControl.ContentCanvas.Background = Brushes.White;
            Document.Nodes = ContentControl.Nodes;
            Document.Links = ContentControl.Links;
        }
Exemplo n.º 14
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            async Task <IClient> CreateClient()
            {
                var exists       = File.Exists(SettingsPath);
                var settingsFile = exists ? Some(SettingsPath) : None <string>();
                var storage      = new SqliteStorage($"{nameof(Chatter)}.db");
                var dispatcher   = new SynchronizationDispatcher(TaskScheduler.FromCurrentSynchronizationContext(), Application.Current.Dispatcher);
                var result       = await TryAsync(() => LinkFactory.CreateClientAsync(dispatcher, storage, settingsFile)).NoticeOnErrorAsync();

                var client = result.UnwrapOrDefault();

                if (exists == false && client != null)
                {
                    client.Profile.Name = $"{Environment.UserName}@{Environment.MachineName}";
                }
                if (result.IsError())
                {
                    Application.Current.Shutdown();
                }
                return(client);
            }

            this.IsEnabled = false;
            using var _0   = Disposable.Create(() => this.IsEnabled = true);

            this.client = App.CurrentClient ?? await CreateClient();

            this.DataContext = this.client?.Profile;
        }
Exemplo n.º 15
0
        public void ParseGoToBranchLink()
        {
            string expected = "gitext://gotobranch/master";
            string actual   = LinkFactory.ParseLink("master#gitext://gotobranch/master");

            Assert.That(actual, Is.EqualTo(expected));
        }
Exemplo n.º 16
0
        public static T CreateLink <T>(this LinkFactory linkFactory, Uri target) where T : Link, new()
        {
            var link = linkFactory.CreateLink <T>();

            link.Target = target;
            return(link);
        }
Exemplo n.º 17
0
        public void ParseRawHttpLinkWithHash()
        {
            string expected = "https://github.com/gitextensions/gitextensions/pull/3471#end";
            string actual   = LinkFactory.ParseLink("https://github.com/gitextensions/gitextensions/pull/3471#end");

            Assert.That(actual, Is.EqualTo(expected));
        }
Exemplo n.º 18
0
        /**
         * Creates a new client end of a NetBarrier connected to the barrier with the given index on the given Node
         *
         * @param addr
         *            NodeAddres of the Node that the barrier is located
         * @param vbn
         *            Index of the barrier to connect to
         * @param enrolled
         *            The number of locally enrolled processes
         * @return A new client end of a NetBarrier
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         * @//throws ArgumentException
         *             Thrown if the number of enrolled processes is outside the defined range.
         */
        public static NetBarrier netBarrier(NodeAddress addr, int vbn, int enrolled)
        {
            // Get the Link with the given address
            Link link = LinkFactory.getLink(addr);

            NetBarrier barrierToReturn = null;

            try
            {
                barrierToReturn = NetBarrier.create(new NetBarrierLocation(link.remoteID, vbn), enrolled);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e);
            }
            catch (JCSPNetworkException e)
            {
                Console.WriteLine(e);
            }

            return(barrierToReturn);


            // Create a new NetBarrier
            //return NetBarrier.create(new NetBarrierLocation(link.remoteID, vbn), enrolled);
        }
Exemplo n.º 19
0
        public void ParseInternalScheme_Null()
        {
            var linkFactory = new LinkFactory();

            Assert.False(linkFactory.ParseInternalScheme(null, out var actualCommandEventArgs));
            Assert.That(actualCommandEventArgs, Is.Null);
        }
Exemplo n.º 20
0
        private static async Task TypedLinksFromGenericType()
        {
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders
                .UserAgent.Add(new ProductInfoHeaderValue("DarrelsGitClient", "1.0"));

            // Factory for typed links
            var linkFactory = new LinkFactory();
            GitHubHelper.RegisterGitHubLinks(linkFactory);

            // Get Home Document, without strongly typed object
            var homelink = new HomeLink();
            var homeResponse = await httpClient.FollowLinkAsync(homelink);
            var githubDocument = await homeResponse.Content.ReadAsGithubDocumentAsync(linkFactory);

            // Retrieve specific link from generic document
            var codeSearchLink = githubDocument.GetLink<CodeSearchLink>();
            codeSearchLink.Query = ".Result user:darrelmiller";

            var responseMessage = await httpClient.FollowLinkAsync(codeSearchLink);
            var githubDocument2 = await responseMessage.Content.ReadAsGithubDocumentAsync();
            var searchResults = CodeSearchLink.InterpretMessageBody(githubDocument2);

            // Show Results
            foreach (var result in searchResults.Items)
            {
                Console.WriteLine(result.Path);
            }
        }
Exemplo n.º 21
0
 public ToDoResource MapToResource(ToDo entity, LinkFactory linker)
 {
     return new ToDoResource(entity.Id) {ActivityDesc = entity.ActivityDesc,
                                         ActivityName = entity.ActivityName,
                                         Self = linker.GetResourceLink<ToDosController>(controller => controller.Get(entity.Id), "self", entity.ActivityName, HttpMethod.Get)
     };
 }
Exemplo n.º 22
0
        public void ParseCustomeSchemeLinkWithHash()
        {
            string expected = "ftp://github.com/gitextensions/gitextensions/pull/3471#end";
            string actual   = LinkFactory.ParseLink("PR#3471 and Issue#64#ftp://github.com/gitextensions/gitextensions/pull/3471#end");

            Assert.That(actual, Is.EqualTo(expected));
        }
Exemplo n.º 23
0
        /**
         * Creates a new NetChannelOutput connected to the channel with the given vcn on the given Node
         *
         * @param nodeAddr
         *            The NodeAddress of the Node to connect to
         * @param vcn
         *            The Virtual Channel Number of the input channel
         * @return A new NetChannelOutput
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         */
        public NetChannelOutput one2net(NodeAddress nodeAddr, int vcn)
        //throws JCSPNetworkException
        {
            NodeID             remoteNode = LinkFactory.getLink(nodeAddr).remoteID;
            NetChannelLocation loc        = new NetChannelLocation(remoteNode, vcn);

            return(One2NetChannel.create(loc, Int32.MaxValue, new ObjectNetworkMessageFilter.FilterTX()));
        }
Exemplo n.º 24
0
        public void CreateAboutLink()
        {
            var registry = new LinkFactory();

            var link = registry.CreateLink<AboutLink>();

            Assert.IsType<AboutLink>(link);
        }
Exemplo n.º 25
0
        /**
         * Creates a new NetSharedChannelOutput connected to the channel with the given vcn on the given Node which uses the
         * given filter to encode outgoing messages
         *
         * @param nodeAddr
         *            The NodeAddress of the Node to connect to
         * @param vcn
         *            The Virtual Channel Number of the input channel
         * @param filter
         *            The immunity to poison that the channel has
         * @return A new NetSharedChannelOutput
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         */
        public NetSharedChannelOutput any2net(NodeAddress nodeAddr, int vcn, NetworkMessageFilter.FilterTx filter)
        //throws JCSPNetworkException
        {
            NodeID             remoteNode = LinkFactory.getLink(nodeAddr).remoteID;
            NetChannelLocation loc        = new NetChannelLocation(remoteNode, vcn);

            return(Any2NetChannel.create(loc, Int32.MaxValue, filter));
        }
Exemplo n.º 26
0
        /**
         * Creates a new NetSharedChannelOutput connected to the channel with the given vcn on the given Node which has the
         * given poison immunity
         *
         * @param nodeAddr
         *            The NodeAddress of the Node to connect to
         * @param vcn
         *            The Virtual Channel Number of the input channel
         * @param immunityLevel
         *            The immunity to poison that the channel has
         * @return A new NetSharedChannelOutput
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         */
        public NetSharedChannelOutput any2net(NodeAddress nodeAddr, int vcn, int immunityLevel)
        //throws JCSPNetworkException
        {
            NodeID             remoteNode = LinkFactory.getLink(nodeAddr).remoteID;
            NetChannelLocation loc        = new NetChannelLocation(remoteNode, vcn);

            return(Any2NetChannel.create(loc, immunityLevel, new ObjectNetworkMessageFilter.FilterTX()));
        }
Exemplo n.º 27
0
        public void ParseInternalScheme_None(string link)
        {
            var linkFactory = new LinkFactory();
            var uri         = new Uri(link);

            Assert.False(linkFactory.ParseInternalScheme(uri, out var actualCommandEventArgs));
            Assert.That(actualCommandEventArgs, Is.Null);
        }
Exemplo n.º 28
0
        public void Add(Link model)
        {
            var entity = LinkFactory.Create(model);

            _linkRepository.Add(entity);

            model.Id = entity.Id;
        }
Exemplo n.º 29
0
        private void LoadListData()
        {
            this.dgLinkList.DataSource = LinkFactory.GetList(possymbol);
            this.dgLinkList.DataBind();

            this.chkSelectAll.Attributes.Add("onclick", "javascript:SelectAll(this);");
            this.btnBatchDelete.Attributes.Add("onclick", "return CheckDeleteHandle(this);");
        }
Exemplo n.º 30
0
        public void CreateAboutLink()
        {
            var registry = new LinkFactory();

            var link = registry.CreateLink <AboutLink>();

            Assert.IsType <AboutLink>(link);
        }
Exemplo n.º 31
0
 public Entity Handle()
 {
     return(new EntityBuilder()
            .WithClass("status")
            .WithProperty("currentUtcTime", DateTime.UtcNow)
            .WithLink(() => LinkFactory.Create("status", true))
            .Build());
 }
Exemplo n.º 32
0
        public void ResolveLinkWithTemplateUri()
        {
            TridionLinkProvider.link2 = "/something";
            var link = LinkFactory.ResolveLink("tcm:2-456-64", "tcm:2-123", "tcm:2-789-32");

            Assert.IsNotNull(link);
            Assert.IsFalse(string.IsNullOrEmpty(link));
            Assert.AreEqual(link, "/something");
        }
Exemplo n.º 33
0
        /**
         * Creates a new NetChannelOutput connected to the channel with the given vcn on the given Node which has the given
         * poison immunity and uses the given filter to encode outgoing messages
         *
         * @param nodeAddr
         *            The NodeAddress of the Node to connect to
         * @param vcn
         *            The Virtual Channel Number of the input channel
         * @param immunityLevel
         *            The immunity to poison that the channel has
         * @param filter
         *            The filter used to encode outgoing messages
         * @return A new NetChannelOutput
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         */
        public NetChannelOutput one2net(NodeAddress nodeAddr, int vcn, int immunityLevel,
                                        NetworkMessageFilter.FilterTx filter)
        //throws JCSPNetworkException
        {
            NodeID             remoteNode = LinkFactory.getLink(nodeAddr).remoteID;
            NetChannelLocation loc        = new NetChannelLocation(remoteNode, vcn);

            return(One2NetChannel.create(loc, immunityLevel, filter));
        }
Exemplo n.º 34
0
        public void Read(string id)
        {
            Feed <FeedEntry> result = new Feed <FeedEntry>();

            //result.Updated = GetRandomDate();
            result.Url         = _request.Uri.ToString();
            result.Author.Name = "Northwind Adapter";


            string resource = TrimApostophes(id);

            if (resource != null)
            {
                _request.Response.FeedEntry = _wrapper.GetFeedEntry(resource);
                if (_request.Response.FeedEntry != null && !_request.Response.FeedEntry.IsDeleted && isActive(_request.Response.FeedEntry))
                {
                    _request.Response.FeedEntry.Title = _request.Response.FeedEntry.ToString();
                }

                else
                {
                    throw new DiagnosesException(Severity.Error, resource + " not found", DiagnosisCode.DatasetNotFound);
                }
            }
            else
            {
                result.Category.Scheme = "http://schemas.sage.com/sdata/categories";
                result.Category.Term   = "collection";
                result.Category.Label  = "Resource Collection";

                string[] ids        = _wrapper.GetFeed();
                long     start      = Math.Max(0, _request.Uri.StartIndex - 1); //Startindex is 1-based
                long     max        = _request.Uri.Count == null ? ids.Length : Math.Min((long)_request.Uri.Count + start, (long)ids.Length);
                long     entryCount = _request.Uri.Count == null ? DEFAULT_COUNT : (long)_request.Uri.Count;
                _request.Uri.Count = entryCount;
                for (long i = start; result.Entries.Count < entryCount && i < ids.Length; i++)
                {
                    string    entryId = ids[i];
                    FeedEntry entry   = _wrapper.GetFeedEntry(entryId);
                    if (entry != null)
                    {
                        entry.Title = entry.ToString();
                        entry.Links.AddRange(LinkFactory.CreateEntryLinks(_context, entry));
                        entry.Updated = DateTime.Now;
                        result.Entries.Add(entry);
                    }
                }

                result.Title = result.Entries.Count + " " + _context.ResourceKind.ToString();
                HandlePaging(_request, result, ids);
                //FeedLink link = new FeedLink(_request.Uri.AppendPath("$schema").ToString(), LinkType.Schema, MediaType.Xml, "Schema");
                FeedLink[] links = LinkFactory.CreateFeedLinks(_context, _request.Uri.ToString());
                result.Links.AddRange(links);
                result.Updated         = DateTime.Now;
                _request.Response.Feed = result;
            }
        }
Exemplo n.º 35
0
 public static void RegisterGitHubLinks(LinkFactory linkFactory)
 {
     linkFactory.AddLinkType<HomeLink>();
     linkFactory.AddLinkType<UserLink>();
     linkFactory.AddLinkType<CodeSearchLink>();
     linkFactory.AddLinkType<EmojisLink>();
     linkFactory.AddLinkType<FollowingLink>();
     linkFactory.AddLinkType<FollowersLink>();
     linkFactory.AddLinkType<GistsLink>();
 }
 public static List<Link> ParseLinkHeaders(this HttpHeaders headers, Uri baseUri, LinkFactory linkRegistry)
 {
     var list = new List<Link>();
     var parser = new LinkHeaderParser(linkRegistry);
     var linkHeaders = headers.GetValues("Link");
     foreach (var linkHeader in linkHeaders)
     {
         list.AddRange(parser.Parse(baseUri, linkHeader));
     }
     return list;
 }
Exemplo n.º 37
0
        public  async Task<HomeDocument> ParseResponse( HttpResponseMessage response, LinkFactory linkFactory)
        {
            if (response.StatusCode != HttpStatusCode.OK) return null;
            if (response.Content == null) return null;
            if (response.Content.Headers.ContentType == null || response.Content.Headers.ContentType.MediaType != "application/home+json") return null;

            Stream stream = await response.Content.ReadAsStreamAsync();
            return HomeDocument.Parse(stream, linkFactory);


        }
Exemplo n.º 38
0
        public void SpecifyHandlerForAboutLink()
        {
            var foo = false;

            var registry = new LinkFactory();
            registry.SetHandler<AboutLink>(new ActionResponseHandler((hrm) => foo = true));

            var link = registry.CreateLink<AboutLink>();

            Assert.IsType<ActionResponseHandler>(link.HttpResponseHandler);
        }
        public Given_a_GitHub_ClientState()
        {
            _linkFactory = new LinkFactory();

            GitHubHelper.RegisterGitHubLinks(_linkFactory);

            _clientstate = new GithubClientState(_linkFactory);

            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MyAmazingApp", "1.0"));

        }
Exemplo n.º 40
0
        private async Task<HomeDocument> GetHomeDocument()
        {
            var linkFactory = new LinkFactory();
            ConferenceWebPack.Config.Register(linkFactory);

            var homeLink = linkFactory.CreateLink<HomeLink>();
            homeLink.Target = new Uri("http://birch:1001/");
            var response = await _client.SendAsync(homeLink.BuildRequestMessage());

            var homeDocument = await homeLink.ParseResponse(response, linkFactory);
            return homeDocument;
        }
Exemplo n.º 41
0
 public static void Register(LinkFactory linkFactory)
 {
     linkFactory.AddLinkType<HomeLink>();
     linkFactory.AddLinkType<DaysLink>();
     linkFactory.AddLinkType<SessionLink>();
     linkFactory.AddLinkType<SessionsLink>();
     linkFactory.AddLinkType<SpeakerLink>();
     linkFactory.AddLinkType<SpeakersLink>();
     linkFactory.AddLinkType<TopicLink>();
     linkFactory.AddLinkType<TopicsLink>();
     linkFactory.AddLinkType<ReviewLink>();
 }
Exemplo n.º 42
0
        public void ParseLinkHeaders2()
        {
            var linkRegistry = new LinkFactory();
            var response = new HttpResponseMessage();
            response.RequestMessage = new HttpRequestMessage() { RequestUri = new Uri("http://example.org/") };
            response.Headers.TryAddWithoutValidation("Link", "<http://example.org/about>;rel=\"about\", "
                                + "<http://example.org/help>;rel=\"help\"");
            var links = response.ParseLinkHeaders(linkRegistry);

            Assert.NotNull(links.Where(l => l is AboutLink).FirstOrDefault());
            Assert.NotNull(links.Where(l => l is HelpLink).FirstOrDefault());
        }
Exemplo n.º 43
0
        public void ParseLinkHeaders()
        {
            var linkRegistry = new LinkFactory();
            var response = new HttpResponseMessage();
            response.RequestMessage = new HttpRequestMessage() { RequestUri = new Uri("http://example.org/") };
            response.Headers.AddLinkHeader(new AboutLink() { Target = new Uri("http://example.org/about") });
            response.Headers.AddLinkHeader(new HelpLink() { Target = new Uri("http://example.org/help") });

            var links = response.ParseLinkHeaders(linkRegistry);

            Assert.Equal(2,links.Count);
            Assert.NotNull(links.Where(l => l is AboutLink).FirstOrDefault());
            Assert.NotNull(links.Where(l => l is HelpLink).FirstOrDefault());
        }
Exemplo n.º 44
0
        // This is bogus too.  Also should be done by HttpClient Message handler
        
        public void Add_auth_header_aboutlink_request()
        {
            var linkFactory = new LinkFactory();
            linkFactory.SetRequestBuilder<AboutLink>(new InlineRequestBuilder(
                r => { r.Headers.Authorization = new AuthenticationHeaderValue("foo", "bar");
                         return r;
                }));

            var aboutlink = linkFactory.CreateLink<AboutLink>();
            aboutlink.Target = new Uri("http://example.org/about");

            var request = aboutlink.CreateRequest();

            Assert.Equal("foo bar", request.Headers.Authorization.ToString());
        }
Exemplo n.º 45
0
        public void Add_user_Agent_header()
        {
            

            var linkFactory = new LinkFactory();
            linkFactory.SetRequestBuilder<AboutLink>(new InlineRequestBuilder(r =>
            {
                r.Headers.UserAgent.Add(new ProductInfoHeaderValue("MyApp", "1.0"));
                return r;
            }));

            var aboutlink = linkFactory.CreateLink<AboutLink>();
            aboutlink.Target = new Uri("http://example.org/about");

            var request = aboutlink.CreateRequest();

            Assert.Equal("MyApp/1.0", request.Headers.UserAgent.ToString());
        }
Exemplo n.º 46
0
        public override IEnumerable<IPageLinkModel> LinkPages(IPageRequestModel request, IPageResultsModel results)
        {
            if (null == request) throw new ArgumentNullException("request");
            if (null == results) throw new ArgumentNullException("results");

            var list = new List<IPageLinkModel>();
            if (results.TotalPageCount > 1) {

                var requestedPage = request.RequestedPage;
                var totalPageCount = results.TotalPageCount;
                var factory = new LinkFactory(request, IsBase1);

                list.Add(factory.CreateLink(0));

                if (requestedPage > 1) {
                    var test = requestedPage == totalPageCount - 1 && totalPageCount > 3;
                    list.Add(factory.CreateRange(1, test ? requestedPage - 3 : requestedPage - 2));
                    if (test) {
                        list.Add(factory.CreateLink(requestedPage - 2));
                    }
                    list.Add(factory.CreateLink(requestedPage - 1));
                }

                if (requestedPage != 0 && requestedPage != totalPageCount - 1) {
                    list.Add(factory.CreateLink(requestedPage));
                }

                if (requestedPage < totalPageCount - 2) {
                    var test = requestedPage == 0 && totalPageCount > 3;
                    list.Add(factory.CreateLink(requestedPage + 1));
                    if (test) {
                        list.Add(factory.CreateLink(requestedPage + 2));
                    }
                    list.Add(factory.CreateRange(test ? requestedPage + 3 : requestedPage + 2, totalPageCount - 2));
                }

                list.Add(factory.CreateLink(totalPageCount - 1));
            }

            return list;
        }
Exemplo n.º 47
0
        public void Add_accept_header_to_stylesheet_link()
        {
            var linkFactory = new LinkFactory();

            var builders = new List<DelegatingRequestBuilder>()
            {
                new AcceptHeaderRequestBuilder(new[] {new MediaTypeWithQualityHeaderValue("text/css")}),
                new InlineRequestBuilder(r =>
                {
                    r.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
                    return r;
                })
            };

            linkFactory.SetRequestBuilder<StylesheetLink>(builders);

            var aboutlink = linkFactory.CreateLink<StylesheetLink>();
            aboutlink.Target = new Uri("http://example.org/about");

            var request = aboutlink.CreateRequest();

            Assert.Equal("text/css", request.Headers.Accept.ToString());
            Assert.Equal("gzip", request.Headers.AcceptEncoding.ToString());
        }
Exemplo n.º 48
0
        public Task SpecifyHandlerChainForAboutLink()
        {
            var foo = false;
            var bar = false;
            var baz = false;

            var registry = new LinkFactory();
            var grh = new ActionResponseHandler((hrm) => baz = true,
                new ActionResponseHandler((hrm) => foo = true,
                    new ActionResponseHandler((hrm) => bar = true)));

            registry.SetHandler<AboutLink>(grh);

            var link = registry.CreateLink<AboutLink>();
            link.Target = new Uri("http://example.org");
            var httpClient = new HttpClient(new FakeHandler() { Response = new HttpResponseMessage()});

            return httpClient.FollowLinkAsync(link).ContinueWith(t =>
                {
                    Assert.True(foo);
                    Assert.True(bar);
                    Assert.True(baz);
                });
        }
Exemplo n.º 49
0
        private static HomeDocument Parse(JObject jObject, LinkFactory linkFactory = null)
        {
            if (linkFactory == null) linkFactory = new LinkFactory();
            

            var doc = new HomeDocument();
            var resources = jObject["resources"] as JObject;
            if (resources != null)
            {
                foreach (var resourceProp in resources.Properties())
                {
                    
                    var link = linkFactory.CreateLink(resourceProp.Name);
                    
                    var resource = resourceProp.Value as JObject;

                    var hrefProp = resource.Property("href");
                    if (hrefProp != null)
                    {
                        
                        link.Target = new Uri(hrefProp.Value.Value<string>(), UriKind.RelativeOrAbsolute);
                    }
                    else
                    {
                        link.Target = new Uri((String)resource["href-template"], UriKind.RelativeOrAbsolute);
                        var hrefvars = resource.Value<JObject>("href-vars");
                        foreach (var hrefvar in hrefvars.Properties())
                        {
                            var hrefUri = (string)hrefvar;
                            if (string.IsNullOrEmpty(hrefUri))
                            {
                                link.SetParameter(hrefvar.Name, null);
                            }
                            else
                            {
                                link.SetParameter(hrefvar.Name, null, new Uri(hrefUri, UriKind.RelativeOrAbsolute));
                            }
                        }
                    }

                    var hintsProp = resource.Property("hints");
                    if (hintsProp != null)
                    {
                        var hintsObject = hintsProp.Value as JObject;
                        foreach (var hintProp in hintsObject.Properties())
                        {
                            var hint = linkFactory.HintFactory.CreateHint(hintProp.Name);
                            hint.Content = hintProp.Value;
                            link.AddHint(hint);
                        }
                        
                    }

                    doc.AddResource(link);
                }
            }

            return doc;
        }
 public static async Task<GithubDocument> ReadAsGithubDocumentAsync(this HttpContent content, LinkFactory linkFactory = null)
 {
     if (linkFactory == null) linkFactory = new LinkFactory();
     var stream = await content.ReadAsStreamAsync();
     return new GithubDocument(stream, linkFactory);
 }
Exemplo n.º 51
0
 /// <summary>
 /// Create a HomeDocument instance from a stream of JSON text that is formatted as per the json-home specification
 /// </summary>
 /// <param name="jsonStream"></param>
 /// <param name="linkFactory">Optionally specifiy a linkFactory for creating strongly typed links.  If one is not provided the default LinkFactory will be created and only IANA registered links will be available as strong types.  All unrecognized link relations will be deserialized as the base Link class.</param>
 /// <returns></returns>
 public static HomeDocument Parse(Stream jsonStream, LinkFactory linkFactory = null)
 {
     var sr = new StreamReader(jsonStream);
     return Parse(sr.ReadToEnd(), linkFactory);
 }
Exemplo n.º 52
0
 public LinkHeaderParser(LinkFactory linkFactory)
 {
     _linkFactory = linkFactory;
 }
Exemplo n.º 53
0
 /// <summary>
 /// Create a HomeDocument instance from a string of JSON text that is formatted as per the json-home specification
 /// </summary>
 /// <param name="jsonString"></param>
 /// <param name="linkFactory">Optionally specifiy a linkFactory for creating strongly typed links.  If one is not provided the default LinkFactory will be created and only IANA registered links will be available as strong types.  All unrecognized link relations will be deserialized as the base Link class.</param>
 /// <returns></returns>
 public static HomeDocument Parse(string jsonString, LinkFactory linkFactory = null)
 {
     var jDoc = JObject.Parse(jsonString);
     return Parse(jDoc, linkFactory);
 }
Exemplo n.º 54
0
 public GithubClientState(LinkFactory linkFactory)
 {
     _linkFactory = linkFactory;
     ConfigureLinkBehaviour();
 }
Exemplo n.º 55
0
        public void Set_path_parameters()
        {
            var linkFactory = new LinkFactory();
            var aboutlink = linkFactory.CreateLink<RelatedLink>();
            aboutlink.Template = new UriTemplate("http://example.org/customer/{id}");
            aboutlink.Template.AddParameter("id", 45 );

            var request = aboutlink.CreateRequest();

            Assert.Equal("http://example.org/customer/45", request.RequestUri.OriginalString);
        }
Exemplo n.º 56
0
        public void Set_query_parameters_without_template()
        {
            var linkFactory = new LinkFactory();
            var aboutlink = linkFactory.CreateLink<RelatedLink>(new Uri("http://example.org/customer"));

            aboutlink.Template = new UriTemplate(aboutlink.Target.AbsoluteUri + "{?id}");
            aboutlink.Template.SetParameter("id", 45);
            var request = aboutlink.CreateRequest();

            Assert.Equal("http://example.org/customer?id=45", request.RequestUri.OriginalString);
        }
Exemplo n.º 57
0
        public void Update_query_parameters()
        {
            var linkFactory = new LinkFactory();
            var relatedLink = linkFactory.CreateLink<RelatedLink>();
            relatedLink.Target = new Uri("http://example.org/customer?id=23");

            relatedLink.Template = new UriTemplate(relatedLink.Target.GetLeftPart(UriPartial.Path) + "{?id}");
            relatedLink.Template.AddParameter("id",45);

            //relatedLink.Template.AddParameters(parameters,true);
            var request = relatedLink.CreateRequest();

            Assert.Equal("http://example.org/customer?id=45", request.RequestUri.OriginalString);
        }
Exemplo n.º 58
0
        public void Create_request_that_has_a_body()
        {
            var linkFactory = new LinkFactory();
            var relatedLink = linkFactory.CreateLink<RelatedLink>(new Uri("http://example.org/customer?format=xml&id=23"));

            relatedLink.Method = HttpMethod.Post;
            relatedLink.Content = new StringContent("");
            var request = relatedLink.CreateRequest();

            Assert.Equal(HttpMethod.Post, request.Method);
        }
Exemplo n.º 59
0
        public void Use_non_get_method()
        {
            var linkFactory = new LinkFactory();
            var relatedLink = linkFactory.CreateLink<RelatedLink>(new Uri("http://example.org/customer?format=xml&id=23"));

            relatedLink.Method = HttpMethod.Head;
            var request = relatedLink.CreateRequest();

            Assert.Equal(HttpMethod.Head, request.Method);
        }
Exemplo n.º 60
0
        public void Remove_a_query_parameters()
        {
            var linkFactory = new LinkFactory();
            var relatedLink = linkFactory.CreateLink<RelatedLink>(new Uri("http://example.org/customer?format=xml&id=23"));
            
            relatedLink.Template = relatedLink.Target.MakeTemplate();
            relatedLink.Template.ClearParameter("format");
            
            var request = relatedLink.CreateRequest();

            Assert.Equal("http://example.org/customer?id=23", request.RequestUri.OriginalString);
        }