Click here to Skip to main content
15,899,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Okay so I'm still quite new to coding and mostly only knows the basics. I have never worked with API. I'm trying to make a program that gets the number of subs from PewDiePie and Cocomelon and compare them.

C#
using System;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Threading;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace PewdiepieVsCoco
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var len = args?.Length;

                if (len == null || len.Value == 0)
                {
                    PrintHelp();
                    return;
                }

                var pdpSubCount = args[0];
                var pdpSub = GetPDPSubcount(pdpSubCount).Result;

                PrintPDPResult(pdpSub);

            }

            catch (AggregateException agg)
            {
                foreach (var e in agg.Flatten().InnerExceptions)
                    Console.WriteLine(e.Message);
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }

        private static async Task<dynamic> GetPDPSubcount(string pdpSubCount)
        {
            var parameters = new Dictionary<String, String>
            {
                ["key"] = ConfigurationManager.AppSettings["APIKey"],
                ["channelId"] = "UC-lHJZR3Gqxm24_Vd_AJ5Yw",
                ["part"] = "statistics",
                ["forUsername"] = "PewDiePie",
                ["fields"] = "items/statistics(subscriberCount)"
            };

            var baseUrl = "https://www.googleapis.com/youtube/v3/channels";
            var fullUrl = MakeUrlWithQuery(baseUrl, parameters);

            var pdpSub =  await new HttpClient().GetStringAsync(fullUrl);
            if (pdpSub != null)
            {
                //Does the thing
                return JsonConvert.DeserializeObject(pdpSubCount);
            }

            return default(dynamic);
        }

        private static string MakeUrlWithQuery(string baseUrl, 
            IEnumerable<KeyValuePair<string, string>> parameters)
        {
            if (string.IsNullOrEmpty(baseUrl))
                throw new ArgumentException(nameof(baseUrl));

            if (parameters == null || parameters.Count() == 0)
                return baseUrl;

            return parameters.Aggregate(baseUrl,
                (accumulated, kvp) => string.Format($"{accumulated}{kvp.Value}&"));

        }

        private static void PrintPDPResult(dynamic pdpSub)
        {
            Console.WriteLine($"PewDiePie currently have: {pdpSub} subscribers");//insert subs
        }


        private static void PrintHelp()
        {
            Console.WriteLine("The war is on!");
            Thread.Sleep(500);
            Console.WriteLine("PewDiePie Vs Cocomelon – Nursery Rhymes");
            Thread.Sleep(500);
        }
    }
}


Here is the code, I have followed what an Indian dude did in a YT video so some things I don't know what do but I have an idea on what's going on.

What I have tried:

I have no idea what is wrong so i dont know where to begin
Posted
Updated 5-Jun-20 16:40pm
v2
Comments
Richard MacCutchan 6-Jun-20 3:58am    
"I have no idea what is wrong so i dont know where to begin"
Stop wasting your time with code that you do not understand. Get a book or find a good online tutorial and spend time learning C# and the basic .NET classes.

Well, it comes down to learning how to debug - stepping through a program often line by line, seeing where an error occurs, then looking at variable contents to see if they match what you expected

So, set a breakpoint on this line
var baseUrl = "https://www.googleapis.com/youtube/v3/channels";
then start single stepping using F10 'Step Over' and F11 'Step Into' (functions etc) until you find where it's going wrong - as you find area(s) of concern, you may need to add logging/diagnostics to help you 'see' state/what's going on - often a Console.WriteLine etc with some text & variable will give you a pointer

btw, I suggested setting a breakpoint on that line, because at some stage, execution would 'skip' to that routine & through it, if you didnt set a breakpoint you'd likely miss the fun

This is something we can give you guidelines on, but ultimately, we cant do for you, since it's your code on your machine. By large, we out here write functions and tests for them as we go, so we dont get 'caught out' by nasty surprises
 
Share this answer
 
Comments
Patrice T 5-Jun-20 22:27pm    
+5
Quote:
I have followed what an Indian dude did in a YT video so some things I don't know what do but I have an idea on what's going on.

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

Debugging C# Code in Visual Studio - YouTube[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900