Exemplo n.º 1
0
        public void Should_Not_Send_Http_Request_If_Cancellation_Is_Requested()
        {
            // Given
            var searchQuery = new SearchQuery {
                InTitle = "Wrido"
            };

            var httpHandler  = Substitute.ForPartsOf <FakeHttpHandler>();
            var queryBuilder = Substitute.For <IQueryStringBuilder>();
            var serializer   = Substitute.For <JsonSerializer>();
            var logger       = Substitute.For <ILogger>();

            httpHandler.Send(Arg.Any <HttpRequestMessage>(), Arg.Any <CancellationToken>());

            var client = new StackExchangeClient(new HttpClient(httpHandler)
            {
                BaseAddress = new Uri("http://localhost")
            }, queryBuilder, serializer, logger);

            // When
            client
            .SearchAsync(searchQuery, new CancellationToken(canceled: true))
            .ContinueWith(t =>
            {
                // Then
                Assert.True(t.IsCanceled);
                Assert.Empty(httpHandler.ReceivedCalls());
            })
            .GetAwaiter()
            .GetResult();
        }
Exemplo n.º 2
0
        public async Task <IPage> ParseDataAndGetPageAsync()
        {
            IPage       page   = null;
            var         client = new StackExchangeClient(k_ClientID, k_Key, Scopes.NoExpiry);
            IList <int> ids    = new List <int> {
                m_ID
            };

            var query = await client.Questions.GetAsync(
                site : "stackoverflow",
                filter : "!)5d3yYdB0grnr6gO7E9oMFDnlZMk",
                ids : ids);

            if (query.Items != null)
            {
                Question question = query.Items.First();

                page = new StackoverflowPage
                {
                    GoogleResultIndex = GoogleResultIndex,
                    WebsiteName       = "Stackoverflow",
                    Url              = "https://stackoverflow.com/questions/" + m_ID,
                    Subject          = HttpUtility.HtmlDecode(question.Title),
                    Date             = Utils.UnixTimeStampToDateTime(question.CreationDate),
                    Score            = question.Score,
                    FavoriteCount    = question.FavoriteCount,
                    ViewCount        = question.ViewCount,
                    IsAcceptedAnswer = question.IsAnswered,
                    AnswerCount      = question.AnswerCount
                };
            }

            return(page);
        }
 public void GetUserById()
 {
     var client = new StackExchangeClient(ApiKey, "http://api.stackapps.com/1.0");
     var response = client.GetUserById(14, null, null, null, null, null, null, null, null);
     Assert.AreEqual(1, response.Items.Count);
     Assert.AreEqual("df4a7fbd8a054fd6193ca0ee62952f1f", response.Items[0].EmailHash);
 }
Exemplo n.º 4
0
 public void GetImplicitAuthenticationUrl_ThrowsIfAnonymous()
 {
     Assert.Throws <InvalidOperationException>(() =>
     {
         var client = new StackExchangeClient();
         client.GetImplicitAuthenticationUrl();
     });
 }
Exemplo n.º 5
0
 public void TryImplicitAuthentication_ThrowsIfAnonymous()
 {
     Assert.Throws <InvalidOperationException>(() =>
     {
         var client = new StackExchangeClient();
         client.TryImplicitAuthentication(new Uri("https://www.example.com/"));
     });
 }
Exemplo n.º 6
0
        public async Task Should_Throw_Argument_Exception_If_Both_InTitle_And_Tag_Are_Not_Set()
        {
            // Given
            var httpClient   = Substitute.For <HttpClient>();
            var queryBuilder = Substitute.For <IQueryStringBuilder>();
            var serializer   = Substitute.For <JsonSerializer>();
            var logger       = Substitute.For <ILogger>();

            var client      = new StackExchangeClient(httpClient, queryBuilder, serializer, logger);
            var searchQuery = new SearchQuery
            {
                InTitle = null,
                Tagged  = Enumerable.Empty <string>()
            };

            // When
            // Then
            await Assert.ThrowsAsync <ArgumentException>(() => client.SearchAsync(searchQuery));
        }
