📜 ⬆️ ⬇️

Working with the VKontakte C # API

Greetings to you, dear reader! The article describes the process of creating the simplest WindowsForms application that will work with the VKontakte social network API.

Application Tasks:

  1. Get User Token and perform all further requests using it.
  2. Get a user ID to login.
  3. Display information about the user with the entered ID.

UPD: Repository on GitHub
UPD (09/26/2018): Added the 'version' parameter to queries. Added auto-complete application ID when receiving a token. Added warning.
Warning: API version used is 5.52. On the 09/26/2018 the latest is 5.85. Starting with API version 5.8, the program will not work, since objects, not numbers, are returned in the 'city' and 'country' fields.
')
For convenience, I will use two libraries:


The first thing to do is get the application ID. To do this, go to VkDevelopers , create a new Standalone application, go to its settings and copy ApplicationID.

You can start creating an application, go to VisualStudio and create a new WindowsForms application.

We connect libraries
The JSON.Net library is connected using the package manager console, just enter the command:
Install-Package Newtonsoft.Json

To connect the xNet library, we need to go here , download xNet.dll and add it to the project using the link manager.

After connecting the libraries, we create two forms: MainForm (You can use the standard Form1) and AuthorizationForm. Forms look like this:

Mainform


AuthorizationForm
This form consists of a WebBrowser element with the Name = GetToken parameter.

Create another class file. Let's call it VkAPI.

Start writing code.


To begin with, we implement getting a token. To do this, create a handler on the Button_GetToken button in the MainForm:

private void Button_GetToken_Click(object sender, EventArgs e) { AuthorizationForm GetToken = new AuthorizationForm(); GetToken.ShowDialog(); } 

 using System; using System.Windows.Forms; using System.IO; namespace VkAPITutorial { public partial class AuthorizationForm : Form { public AuthorizationForm() { InitializeComponent(); } private void AuthorizationForm_Load(object sender, EventArgs e) { GetToken.DocumentCompleted += GetToken_DocumentCompleted; GetToken.Navigate("https://oauth.vk.com/authorize?client_id="+ VkAPI.__APPID +"&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends&response_type=token&v=5.52"); } private void GetToken_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (GetToken.Url.ToString().IndexOf("access_token=") != -1) { GetUserToken(); } } private void GetUserToken() { char[] Symbols = { '=', '&' }; string[] URL = GetToken.Url.ToString().Split(Symbols); File.WriteAllText("UserInf.txt", URL[1] + "\n"); File.AppendAllText("UserInf.txt", URL[5]); this.Visible = false; } private void GetToken_DocumentCompleted_1(object sender, WebBrowserDocumentCompletedEventArgs e){} } } 

Now let's sort everything in order:

When you click on the button, the AuthorizationForm opens with a Web browser, the link opens in the browser:
  https://oauth.vk.com/authorize?client_id=ApplicationID&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends&response_type=token&v=5.52 

The client_id parameter is the application ID that we received at the beginning of the article . After the scope parameter lists the permissions that we request, a full list of permissions can be found here .

When refreshing the page, we check if the access_token is in the address, if so, we split the address and enter it into the token file and the user ID that has logged in. After that, AuthorizationForm closes. Token received!

Now you can begin to receive and display information about the user. We need to get a first name, a last name, a city, a country, and a photo. You can receive them by requests, separately, but it is better to receive them in one request.

