public void CreateResourceWithPathParameterAndRelWithDots() { var doc = new HomeDocument(); doc.AddResource <Link>(l => { l.Relation = "vnd.foo.about"; l.Target = new Uri("http://example.org:1001/about/{id}"); }); doc.AddResource <HelpLink>(l => { l.Target = new Uri("http://example.org:1001/help/{id}"); }); var ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; var st = new StreamReader(ms); var s = st.ReadToEnd(); Assert.True(s.Contains("href-template")); }
public void ParseEmptyHomeDoc() { // Doc needs to be at least an object var doc = HomeDocument.Parse("{}"); Assert.NotNull(doc); }
public void ParseHomeDocWithNoResources() { // Doc needs to be at least an object var doc = HomeDocument.Parse("{ \"resources\" : {} }"); Assert.NotNull(doc); }
public void RoundTripHomeDocumentWithHint() { var doc = new HomeDocument(); var aboutLink = new AboutLink() { Target = new Uri("about", UriKind.Relative) }; var allowHint = new AllowHint(); allowHint.AddMethod(HttpMethod.Get); aboutLink.AddHint(allowHint); aboutLink.AddHint(new FormatsHint()); doc.AddResource(aboutLink); var ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; var outDoc = HomeDocument.Parse(ms); var link = outDoc.GetResource("about"); Assert.IsType <AboutLink>(link); Assert.IsType <AllowHint>(link.GetHints().First()); Assert.IsType <FormatsHint>(link.GetHints().Last()); }
private HomeDocument GetHomeDocument() { var home = new HomeDocument(); string Prefix = Request.RequestUri + "/"; Prefix = ""; JToken listFormat = JToken.FromObject(new List <PhysicalTopology>() { new PhysicalTopology(), new PhysicalTopology() }); JToken itemFormat = JToken.FromObject(new PhysicalTopology() { Id = 1, Name = "a" }); JToken treeFormat = JToken.FromObject(new PhysicalTopology[] { new PhysicalTopology { Children = new List <PhysicalTopology> { } } }); home.AddResource(GetLink(Prefix, "areaList", "area", listFormat)); home.AddResource(GetLink(Prefix, "areaItem", "area/{id}", itemFormat, HttpMethod.Get, HttpMethod.Delete)); home.AddResource(GetLink(Prefix, "areaTreeRoot", "area/tree", treeFormat)); home.AddResource(GetLink(Prefix, "areaTree", "area/tree/{id}", treeFormat)); home.AddResource(GetLink(Prefix, "areaSearch", "area/search?name={name}", listFormat)); home.AddResource(GetLink(Prefix, "areaChildren", "area/{id}/children", listFormat)); home.AddResource(GetLink(Prefix, "areaPost", "area", itemFormat, HttpMethod.Post)); home.AddResource(GetLink(Prefix, "areaPut", "area", itemFormat, HttpMethod.Put)); return(home); }
public void CreateHomeDocumentWithFormatsHints() { var doc = new HomeDocument(); var aboutLink = new AboutLink() { Target = new Uri("about", UriKind.Relative) }; aboutLink.AddHint <AllowHint>(h => h.AddMethod(HttpMethod.Get)); aboutLink.AddHint <FormatsHint>(h => h.AddMediaType("application/json")); doc.AddResource(aboutLink); var ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; var outDoc = HomeDocument.Parse(ms); var link = outDoc.GetResource("about"); Assert.IsType <AboutLink>(link); Assert.IsType <AllowHint>(link.GetHints().First()); Assert.IsType <FormatsHint>(link.GetHints().Last()); Assert.IsType <AboutLink>(outDoc.Resources.First()); }
/// <inheritdoc/> public Task <HomeDocument> GetHomeAsync(CancellationToken cancellationToken) { if (_homeDocument != null) { return(InternalTaskExtensions.CompletedTask(_homeDocument)); } UriTemplate template = new UriTemplate("/"); Func <Task <Tuple <IdentityToken, Uri> >, HttpWebRequest> prepareRequest = PrepareRequestAsyncFunc(HttpMethod.GET, template, new Dictionary <string, string>()); Func <Task <HttpWebRequest>, Task <HomeDocument> > requestResource = GetResponseAsyncFunc <HomeDocument>(cancellationToken); Func <Task <HomeDocument>, HomeDocument> cacheResult = task => { _homeDocument = task.Result; return(task.Result); }; return(AuthenticateServiceAsync(cancellationToken) .Select(prepareRequest) .Then(requestResource) .Select(cacheResult)); }
public void SynchronousTestGetHome() { IQueueingService provider = CreateProvider(); HomeDocument document = provider.GetHome(); Assert.IsNotNull(document); Console.WriteLine(JsonConvert.SerializeObject(document, Formatting.Indented)); }
private async Task DiscoverResources() { var response = await _HttpClient.GetAsync("/"); _homeDocument = HomeDocument.Parse(await response.Content.ReadAsStreamAsync()); AllSpeakers = _homeDocument.GetResource(LinkHelper.GetLinkRelationTypeName <SpeakersLink>()).Target.OriginalString; AllSessions = _homeDocument.GetResource(LinkHelper.GetLinkRelationTypeName <SessionsLink>()).Target.OriginalString; }
public async Task GetHomeAsyncAwait() { #region GetHomeAsync (await) IQueueingService queueingService = new CloudQueuesProvider(identity, region, clientId, internalUrl, identityProvider); HomeDocument createdQueue = await queueingService.GetHomeAsync(CancellationToken.None); #endregion }
private async Task DiscoverResources() { var response = await _HttpClient.GetAsync("/"); _homeDocument = HomeDocument.Parse(await response.Content.ReadAsStreamAsync()); SpeakersLink = _homeDocument.GetResource <SpeakersLink>(); SessionsLink = _homeDocument.GetResource <SessionsLink>(); }
public async Task TestGetHome() { IQueueingService provider = CreateProvider(); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(10))); HomeDocument document = await provider.GetHomeAsync(cancellationTokenSource.Token); Assert.IsNotNull(document); Console.WriteLine(JsonConvert.SerializeObject(document, Formatting.Indented)); }
public void ParseHomeDocWithOneResource() { // Doc needs to be at least an object var doc = HomeDocument.Parse("{ \"resources\" :{ \"http://example.org/rels/test\" : {\"href\" : \"/test\"} }}"); var resource = doc.GetResource("http://example.org/rels/test"); Assert.NotNull(resource); Assert.Equal(resource.Target, new Uri("/test", UriKind.Relative)); }
public SensorThingsClient(string server) { Task.Run(async() => { var response = await Http.GetJson <HomeDocument>(server); if (!response.Success) { throw new Exception("Unable to get home document"); } return(_homedoc = response.Result); }) .Wait(); }
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 }); }
public static void Run(RestController client, string RestHomeUri, string filter, int itemsPerPage, bool pauseBetweenPages, string repositoryName, bool printResult, string userName) { // get repository resource HomeDocument home = client.Get <HomeDocument>(RestHomeUri, null); Feed <Repository> repositories = home.GetRepositories <Repository>(new FeedGetOptions { Inline = true, Links = true }); Repository repository = repositories.FindInlineEntry(repositoryName); // get a collection of users GetUsers(repository, filter, itemsPerPage, pauseBetweenPages, printResult); OperationsOnUser(repository, userName, itemsPerPage, pauseBetweenPages, printResult); }
public IHttpActionResult Get() { var home = new HomeDocument(); home.AddResource(TopicsLinkHelper.CreateLink(Request).WithHints()); home.AddResource(DaysLinkHelper.CreateLink(Request).WithHints()); home.AddResource(SessionsLinkHelper.CreateLink(Request).WithHints()); home.AddResource(SpeakersLinkHelper.CreateLink(Request).WithHints()); return(new OkResult(Request) .WithCaching(new CacheControlHeaderValue() { MaxAge = new TimeSpan(0, 0, 60) }) .WithContent(new HomeContent(home))); }
public void RoundTripHomeDocument() { var doc = new HomeDocument(); doc.AddResource(new AboutLink() { Target = new Uri("about", UriKind.Relative) }); var ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; var outDoc = HomeDocument.Parse(ms); Assert.NotNull(outDoc.GetResource("about")); }
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)); }
public IHttpActionResult Get() { //var explorer = new ApiExplorer(Configuration); //var descriptions = explorer.ApiDescriptions; //return new OkResult(Request).WithContent(new StringContent(String.Join("\n",descriptions.Select(d=> d.ID).ToArray()))); var home = new HomeDocument(); home.AddResource(TopicsLinkHelper.CreateLink(Request).WithHints()); home.AddResource(DaysLinkHelper.CreateLink(Request).WithHints()); home.AddResource(SessionsLinkHelper.CreateLink(Request).WithHints()); home.AddResource(SpeakersLinkHelper.CreateLink(Request).WithHints()); return(new OkResult(Request) .WithCaching(new CacheControlHeaderValue() { MaxAge = new TimeSpan(0, 0, 60) }) .WithContent(new HomeContent(home))); }
public void CreateResource_with_extension_rel_and_template() { var doc = new HomeDocument(); doc.AddResource <Link>(l => { l.Relation = "http://webapibook.net/rels#issue-processor"; l.Target = new Uri("/issueprocessor/{id}{?action}", UriKind.Relative); }); var ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; var st = new StreamReader(ms); var s = st.ReadToEnd(); Assert.True(s.Contains("href-template")); }
public void CreateResourceWithMultipleQueryParameters() { var doc = new HomeDocument(); doc.AddResource <Link>(l => { l.Relation = "vnd.foo.about"; l.Template = new UriTemplate("http://example.org:1001/about{?id,name}"); }); var ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; var st = new StreamReader(ms); var s = st.ReadToEnd(); Assert.True(s.Contains("href-template")); }
public ActionResult <IEnumerable <Author> > GetAuthors() { var apiEntryPoint = new HomeDocument { Message = @"Entry point into the Blogging Hypermedia API powered by JsonApiFramework [Server]." + " " + "Implements the JSON API 1.0 specification.", Version = "1.0" }; var authorsFromRepo = _repository.GetAuthors(); var courses = _repository.GetCourses1(); var currentRequestUri = this.GetCurrentRequestUri(); using var documentContext = this.ApiServiceContext.CreateApiDocumentContext(); var document = documentContext .NewDocument(currentRequestUri) .ResourceCollection(authorsFromRepo) .Relationships() .Relationship("author") .RelationshipEnd() .RelationshipsEnd() .Relationships() .AddRelationship("course", new[] { Keywords.Related }) .RelationshipsEnd() .ResourceCollectionEnd() .WriteDocument(); // Convert document to JSON and output to the console. var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, Converters = new List <JsonConverter> { new StringEnumConverter() } }; var json = document.ToJson(jsonSerializerSettings); return(Ok(json)); }
public void RetrievingHomeRepresentation(HomeDocument home) { "When it is retrieved". f(() => { Request.RequestUri = _uriHome; Response = Client.SendAsync(Request).Result; var stream = Response.Content.ReadAsStreamAsync().Result; home = HomeDocument.Parse(stream); }); "Then a '200 OK' status is returned". f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK)); "And it is returned". f(() => home.ShouldNotBeNull()); "And it should have an issueprocessor link". f(() => home.Resources.FirstOrDefault(l => l.Relation == IssueLinkFactory.Rels.IssueProcessor).ShouldNotBeNull()); "And it should have an issue link". f(() => home.Resources.FirstOrDefault(l => l.Relation == IssueLinkFactory.Rels.Issue).ShouldNotBeNull()); "And it should have an issues link". f(() => home.Resources.FirstOrDefault(l => l.Relation == IssueLinkFactory.Rels.Issues).ShouldNotBeNull()); "And it should have an search link". f(() => home.Resources.FirstOrDefault(l => l.Relation == IssueLinkFactory.Rels.SearchQuery).ShouldNotBeNull()); }
public void CreateHomeDocumentWithLotsOfHints() { var doc = new HomeDocument(); doc.AddResource <AboutLink>(l => { l.Target = new Uri("about", UriKind.Relative); l.AddHint <AllowHint>(h => h.AddMethod(HttpMethod.Get)); l.AddHint <FormatsHint>(h => h.AddMediaType("application/json")); l.AddHint <AcceptPostHint>(h => h.AddMediaType("application/vnd.tavis.foo+json")); l.AddHint <AcceptPreferHint>(h => h.AddPreference("handling")); }); var ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; var st = new StreamReader(ms); var s = st.ReadToEnd(); Assert.NotNull(s); }
public static void Run(RestController client, string RestHomeUri, string repositoryName, bool printResult, string groupName, string subGroupName, string userName) { // get repository resource HomeDocument home = client.Get <HomeDocument>(RestHomeUri, null); Feed <Repository> repositories = home.GetRepositories <Repository>(new FeedGetOptions { Inline = true, Links = true }); Repository repository = repositories.FindInlineEntry(repositoryName); //create or get group Group testGroup = CreateOrGetGroup(repository, groupName, printResult); //create or get group Group testSubGroup = CreateOrGetGroup(repository, subGroupName, printResult); //create or get user User testUser = CreateOrGetUser(repository, userName, printResult); //add user/sub-group to the parent group AddMembersOperations(repository, testGroup, testSubGroup, testUser, printResult); //remove user/sub-group from the parent group RemoveMembersOperations(repository, testGroup, testSubGroup, testUser, printResult); }
public static void Run(RestController client, string RestHomeUri, string filter, int itemsPerPage, bool pauseBetweenPages, string repositoryName, bool printResult) { HomeDocument home = client.Get <HomeDocument>(RestHomeUri, null); Feed <Repository> repositories = home.GetRepositories <Repository>(new FeedGetOptions { Inline = true, Links = true }); Repository repository = repositories.FindInlineEntry(repositoryName); Console.WriteLine(String.Format("Getting formats for filter '{0}' on repository '{1}', with page size {2}", filter, repository.Name, itemsPerPage)); // REST call to get the 1st page of formats for the specified filter FeedGetOptions options = new FeedGetOptions() { ItemsPerPage = itemsPerPage, Inline = true, IncludeTotal = true, Filter = String.IsNullOrEmpty(filter) ? null : filter }; Feed <Format> formats = repository.GetFormats <Format>(options); if (formats != null) { int totalResults = formats.Total; double totalPages = formats.PageCount; int docProcessed = 0; for (int i = 0; i < totalPages; i++) { Console.WriteLine("**************************** PAGE " + (i + 1) + " *******************************"); foreach (Entry <Format> obj in formats.Entries) { StringBuilder values = new StringBuilder(); Console.WriteLine(String.Format("Name: {0}, \tExtension: {1}, \tMime: {2}", obj.Content.GetPropertyString("name"), obj.Content.GetPropertyString("dos_extension"), obj.Content.GetPropertyString("mime_type"))); Console.WriteLine(values.ToString()); docProcessed++; } // REST call to get next page if (totalResults != docProcessed) { formats = formats.NextPage(); } Console.WriteLine("*******************************************************************"); Console.WriteLine("Page:" + (i + 1) + " Results: " + docProcessed + " out of " + totalResults + " Processed"); Console.WriteLine("*******************************************************************"); Console.WriteLine("\n\n"); if (pauseBetweenPages) { Console.WriteLine("Press 'q' to quit, 'g' to run to end, or any other key to run next page.."); ConsoleKeyInfo next = Console.ReadKey(); if (next.KeyChar.Equals('q')) { return; } if (next.KeyChar.Equals('g')) { pauseBetweenPages = false; } } } } if (printResult) { Console.WriteLine(formats == null ? "NULL" : formats.ToString()); } }
public static void Run(RestController client, string RestHomeUri, string repositoryName) { HomeDocument home = client.Get <HomeDocument>(RestHomeUri, null); Feed <Repository> repositories = home.GetRepositories <Repository>(new FeedGetOptions { Inline = true, Links = true }); Repository repository = repositories.FindInlineEntry(repositoryName); BatchCapabilities batchCapabilities = repository.GetBatchCapabilities(); Console.WriteLine("Batch capabilities for this repository:"); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(" - transactional or non-transactional? {0}", batchCapabilities.Transactions); Console.WriteLine(" - sequential or non-sequential? {0}", batchCapabilities.Sequence); Console.WriteLine(" - fail on error or continue on error? {0}", batchCapabilities.OnError); Console.WriteLine(" - all resources are batch-able except these [{0}] ", String.Join(",", batchCapabilities.NonBatchableResources.ToArray <string>())); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Press any key to continue batch test.."); Console.ReadKey(); Console.WriteLine(String.Format("\r\nPreparing data for the batch..")); User currentUser = repository.GetCurrentUser(new SingleGetOptions()); Console.WriteLine("\t - Fetched current user: "******"user_name")); Cabinet homeCabinet = currentUser.GetHomeCabinet(new SingleGetOptions()); Console.WriteLine("\t - Fetched home cabinet: " + homeCabinet.GetPropertyString("object_name")); // start a batch - create 1 folder & 1 document under home cabinet + get dql + create a new relation Console.WriteLine("\r\nReady to create a batch with 5 operations:"); string folderNamePrefix = "BatchTestFolder-"; Console.WriteLine("\t - (1) create a new folder under home cabinet with name prefix: " + folderNamePrefix); string docNamePrefix = "BatchTestDoc-"; Console.WriteLine("\t - (2) create a new document under home cabinet with name: " + docNamePrefix); string dql = "select * from dm_group"; Console.WriteLine("\t - (3) execute a dql query: " + dql); Console.WriteLine("\t - (4) get all relations"); Console.WriteLine("\t - (5) create a new cabinet with empty name (should fail)"); Console.WriteLine("Press any key to run batch.."); Console.ReadKey(); List <KeyValuePair <string, object> > dqlParams = new List <KeyValuePair <string, object> >(); dqlParams.Add(new KeyValuePair <string, object>("dql", dql)); string dqlUri = UriUtil.BuildUri(LinkRelations.FindLinkAsString(repository.Links, LinkRelations.DQL.Rel), dqlParams); Batch batch = Batch.CreateFromBuilder() .Description("a sample batch with 4 operations") .BatchSpec(new BatchSpec { Transactional = false, Sequential = false, FailOnError = false, ReturnRequest = false }) .AddOperation <Folder>( "batch-opt-1", homeCabinet, LinkRelations.FOLDERS.Rel, "POST", ObjectUtil.NewRandomFolder(folderNamePrefix, "dm_folder") ) .AddOperation <Document>( "batch-opt-2", homeCabinet, LinkRelations.DOCUMENTS.Rel, "POST", ObjectUtil.NewRandomDocument(docNamePrefix, "dm_document") ) .AddOperation( "batch-opt-3", dqlUri, "GET" ) .AddOperation( "batch-opt-4", homeCabinet, LinkRelations.RELATIONS.Rel, "GET" ) .AddOperation( "batch-opt-5", repository, LinkRelations.CABINETS.Rel, "POST", new Cabinet() ) .Build(); Batch result = repository.CreateBatch(batch); Console.WriteLine("\r\nPrinting batch result.."); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(String.Format(" - description [{0}]", result.Description)); Console.WriteLine(String.Format(" - owner [{0}]", result.Owner)); Console.WriteLine(String.Format(" - state [{0}]", result.State)); Console.WriteLine(String.Format(" - submitted [{0}]", result.Submitted)); Console.WriteLine(String.Format(" - started [{0}]", result.Started)); Console.WriteLine(String.Format(" - finished [{0}]", result.Finished)); foreach (BatchOperation operation in result.Operations) { Console.WriteLine(String.Format("\r\n - operation [{0}]", operation.Id)); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(String.Format("\t--> state [{0}]", operation.State)); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(String.Format("\t--> started [{0}]", operation.Started)); Console.WriteLine(String.Format("\t--> finished [{0}]", operation.Finished)); Console.WriteLine("\t--> response"); Console.WriteLine(String.Format("\t-----------> status [{0}]", operation.Response.Status)); if (operation.Response.HasError()) { Error error = operation.Response.GetError(); Console.WriteLine(String.Format("\t-----------> entity [{0}:{1}]", error.Code, error.Message)); } else { if (operation.Id.Equals("batch-opt-1") || operation.Id.Equals("batch-opt-2")) { PersistentObject po = operation.Response.GetObject <PersistentObject>(); Console.WriteLine(String.Format("\t-----------> entity [object of URI {0}]", LinkRelations.FindLinkAsString(po.Links, LinkRelations.SELF.Rel))); } else if (operation.Id.Equals("batch-opt-3") || operation.Id.Equals("batch-opt-4")) { Feed <PersistentObject> feed = operation.Response.GetObject <Feed <PersistentObject> >(); Console.WriteLine(String.Format("\t-----------> entity [feed with title {0} and entry count {1}]", feed.Title, feed.Entries.Count)); } } } Console.ForegroundColor = ConsoleColor.White; }
public static void Run(RestController client, string RestHomeUri, string query, int itemsPerPage, bool pauseBetweenPages, string repositoryName, bool printResult) { HomeDocument home = client.Get <HomeDocument>(RestHomeUri, null); Feed <Repository> repositories = home.GetRepositories <Repository>(new FeedGetOptions { Inline = true, Links = true }); Repository repository = repositories.FindInlineEntry(repositoryName); Console.WriteLine(string.Format("Running DQL query '{0}' on repository '{1}', with page size {2}", query, repository.Name, itemsPerPage)); // REST call to get the 1st page of the dql query Feed <PersistentObject> queryResult = repository.ExecuteDQL <PersistentObject>(query, new FeedGetOptions() { ItemsPerPage = itemsPerPage }); if (queryResult != null) { int totalResults = queryResult.Total; double totalPages = queryResult.PageCount; int docProcessed = 0; //int pageCount = queryResult.Entries.c for (int i = 0; i < totalPages && queryResult != null; i++) { Console.WriteLine("**************************** PAGE " + (i + 1) + " *******************************"); foreach (Entry <PersistentObject> obj in queryResult.Entries) { StringBuilder values = new StringBuilder(); Console.WriteLine(string.Format(" ID: {0} \t\tName: {1}", GetAttr(obj.Content, new string[] { "r_object_id" }), GetAttr(obj.Content, new string[] { "object_name", "user_name", "group_name", "name" }))); Console.WriteLine(values.ToString()); docProcessed++; } // REST call to get next page of the dql query if (totalResults != docProcessed) { queryResult = queryResult.NextPage(); } Console.WriteLine("*******************************************************************"); Console.WriteLine("Page:" + (i + 1) + " Results: " + docProcessed + " out of " + totalResults + " Processed"); Console.WriteLine("*******************************************************************"); Console.WriteLine("\n\n"); if (pauseBetweenPages) { Console.WriteLine("Press 'q' to quit, 'g' to run to end, or any other key to run next page.."); ConsoleKeyInfo next = Console.ReadKey(); if (next.KeyChar.Equals('q')) { return; } if (next.KeyChar.Equals('g')) { pauseBetweenPages = false; } } } } if (printResult) { Console.WriteLine(queryResult == null ? "NULL" : queryResult.ToString()); } }
public static void Run(RestController client, string RestHomeUri, string parent, int itemsPerPage, bool pauseBetweenPages, string repositoryName, bool printResult) { HomeDocument home = client.Get <HomeDocument>(RestHomeUri, null); Feed <Repository> repositories = home.GetRepositories <Repository>(new FeedGetOptions { Inline = true, Links = true }); Repository repository = repositories.FindInlineEntry(repositoryName); Console.WriteLine(String.Format("Getting types for parent '{0}' on repository '{1}', with page size {2}", parent, repository.Name, itemsPerPage)); // REST call to get the 1st page of the types FeedGetOptions options = new FeedGetOptions() { ItemsPerPage = itemsPerPage, Inline = true, IncludeTotal = true }; if (!String.IsNullOrEmpty(parent)) { options.SetQuery("parent-type", parent); } options.SetQuery("inherited", false); Feed <DmType> types = repository.GetTypes(options); if (types != null) { int totalResults = types.Total; double totalPages = types.PageCount; int docProcessed = 0; for (int i = 0; i < totalPages; i++) { Console.WriteLine("**************************** PAGE " + (i + 1) + " *******************************"); foreach (Entry <DmType> obj in types.Entries) { StringBuilder values = new StringBuilder(); Console.WriteLine(String.Format("Name: {0}, \t\tParent: {1}, \tNon-inherited Attrs: {2}", obj.Title, String.IsNullOrEmpty(obj.Content.Parent) ? "" : obj.Content.Parent.Substring(obj.Content.Parent.LastIndexOf("/") + 1), obj.Content.TypeProperties == null ? 0 : obj.Content.TypeProperties.Count)); Console.WriteLine(values.ToString()); docProcessed++; } // REST call to get next page of the types if (totalResults != docProcessed) { types = types.NextPage(); } Console.WriteLine("*******************************************************************"); Console.WriteLine("Page:" + (i + 1) + " Results: " + docProcessed + " out of " + totalResults + " Processed"); Console.WriteLine("*******************************************************************"); Console.WriteLine("\n\n"); if (pauseBetweenPages) { Console.WriteLine("Press 'q' to quit, 'g' to run to end, or any other key to run next page.."); ConsoleKeyInfo next = Console.ReadKey(); if (next.KeyChar.Equals('q')) { return; } if (next.KeyChar.Equals('g')) { pauseBetweenPages = false; } } } } if (printResult) { Console.WriteLine(types == null ? "NULL" : types.ToString()); } }