Exemplo n.º 7
0
        public async Task Should_Return_Questions_Retrieved_From_Api_Endpoint()
        {
            // Given
            var questions = new PaginationResult <Question>
            {
                Items = new List <Question>
                {
                    new Question {
                        Title = "Regexp for match second numeric values"
                    },
                    new Question {
                        Title = "How to use regexp for finding patterns in strings?"
                    }
                },
            };
            var httpHandler  = Substitute.ForPartsOf <FakeHttpHandler>();
            var queryBuilder = Substitute.For <IQueryStringBuilder>();
            var serializer   = new JsonSerializer();
            var logger       = Substitute.For <ILogger>();

            queryBuilder
            .Build(Arg.Any <SearchQuery>())
            .Returns(string.Empty);

            httpHandler
            .Send(Arg.Any <HttpRequestMessage>(), Arg.Any <CancellationToken>())
            .Returns(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new JsonContent(questions, serializer)
            });

            var client = new StackExchangeClient(new HttpClient(httpHandler)
            {
                BaseAddress = new Uri("http://localhost")
            }, queryBuilder, serializer, logger);

            // When
            var result = await client.SearchAsync(new SearchQuery { InTitle = "Wrido" });

            // Then
            Assert.Equal(questions.Items[0].Title, result[0].Title);
            Assert.Equal(questions.Items[1].Title, result[1].Title);
        }
Exemplo n.º 8
0
        public async Task Should_Send_Http_Request_With_Query_Parameter_From_Provider()
        {
            // Given
            var searchQuery = new SearchQuery {
                InTitle = "Wrido"
            };
            var expectedQueryParamter = $"/id={Guid.NewGuid()}";

            var httpHandler  = Substitute.ForPartsOf <FakeHttpHandler>();
            var queryBuilder = Substitute.For <IQueryStringBuilder>();
            var serializer   = Substitute.For <JsonSerializer>();
            var logger       = Substitute.For <ILogger>();

            queryBuilder
            .Build(searchQuery)
            .Returns(expectedQueryParamter);

            httpHandler
            .Send(Arg.Any <HttpRequestMessage>(), Arg.Any <CancellationToken>())
            .Returns(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(string.Empty)
            });

            var client = new StackExchangeClient(new HttpClient(httpHandler)
            {
                BaseAddress = new Uri("http://localhost")
            }, queryBuilder, serializer, logger);

            // When
            await client.SearchAsync(searchQuery);

            // Then
            var outgoingRequest = httpHandler.ReceivedCalls().First().GetArguments()[0] as HttpRequestMessage;

            Assert.NotNull(outgoingRequest);
            Assert.Equal(outgoingRequest.RequestUri.PathAndQuery, expectedQueryParamter);
        }
