суббота, 24 февраля 2018 г.

Google Cloud Translation API пример кода на C#

Простой пример реализации сервиса перводов Google Cloud Translation API на C#

Для работы коду нужно устанвоить в проект через NuGet библиотеку Google.Cloud.Translation.V2


public class TranslateServiceGoogle
    {
        public int MaxTextLenght => 4999;

        private readonly string apiKey;

        private TranslationClient _client;
        private TranslationClient Client => _client ?? (_client = TranslationClient.CreateFromApiKey(apiKey));

        public TranslateServiceGoogle(string apiKey)
        {
            this.apiKey = apiKey;
        }        

        public string TranslateText(
            string text,
            string languageFrom,
            string languageTo
            )
        {
            if (string.IsNullOrWhiteSpace(text)) return "";

            CheckTranslatebleText(text);                      

            var res = Client.TranslateText(text, languageTo, languageFrom);

            return res.TranslatedText;
        }

        public string TranslateHtml(
            string text,
            string languageFrom,
            string languageTo
        )
        {
            if (string.IsNullOrWhiteSpace(text))
                return "";

            CheckTranslatebleText(text);
            
            var response = Client.TranslateHtml(text, languageTo, languageFrom);

            return response.TranslatedText;
        }

        public void CheckTranslatebleText(string text)
        {
            if (text.Length > MaxTextLenght)
            {
                throw new ArgumentOutOfRangeException($"Недопустимый размер текста ({text.Length} символов) в блоке!");
            }
        }
    }


см. также
Сравнение сервисов облачных переводов Microsoft Azure Translator Text API и Google Cloud Translation API

четверг, 15 февраля 2018 г.

Connection to MS SQL Server slows down via WiFi (TP-Link Archer C2, AC 750 router)

Situation

I bought and installed a new TP-Link Archer C2, AC 750 router

Found strange slows down when connecting to a remote MS SQL Server database

When connecting by cable, the connection speed with the database is almost instantaneous (up to 1 second)

Through the wi-fi connection to the base took 35 seconds (although the overall speed of the wi-fay is almost the same as the cable)

With the old D-link dir 300 router, there were no such problems. The laptop did not change. The provider did not change.

I use EMS SQL Manager for SQL for database coneection
https://www.sqlmanager.net/en/products/mssql/manager


What did not help


Switched to different 2.4 and 5 MHz bands
Played with subtle settings WiFi (channel, channel width, Package, WPS) - all useless


What helped


It turned out that it was in the settings for WiFi authorization

in the web interface of the router (usually access through http://192.168.0.1/)
section
Wireless Security

defaults:

Authentication type: WPA2-PSK
Encryption: AES

It was necessary to change the encryption to TKIP

Note: to change the encryption from AES to TKIP it was necessary to disable WPS mode for one of the channels (this is also done via the web interface of the router.) The section is called "WPS")

I want to note the support service TP-Link.
Although the modem is home-use, but I was not left alone with the problem. Manager Vyacheslav Didenko contacted me and we spent more than an hour dealing with the situation. Good job!

Соединение с MS SQL Server тормозит по WiFi (роутер TP-Link Archer C2, AC 750)

Ситуация

Купил и установил дома новый роутер TP-Link Archer C2, AC 750

Обнаружил странные торможения при подключении к удаленной базе данных MS SQL Server

При соединении по кабелю скорость соединения с базой данных практически моментальная (до 1-ой секунды)

Через вай-фай соединение с базой заняло 35 сек (хотя общая скорость по вай-фаю почти такая же как и по кабелю)

Со старым роутером d-link dir 300 таких проблем не было. Ноутбук не менял. Провайдера не менял

С БД коннекчусь через EMS SQL Manager for SQL Server
https://www.sqlmanager.net/en/products/mssql/manager 


Что НЕ помогло


Переключался на разные диапазоны 2,4 и 5 Мгц
Игрался с тонкими настройками WiFi (канал, ширина канала, Пакет, WPS) - все без толку


Что помогло


Оказывается дело было в настройках авторизации WiFi

в веб-интерфейсе роутера (обычно доступ через http://192.168.0.1/)
раздел
Защита беспроводного режима

по умолчанию стояло так

Тип аутентификации: WPA2-PSK
Шифрование: AES

Нужно было изменить шифрование на TKIP

Примечание: чтобы сменить шифрование с AES на TKIP пришлось для одного из каналов отключить режим WPS (это тоже через веб-интерфейс роутера делается. Раздел так и называется "WPS")

Отдельно хочу отметить службу поддержки TP-Link.
Хоть модем и домашний, но меня не бросили один на один с проблемой. Менеджер Вячеслав Диденко связался со сной и мы больше часа разбирались с ситуацией. Зачет однозначно!