Для начала работы с консолью необходимо получить ее дескриптор.
Функция получения дескриптора стандартного устройства ввода, вывода или ошибки в зависимости от переданного константного параметра:
HANDLE WINAPI GetStdHandle(__in DWORD nStdHandle);
nStdHandle может принимать значения
- STD_INPUT_HANDLE = -10; // устройство ввода
- STD_OUTPUT_HANDLE = -11; // устройство вывода
- STD_ERROR_HANDLE = -12; // ошибка
Использование русского языка в консоли с помощью API
Для указания кодовой страницы используются функции
- Кодовая страница консоли вывода
BOOL WINAPI SetConsoleOutputCP(UINT wCodePageID); - Кодовая страница консоли ввода
BOOL WINAPI SetConsoleCP(UINT wCodePageID);
где wCodePageID — номер кодовой страницы.
Для перекодировки на русский язык используется кодовая страница wCodePageID=1251 .
Для перекодировки русского текста, введенного в Win-коде также может использоваться функция
VK API docs.search поиск документов вконтакте апи
BOOL WINAPI CharToOem (LPCTSTR lpszSrc, LPSTR lpszDst)
- lpszSrc – указатель на строку-источник;
- lpszDst/strong> – указатель на строку-приемник
Возвращаемое значение 1 в случае успешной перекодировки.
Чтение/запись данных в консоль/файл
Для чтения и записи данных в консоль используются функции
BOOL WINAPI ReadFile(
_In_ HANDLE hFile,
_Out_ LPVOID lpBuffer,
_In_ D WORD nNumberOfBytesToRead,
_Out_ LP D WORD lpNumberOfBytesRead,
_Inout_ LPOVERLAPPED lpOverlapped);
BOOL WINAPI WriteFile(
_In_ HANDLE hFile,
_In_ LPCVOID lpBuffer,
_In_ D WORD nNumberOfBytesToWrite,
_Out_ LP D WORD lpNumberOfBytesWritten,
_Inout_ LPOVERLAPPED lpOverlapped);
В случае успешного завершения функции возвращают ненулевое значение.
Аргументы функций
- hFile -дескриптор файла/консоли. Файл/консоль должен иметь доступ для чтения для функции ReadFile() и доступ для записи для функции WriteFile() .
- lpBuffer — указатель на буфер (строку) для чтения/записи данных.
- nNumberOfBytesToWrite — число байтов, которые будут записаны в файл.
- lpNumberOfBytesWritten — указатель на переменную, которая получает число считанных/записанных байтов.
- lpOverlapped — указатель на структуру OVERLAPPED , которая используется в операциях асинхронного ввода-вывода (например, получение данных по интерфейсу связи). Для синхронного ввода-вывода данный указатель имеет значение NULL .
Установка заголовка окна консоли
Функция установки заголовка окна консоли
BOOL WINAPI SetConsoleTitle(__in LPCTSTR lpConsoleTitle);
lpConsoleTitle – указатель на строку имени консоли с завершающим нуль-символом
Установка цвета символов и фона в консоли
Цвет символов и фона задается с помощью констант, определяющих тетрады символов.
Как получить токен ВК | Как узнать токен Api Vk приложения для выполнения действий по api
Цвет символов
Каждая тетрада, определяющая цвет символов или фона, представляет собой значение от 0 до 15, задаваемая логической суммой соответствующих констант:
Например, цвет символов с кодом 13 задается как
FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY .
Функция определения атрибутов вводимых символов в окне консоли
BOOL WINAPI SetConsoleTextAttribute(
__in HANDLE hConsoleOutput,
__in WORD wAttributes);
- hConsoleOutput – дескриптор буфера консоли вывода;
- wAttributes – цвет букв и фона, получаемый путем комбинации констант
Функция, задающая цвет фона консоли(путем закрашивания фона отдельных символов)
BOOL WINAPI FillConsoleOutputAttribute(
__in HANDLE hConsoleOutput,
__in WORD wAttribute,
__in D WORD nLength,
__in COORD dwWriteCoord,
__out LP D WORD lpNumberOfAttrsWritten);
- hConsoleOutput – дескриптор буфера вывода консоли;
wAttribute – атрибут цвета фона символа в консоли; - nLength – количество ячеек символов, фон которых устанавливается заданным цветом;
- dwWriteCoord – координаты первой закрашиваемой ячейки;
- lpNumberOfAttrsWritten – указатель на идентификатор, в который записывается количество реально закрашенных ячеек.
Для того чтобы изменить цвет всего окна консоли необходимо задать цвет символов, количество которых определяется размером окна консоли. Размер стандартного окна консоли 80×25 = 2000 символов.
Установка позиции курсора
Функция установки позиции курсора в окне консоли
BOOL WINAPI SetConsoleCursorPosition(
__in HANDLE hConsoleOutput,
__in COORD dwCursorPosition);
hConsoleOutput – дескриптор буфера вывода консоли;
dwCursorPosition – структура координат COORD, определяющая позицию курсора.
Структура координат представляет собой
struct COORD
short X;
short Y;
>;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include
int main()
D WORD l;
COORD point;
point.X = 0; point.Y = 0;
HANDLE hout = GetStdHandle( STD_OUTPUT_ HANDLE );
HANDLE hin = GetStdHandle( STD_INPUT_ HANDLE );
char title[] = «Консольная программа» ;
CharToOem (title, title);
SetConsoleTitle(title);
SetConsoleOutputCP(1251);
SetConsoleTextAttribute(hout, FOREGROUND_RED | FOREGROUND_INTENSITY);
FillConsoleOutputAttribute(hout, 0, 2000, point, // очистка экрана
for ( int y = 0; y < 16; y++) point.Y = y;
FillConsoleOutputAttribute(hout, y SetConsoleCursorPosition(hout, point);
>
char c;
ReadFile(hin, l, NULL );
return 0;
>
Результат выполнения
Примечание: для корректной компиляции программы необходимо изменить тип кодировки проекта на многобайтовую.
Комментариев к записи: 2
Visual C++ 2008 Express. На строчке HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE); Вылетает ошибка: «error C2275: HANDLE: недопустимое использование этого типа в качестве выражения c:program filesmicrosoft sdkswindowsv6.0aincludewinnt.h(402): см. объявление ‘HANDLE’». Дальше (поскольку не смог объявить hout) валом валят другие обишки (C2275 повторяется ещё раз): error C2146: синтаксическая ошибка: отсутствие «;» перед идентификатором «hout» error C2065: hout: необъявленный идентификатор warning C4047: =: ‘int’ отличается по уровням косвенного обращения от ‘HANDLE’ error C2275: HANDLE: недопустимое использование этого типа в качестве выражения c:program filesmicrosoft sdkswindowsv6.0aincludewinnt.h(402): см. объявление ‘HANDLE’ Чего ему не хватает-то?!
Всё, разобрался. Объявления должны стоять до инициализирующих конструкций. В статье сначала идёт присваивание point.X и point.Y, а затем объявление хендлов. Поменял местами, сгруппировал все объявления (которые с указанием типа),в начале функции main() — и ошибки исчезли.
Источник: prog-cpp.ru
Взгляд на API консоли
Если вы пишете код для Интернета, вы, вероятно, работаете с console API, который помогает вам разрабатывать и отлаживать ваш код, например регистрацию сообщений или значений переменных в заданных точках вашего кода или времени, в течение которого операция требует завершения.
Что такое объект консоли?
Объект console является единственным доступным интерфейсом в console API, который предоставляет методы для записи информации в консоль браузера и может быть доступен из любого глобального объект (например, окно при просмотре областей).
Свойство window.console возвращает ссылку на объект console.
В этом посте давайте рассмотрим некоторые из основных методов, доступных с помощью объекта консоли.
console.log
Выводит сообщение на консоль.
console.error
Выводит на консоль сообщение об ошибке.
console.assert
Записывает в консоль сообщение об ошибке, если утверждение ложно.
console.clear
просто очищает консоль.
console.count
Регистрирует количество вызовов этого конкретного вызова count ().
console.warn
Выводит на консоль предупреждающее сообщение.
console.time
Запускает таймер, чтобы отслеживать, сколько времени занимает операция.
console.timeEnd
Останавливает таймер, который ранее был запущен console.time ().
console.table
Выводит указанные данные в виде таблицы. Эта функция принимает один обязательный аргумент data , который должен быть массивом или объектом, и один дополнительный необязательный параметр columns (для описания имен столбцов, включаемых в вывод).
console.trace
Выводит на консоль трассировку стека.
Хотите большего?
В этот пост я включил только те методы, которые считаю наиболее полезными при разработке / отладке приложения. Вы можете узнать больше о методах console в веб-документации MDN.
Источник: questu.ru
Getting Started with the API Console
The ability to link with other programs and devices is an amazing thing. We are all connected to the world and each other like never before. But how does data come from one point to another — from here to there. How do different applications and devices connect with each other to allow us to do different jobs with just a few clicks?
The little-known warrior of our connected world is the Аpplication Programming Interface or API.
It is the engine behind the scenes that we take for granted but it is what makes possible all the interactivity we have come to expect and rely upon. In our context, the API is a set of functions that allow the creation of applications that access the features or data of other applications or services.
What is a REST API
One of the most popular types of APIs is REST or, as they’re sometimes known, RESTful APIs. REST or RESTful APIs were designed to take advantage of existing protocols. While REST — or Representational State Transfer — can be used over nearly any protocol, when used for web APIs it typically takes advantage of the HTTP protocol.
Parse Server uses the REST API so basically you can interact with the Parse Server from anything that can send an HTTP request. There are many things you can do with the Parse REST API. For example:
- A mobile website can access Parse Server data from JavaScript.
- A web server can show data from Parse Server on a website.
- You can upload large amounts of data that will later be consumed in a mobile app.
- You can download recent data to run your own custom analytics.
In-depth knowledge of how to work with the Parse REST API is available on the official Parse Server REST API Guide.
Now, after you have an understanding of how the Parse Server communicates with the outside world you might want to try some actual requests, be it to get a hands-on experience, do a quick proof of concept, or just quickly test something out. You have a few options on how to do it — write client-side code, use a REST client, or simple cURL commands. But that can be a laborious process which takes away valuable time that you could be putting toward designing great experiences for your users. That’s why we made this part of your job easier by providing the API Console.
The API Console in SashiDo’s Dashboard
The API Console provides a graphical UI for exploring your Parse Server API’s resources and interacting with it. It has a beautiful interface and is pretty easy to use. You can compose requests, inspect server response, generate client cloud code calls and export cURLs painlessly
You will find SashiDo’s API Console when you enter the Dashboard, choose the app you want to work on, navigate to Core and then you will see the API Console.
Here are a few things you can do with the API Console:
- Create, read, update, and delete objects
- Run requests as a specific user of your app (to test your ACLs and CLPs)
- Call your Cloud Code functions and start background jobs
- Export the calls to cURL to test them in your Terminal or Shell
So, let’s go directly to our API Console and have a look there. You can try out some queries and take a look at what the server returns.
When you open the API Console you will find a toggle on the upper right corner, — that is where you can choose whether or not to use the Master Key when you perform sensitive API calls. Talking about sensitive API calls you will find some additional info about the use of Master Key in the Parse official REST API guide in the Security section.
Using the Master Key will give you access to data ignoring all the ACLs and CLPs. If this isn’t a requirement for your use case, you can switch off the Use Master Key toggle
Request types
Have you ever asked yourself what is the difference between GET and POST requests, or when to use the PUT request? Having basic information of how to execute HTTP methods with an API Console is a useful knowledge while exploring and trying out APIs. Let’s look through the different request types.
GET requests
GET requests are the most widely used methods in APIs. You can use the GET method to retrieve data from a server at the specified resource. For example, say you have an API with a classes/Users endpoint. Making a GET request to that endpoint should return a list of all available users.
Having in mind that a GET request is simplest, inquiring for statistics and no longer modifying any assets, it is considered a safe and idempotent method.
Whilst you’re developing tests for an API, the GET method will likely be the most common type of request made, so it’s essential to test every acknowledged endpoint with a GET request.
POST requests
POST requests are used to send data to the server’s API to create а resource. The data sent to the server is stored inside the request body of the HTTP request.
The simplest example is a “hello message” on a website. When you fill out the inputs in a form and hit Send, that data is put in the response body of the request and sent to the server.
It’s worth noting that a POST request is non-idempotent. It mutates data on the backend server (by creating or updating a resource), as opposed to a GET request which does not change any data. Here is a great explanation of idempotency.
Here are some tips for testing POST requests:
- Create a resource with a POST request and ensure a 200 status code is returned.
- Next, make a GET request for that resource, and ensure the data was saved correctly.
- Add tests that ensure POST requests fail with incorrect or ill-formatted data.
PUT requests
Just like POST, the PUT requests are used to send data to the API to update a resource. The difference is that PUT requests are idempotent. That is, calling the same PUT request multiple times will usually produce the identical result. In comparison, calling a POST request many times can have side effects of creating the same resource more than one time.
Testing an APIs PUT request is very much like testing POST requests. But now that we recognize the difference between the two, we are able to create API tests to affirm this behavior.
Check for the following things when you test the PUT requests:
- Repeatedly calling the PUT request always returns the same result.
- After updating a useful resource with a PUT request, a GET request for that useful resource should retrieve the new data.
- PUT requests will fail if invalid data is sent in the request body, hence the specified resource will not be updated.
DELETE requests
The DELETE method is precisely as it sounds: delete the resource of the desired URL. This method is one of the most frequent in RESTful APIs so it is top priority to recognize the way it works.
If a brand new user is created with a POST request at the classes/User endpoint, and it can be retrieved with a GET request to classes/Users/UserID, then creating a DELETE request to classes/Users/UserID will completely remove that user.
DELETE requests must be heavily tested on the grounds that they normally dispose of information from a database. Be careful when testing DELETE methods. Ensure you are using the precise credentials and no longer checking out with actual user records.
In a normal test case, a DELETE request should look like this:
- Create a brand new user with a POSТ request to classes/_Users
- After the POST request was successful, make a DELETE request to the endpoint classes/Users/UserID
- Next, a GET request to classes/Users/UserID will return a 101 status code, with an error Object not found, in the Results, if the DELETE request was successful.
Test your ACLs and CLPs by running requests as a specific user of your app
You can call a function as a specific user and check if the user has access to the resources you are calling. This is a very easy and simple way to verify if you have correctly implemented the ACLs and CLPs for a certain user of yours. Just enter the username or user ID in the Run as.. field and perform the command you want to receive results for.
Call your Cloud Code functions
Calling your Cloud Code functions has never been so effortless as it is with our API Console. By default there is a simple cloud code function sample in the functions.js file in your Cloud Code and in your Github Repo in the cloud folder so we can use it and show you how you can call a function through the API Console.
You will simply need to go to the API Console, choose the type of request, which will be POST, and choose the endpoint. Select the POST request and the endpoint functions/hello, click on the Send query button and see if the Dashboard shows you “Hello from SashiDo’s simple cloud code” message.
Export calls to cURL
cURL is the most used command line tool for making API calls. It is great for complex operations since it is scriptable and versatile. It combines the command, the credentials, like application ID, REST API key, your desired API endpoint, query parameters and more in a single command.
There is a very easy way to create cURL commands. You can construct a request in our API Console and convert it to cURL using the Export to cURL button. It is that easy. I am sure this will save a lot of your time if you have to write it on your own. For example, if you experience an error with your Cloud Code and you are contacting our Help Desk it is a good idea to run the same request or query through the API Console, export it to cURL and then include it in the steps to reproduce.
Our Dev and Engineering team will be happy to resolve your issue in a faster and more adequate manner.
Useful links:
For easing you even more we have also made a video about the API Console.
Fin
There you go! Now you have some ideas on how you can play around with the API Console or debug issues without writing a single line of code. Now it is your turn to explore it and enjoy the easiness of coding!
Источник: dev.to