Exemplo n.º 9
0
        public Dingo(BotConfig config)
        {
            Instance      = this;
            Configuration = config;
            Logger        = new Logger("BOT");

            Logger.Log("Creating Stack Exchange Client");
            Redis = new StackExchangeClient(config.Redis.Address, config.Redis.Database, Logger.CreateChild("REDIS"));
            Namespace.SetRoot(config.Redis.Prefix);

            Logger.Log("Creating new Bot");
            Discord = new DiscordClient(new DiscordConfiguration()
            {
                Token = config.Token
            });

            Logger.Log("Creating Instances");
            ReplyManager = new ReplyManager(this, Logger.CreateChild("REPLY"));
            SiegeManager = new SiegeManager(this, Logger.CreateChild("SIEGE"));
            LastManager  = new LastManager(this, Logger.CreateChild("LAST"));

            Logger.Log("Creating Command Next");
            var deps = new ServiceCollection()
                       .AddSingleton(this)
                       .BuildServiceProvider(true);

            CommandsNext = Discord.UseCommandsNext(new CommandsNextConfiguration()
            {
                PrefixResolver = ResolvePrefix, Services = deps
            });
            CommandsNext.RegisterConverter(new QueryConverter());
            CommandsNext.RegisterConverter(new CommandQueryArgumentConverter());
            CommandsNext.RegisterCommands(Assembly.GetExecutingAssembly());
            CommandsNext.CommandErrored += HandleCommandErrorAsync;

            this.Discord.ClientErrored += async(error) => await LogException(error.Exception);
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            var client      = new StackExchangeClient("yourApiKey");
            var queryString = new AnswerFilters()
            {
                //PageSize = 1,
                //Page = 1,
                //Sort = Sort.Votes
            };

            var answers = client.Answers.GetAllAnswers(queryString);
            var ids     = new List <string>()
            {
                "44164379", "6841479"
            };
            //var answers = client.Answers.GetAnswerByIds(ids, queryString);
            //var answers = client.Answers.GetCommentsOnAnswers(ids, queryString);
            //var answers = client.Answers.GetQuestionByAnswerIds(ids, queryString);

            var badgeFilter = new BadgeFilters()
            {
                Sort = Enums.BadgeSort.Name
            };
            //var badges = client.Badges.GetAllBadges(badgeFilter);

            var batchIds = new List <string>()
            {
                "4600", "2600", "26"
            };
            //var getBadgesByIds = client.Badges.GetNonTaggedBadges(batchIds, badgeFilter);
            //var getBadgesByIds = client.Badges.GetBadgesByIds(batchIds, badgeFilter);
            //var getBadgesByIds = client.Badges.GetRecentlyAwardedBadges(badgeFilter);

            //	var getBadgesByIds = client.Badges.GetRecentlyAwardedBadgesByIds(batchIds, badgeFilter);

            //var getBadgesByIds = client.Badges.GetAllTaggedBadges(badgeFilter);
            //Console.WriteLine(JsonConvert.SerializeObject(getBadgesByIds));

            var commentFilter = new CommentFilter()
            {
                Sort = Enums.CommentSort.Creation
            };
            //var comments = client.Comments.GetAllComments(commentFilter);

            var commentIds = new List <string>()
            {
                "102165885", "102166303"
            };
            //var comments = client.Comments.GetCommentsOnAnswers(commentIds,commentFilter);
            //Console.WriteLine(JsonConvert.SerializeObject(comments));

            var postFilter = new PostFilter()
            {
                Sort = Enums.PostSort.Creation
            };
            //var posts = client.Posts.GetAllPosts(postFilter);

            var postIds = new List <string>()
            {
                "57871119", "57698255"
            };

            //var postsByIds = client.Posts.GetAllPostsByIds(postIds, postFilter);


            //var postsByIds = client.Posts.GetCommentsOnPosts(postIds, postFilter);

            //	var revisionByIds = client.Posts.GetRevisionsByIds(postIds, postFilter);

            //var suggestedEdits = client.Posts.GetSuggestedEdits(postIds, new SuggestedEditFilter()
            //{
            //	Sort = PostSort.Creation
            //});

            //Console.WriteLine(JsonConvert.SerializeObject(suggestedEdits));

            var questionFilter = new QuestionFilters()
            {
                Sort = Enums.Sort.Activity
            };

            var qIds = new List <string>()
            {
                "58054349", "58038242"
            };

            //var result = client.Questions.GetAllQuestions(questionFilter);
            //var result = client.Questions.GetQuestionsByIds(qIds,questionFilter);
            //var result = client.Questions.GetAnswersByQuestionIds(qIds,questionFilter);
            //var result = client.Questions.GetCommentsByQuestionIds(qIds,questionFilter);
            //var linked = client.Questions.GetLinkedQuestions(qIds, questionFilter);
            //var related = client.Questions.GetRelatedQuestions(qIds, questionFilter);
            //var getFeaturedQuestions = client.Questions.GetFeaturedQuestions(questionFilter);
            //var getQuestionsWithNoAnswers = client.Questions.GetQuestionsWithNoAnswers(questionFilter);
            //var getUnansweredQuestions = client.Questions.GetUnansweredQuestions(questionFilter);

            var suggestedEditFilter = new SuggestedEditFilter()
            {
                Sort = Enums.Sort.Creation
            };

            var sEditIds = new List <string>()
            {
                "4509686"
            };

            //var result = client.SuggestedEdits.GetAllSuggestedEdits(suggestedEditFilter);
            //var result = client.SuggestedEdits.GetSuggestedEditsByIds(sEditIds, suggestedEditFilter);
            var tagFilter  = new TagFilter();
            var listOfTags = new List <string>()
            {
                "azure-functions", "azure"
            };

            //var tags = client.Tags.GetAllTags(tagFilter);
            //var tags = client.Tags.GetTagsByNames(listOfTags,tagFilter);
            //var tags = client.Tags.GetModeratorOnlyTags(tagFilter);
            //var tags = client.Tags.GetAllTagSynonyms(tagFilter);
            //var tags = client.Tags.GetFrequentlyAskedQuestions(listOfTags);
            //var tags = client.Tags.GetRelatedTags(listOfTags);
            //var tags = client.Tags.GetSynonymsForTags(listOfTags,tagFilter);
            //var tags = client.Tags.GetTopAnswerersPosts("azure-functions","all_time");
            var tags = client.Tags.GetTopAskers("azure-functions", "all_time");

            Console.ReadKey();
        }