Edit the VkAPI.cs file:

 using System.Collections.Generic; using xNet; using Newtonsoft.Json; namespace VkAPITutorial { class VkAPI { public const string __APPID = "APPLICATION_ID"; //ID  private const string __VKAPIURL = "https://api.vk.com/method/"; //   private string _Token; //,    public VkAPI(string AccessToken) { _Token = AccessToken; } public Dictionary<string, string> GetInformation(string UserId, string[] Fields) //       ID { HttpRequest GetInformation = new HttpRequest(); GetInformation.AddUrlParam("user_ids", UserId); GetInformation.AddUrlParam("access_token", _Token); GetInformation.AddUrlParam("version", "5.52"); string Params = ""; foreach (string i in Fields) { Params += i + ","; } Params = Params.Remove(Params.Length - 1); GetInformation.AddUrlParam("fields", Params); string Result = GetInformation.Get(__VKAPIURL + "users.get").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary<string, string> Dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(Result); return Dict; } public string GetCityById(string CityId) // ID    { HttpRequest GetCityById = new HttpRequest(); GetCityById.AddUrlParam("city_ids", CityId); GetCityById.AddUrlParam("access_token", _Token); GetCityById.AddUrlParam("version", "5.52"); string Result = GetCityById.Get(__VKAPIURL + "database.getCitiesById").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary<string, string> Dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(Result); return Dict["name"]; } public string GetCountryById(string CountryId) // ID    { HttpRequest GetCountryById = new HttpRequest(); GetCountryById.AddUrlParam("country_ids", CountryId); GetCountryById.AddUrlParam("access_token", _Token); GetCountryById.AddUrlParam("version", "5.52"); string Result = GetCountryById.Get(__VKAPIURL + "database.getCountriesById").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary<string, string> Dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(Result); return Dict["name"]; } } } 

And MainForm:

 using System; using System.Windows.Forms; using System.Collections.Generic; using System.IO; namespace VkAPITutorial { public partial class MainForm : Form { VkAPI _ApiRequest; private string _Token; //,    private string _UserId; //ID  private Dictionary<string, string> _Response; //   public MainForm() { InitializeComponent(); } private void Button_GetToken_Click_1(object sender, EventArgs e) { AuthorizationForm GetToken = new AuthorizationForm(); GetToken.ShowDialog(); } private void MainForm_Load(object sender, EventArgs e) { try { StreamReader ControlInf = new StreamReader("UserInf.txt"); _Token = ControlInf.ReadLine(); _UserId = ControlInf.ReadLine(); ControlInf.Close(); if (_Token != null) { _ApiRequest = new VkAPI(_Token); string[] Params = { "city", "country", "photo_max" }; _Response = _ApiRequest.GetInformation(_UserId, Params); if (_Response != null) { User_ID.Text = _UserId; User_Photo.ImageLocation = _Response["photo_max"]; User_Name.Text = _Response["first_name"]; User_Surname.Text = _Response["last_name"]; User_Country.Text = _ApiRequest.GetCountryById(_Response["country"]); User_City.Text = _ApiRequest.GetCityById(_Response["city"]); Button_GetToken.Visible = false; } } } catch { } } private void Button_GetInformation_Click_1(object sender, EventArgs e) { try { StreamReader ControlInf = new StreamReader("UserInf.txt"); _Token = ControlInf.ReadLine(); ControlInf.Close(); _ApiRequest = new VkAPI(_Token); _UserId = User_ID.Text; string[] Params = { "city", "country", "photo_max" }; _Response = _ApiRequest.GetInformation(_UserId, Params); if (_Response != null) { User_ID.Text = _UserId; User_Photo.ImageLocation = _Response["photo_max"]; User_Name.Text = _Response["first_name"]; User_Surname.Text = _Response["last_name"]; User_Country.Text = _ApiRequest.GetCountryById(_Response["country"]); User_City.Text = _ApiRequest.GetCityById(_Response["city"]); Button_GetToken.Visible = false; } } catch { } } } } 

Let's sort the code:

At startup, the application tries to read the token and user ID:

 StreamReader ControlInf = new StreamReader("UserInf.txt"); _Token = ControlInf.ReadLine(); _UserId = ControlInf.ReadLine(); ControlInf.Close(); 

If the reading is successful, the application tries to make a request for information about the user (Check Token for validity):

 _ApiRequest = new VkAPI(_Token); string[] Params = { "city", "country", "photo_max" }; _Response = _ApiRequest.GetInformation(_UserId, Params); 

If the request is successful, then all the fields in the form are filled in and the GetToken button becomes inactive:

 User_ID.Text = _UserId; User_Photo.ImageLocation = _Response["photo_max"]; User_Name.Text = _Response["first_name"]; User_Surname.Text = _Response["last_name"]; User_Country.Text = _ApiRequest.GetCountryById(_Response["country"]); User_City.Text = _ApiRequest.GetCityById(_Response["city"]); Button_GetToken.Visible = false; 

Otherwise, the GetToken button is active, and when you click on it, the function is triggered:

  private void Button_GetInformation_Click(object sender, EventArgs e) { try { StreamReader ControlInf = new StreamReader("UserInf.txt"); _Token = ControlInf.ReadLine(); ControlInf.Close(); _ApiRequest = new VkAPI(_Token); _UserId = User_ID.Text; string[] Params = { "city", "country", "photo_max" }; _Response = _ApiRequest.GetInformation(_UserId, Params); if (_Response != null) { User_ID.Text = _UserId; User_Photo.ImageLocation = _Response["photo_max"]; User_Name.Text = _Response["first_name"]; User_Surname.Text = _Response["last_name"]; User_Country.Text = _ApiRequest.GetCountryById(_Response["country"]); User_City.Text = _ApiRequest.GetCityById(_Response["city"]); Button_GetToken.Visible = false; } } catch { } } 

Now let's figure out how a GET request occurs. First a variable is created:

 HttpRequest GetInformation = new HttpRequest(); 

Next, the parameters are entered into it:

 GetInformation.AddUrlParam("user_ids", UserId); GetInformation.AddUrlParam("access_token", _Token); GetInformation.AddUrlParam("version", "5.52"); string Params = ""; foreach (string i in Fields) { Params += i + ","; } Params = Params.Remove(Params.Length - 1); GetInformation.AddUrlParam("fields", Params); 

And a GET request is made:

 string Result = GetInformation.Get(__VKAPIURL + "users.get").ToString(); 

The result is truncated to a string that can be converted:

 Result = Result.Substring(13, Result.Length - 15); 

There is a conversion of json into the dictionary:

 Dictionary<string, string> Dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(Result); 

Our little app is ready! Thank you all for your attention! I am ready to listen to your comments.

Source: https://habr.com/ru/post/314518/


All Articles