Exemplo n.º 11
0
 public void Setup()
 {
     Client = Substitute.For <StackExchangeClient>("someKey");
 }
Exemplo n.º 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Endpoint"/> class.
 /// </summary>
 /// <param name="client">The <see cref="StackExchangeClient"/> object to perform requests via.</param>
 /// <exception cref="ArgumentNullException">Thrown if the specified <see cref="StackExchangeClient"/> object is <c>null</c>.</exception>
 protected Endpoint(StackExchangeClient client)
 {
     this.client = client ?? throw new ArgumentNullException(nameof(client));
 }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            var client      = new StackExchangeClient("U4DMV*8nvpm3EOpvf69Rxw((");
            var queryString = new AnswerFilters()
            {
                PageSize = 1,
                Page     = 1,
                Sort     = Sort.Votes
            };
            //var answers = client.Answers.GetAllAnswers(queryString);
            var ids = new List <string>()
            {
                "44164379", "6841479"
            };
            //var answers = client.Answers.GetAnswerByIds(ids, queryString);
            //var answers = client.Answers.GetCommentsByIds(ids, queryString);
            //var answers = client.Answers.GetQuestionByAnswerIds(ids, queryString);

            var badgeFilter = new BadgeFilters()
            {
                Sort = BadgeSort.Name
            };
            //var badges = client.Badges.GetAllBadges(badgeFilter);

            var batchIds = new List <string>()
            {
                "4600", "2600", "26"
            };

            //var getBadgesByIds = client.Badges.GetBadgesByIds(batchIds, badgeFilter);
            //var getBadgesByIds = client.Badges.GetRecentlyAwardedBadges(badgeFilter);

            //var getBadgesByIds = client.Badges.GetRecentlyAwardedBadgesByIds(batchIds, badgeFilter);

            //var getBadgesByIds = client.Badges.GetAllTaggedBadges(badgeFilter);
            //Console.WriteLine(JsonConvert.SerializeObject(getBadgesByIds));

            var commentFilter = new CommentFilter()
            {
                Sort = CommentSort.Creation
            };
            //var comments = client.Comments.GetAllComments(commentFilter);

            var commentIds = new List <string>()
            {
                "102165885", "102166303"
            };
            //var comments = client.Comments.GetCommentsByIds(commentIds,commentFilter);
            //Console.WriteLine(JsonConvert.SerializeObject(comments));

            var postFilter = new PostFilter()
            {
                Sort = PostSort.Creation
            };
            //var posts = client.Posts.GetAllPosts(postFilter);

            var postIds = new List <string>()
            {
                "57871119", "57698255"
            };

            var postsByIds = client.Posts.GetAllPostsByIds(postIds, postFilter);


            //var postsByIds = client.Posts.GetCommentsOnPosts(postIds, postFilter);

            //var revisionByIds = client.Posts.GetRevisionsByIds(postIds, postFilter);

            // var suggestedEdits = client.Posts.GetSuggestedEdits(postIds, new SuggestedEditFilter()
            // {
            //  Sort = Sort.Activity
            // });

            //Console.WriteLine(JsonConvert.SerializeObject(suggestedEdits));
            Console.ReadKey();
        }