Access USB port from C# and send and receive data - c#

How to access a USB port in C#, send a data stream and receive other data?

there's a .net library for that: SharpUSBLib
http://www.icsharpcode.net/OpenSource/SharpUSBLib/default.aspx

There are many libraries that achieve the job. Here is sample code for three platforms from Usb.Net (https://github.com/MelbourneDeveloper/Device.Net)
Windows (WinUSB)
https://github.com/MelbourneDeveloper/Device.Net/blob/411fea4acfbf965fc0160bf728a46b5ded8abc5d/src/Usb.Net/Windows/WindowsUsbDevice.cs#L33
public override Task InitializeAsync()
{
Dispose();
int errorCode;
if (string.IsNullOrEmpty(DeviceId))
{
throw new WindowsException($"{nameof(DeviceDefinition)} must be specified before {nameof(InitializeAsync)} can be called.");
}
_DeviceHandle = APICalls.CreateFile(DeviceId, (APICalls.GenericWrite | APICalls.GenericRead), APICalls.FileShareRead | APICalls.FileShareWrite, IntPtr.Zero, APICalls.OpenExisting, APICalls.FileAttributeNormal | APICalls.FileFlagOverlapped, IntPtr.Zero);
if (_DeviceHandle.IsInvalid)
{
//TODO: is error code useful here?
errorCode = Marshal.GetLastWin32Error();
if (errorCode > 0) throw new Exception($"Device handle no good. Error code: {errorCode}");
}
var isSuccess = WinUsbApiCalls.WinUsb_Initialize(_DeviceHandle, out var defaultInterfaceHandle);
HandleError(isSuccess, "Couldn't initialize device");
var bufferLength = (uint)Marshal.SizeOf(typeof(USB_DEVICE_DESCRIPTOR));
isSuccess = WinUsbApiCalls.WinUsb_GetDescriptor(defaultInterfaceHandle, WinUsbApiCalls.DEFAULT_DESCRIPTOR_TYPE, 0, 0, out _UsbDeviceDescriptor, bufferLength, out var lengthTransferred);
HandleError(isSuccess, "Couldn't get device descriptor");
byte i = 0;
//Get the first (default) interface
var defaultInterface = GetInterface(defaultInterfaceHandle);
_UsbInterfaces.Add(defaultInterface);
while (true)
{
isSuccess = WinUsbApiCalls.WinUsb_GetAssociatedInterface(defaultInterfaceHandle, i, out var interfacePointer);
if (!isSuccess)
{
errorCode = Marshal.GetLastWin32Error();
if (errorCode == APICalls.ERROR_NO_MORE_ITEMS) break;
throw new Exception($"Could not enumerate interfaces for device {DeviceId}. Error code: { errorCode}");
}
var associatedInterface = GetInterface(interfacePointer);
_UsbInterfaces.Add(associatedInterface);
i++;
}
IsInitialized = true;
RaiseConnected();
return Task.CompletedTask;
}
public override async Task<byte[]> ReadAsync()
{
return await Task.Run(() =>
{
var bytes = new byte[ReadBufferSize];
//TODO: Allow for different interfaces and pipes...
var isSuccess = WinUsbApiCalls.WinUsb_ReadPipe(_DefaultUsbInterface.Handle, _DefaultUsbInterface.ReadPipe.WINUSB_PIPE_INFORMATION.PipeId, bytes, ReadBufferSize, out var bytesRead, IntPtr.Zero);
HandleError(isSuccess, "Couldn't read data");
Tracer?.Trace(false, bytes);
return bytes;
});
}
public override async Task WriteAsync(byte[] data)
{
await Task.Run(() =>
{
if (data.Length > WriteBufferSize)
{
throw new Exception($"Data is longer than {WriteBufferSize} bytes which is the device's max buffer size.");
}
//TODO: Allow for different interfaces and pipes...
var isSuccess = WinUsbApiCalls.WinUsb_WritePipe(_DefaultUsbInterface.Handle, _DefaultUsbInterface.WritePipe.WINUSB_PIPE_INFORMATION.PipeId, data, (uint)data.Length, out var bytesWritten, IntPtr.Zero);
HandleError(isSuccess, "Couldn't write data");
Tracer?.Trace(true, data);
});
}
UWP
https://github.com/MelbourneDeveloper/Device.Net/blob/411fea4acfbf965fc0160bf728a46b5ded8abc5d/src/Usb.Net.UWP/UWPUsbDevice.cs#L24
public override async Task InitializeAsync()
{
await GetDevice(DeviceId);
if (_ConnectedDevice != null)
{
var usbInterface = _ConnectedDevice.Configuration.UsbInterfaces.FirstOrDefault();
if (usbInterface == null)
{
_ConnectedDevice.Dispose();
throw new Exception("There was no Usb Interface found for the device.");
}
var interruptPipe = usbInterface.InterruptInPipes.FirstOrDefault();
if (interruptPipe == null)
{
throw new Exception("There was no interrupt pipe found on the interface");
}
interruptPipe.DataReceived += InterruptPipe_DataReceived;
RaiseConnected();
}
else
{
throw new Exception($"Could not connect to device with Device Id {DeviceId}. Check that the package manifest has been configured to allow this device.");
}
}
public override async Task WriteAsync(byte[] bytes)
{
var bufferToSend = bytes.AsBuffer();
var usbInterface = _ConnectedDevice.Configuration.UsbInterfaces.FirstOrDefault();
var outPipe = usbInterface.InterruptOutPipes.FirstOrDefault();
await outPipe.OutputStream.WriteAsync(bufferToSend);
Tracer?.Trace(false, bytes);
}
public override async Task<byte[]> ReadAsync()
{
if (_IsReading)
{
throw new Exception("Reentry");
}
lock (_Chunks)
{
if (_Chunks.Count > 0)
{
var retVal = _Chunks[0];
Tracer?.Trace(false, retVal);
_Chunks.RemoveAt(0);
return retVal;
}
}
_IsReading = true;
_TaskCompletionSource = new TaskCompletionSource<byte[]>();
return await _TaskCompletionSource.Task;
}
Android
https://github.com/MelbourneDeveloper/Device.Net/blob/411fea4acfbf965fc0160bf728a46b5ded8abc5d/src/Usb.Net.Android/AndroidUsbDevice.cs#L199
public async Task InitializeAsync()
{
//TODO: Use a semaphore lock here
if (_IsInitializing)
{
return;
}
_IsInitializing = true;
try
{
//TODO:
//Dispose();
var isPermissionGranted = await RequestPermissionAsync();
if (!isPermissionGranted.HasValue)
{
throw new Exception("User did not respond to permission request");
}
if (!isPermissionGranted.Value)
{
throw new Exception("The user did not give the permission to access the device");
}
var usbInterface = _UsbDevice.GetInterface(0);
//TODO: This selection stuff needs to be moved up higher. The constructor should take these arguments
for (var i = 0; i < usbInterface.EndpointCount; i++)
{
var ep = usbInterface.GetEndpoint(i);
if (_ReadEndpoint == null && ep.Type == UsbAddressing.XferInterrupt && ep.Address == (UsbAddressing)129)
{
_ReadEndpoint = ep;
continue;
}
if (_WriteEndpoint == null && ep.Type == UsbAddressing.XferInterrupt && (ep.Address == (UsbAddressing)1 || ep.Address == (UsbAddressing)2))
{
_WriteEndpoint = ep;
}
}
//TODO: This is a bit of a guess. It only kicks in if the previous code fails. This needs to be reworked for different devices
if (_ReadEndpoint == null)
{
_ReadEndpoint = usbInterface.GetEndpoint(0);
}
if (_WriteEndpoint == null)
{
_WriteEndpoint = usbInterface.GetEndpoint(1);
}
if (_ReadEndpoint.MaxPacketSize != ReadBufferLength)
{
throw new Exception("Wrong packet size for read endpoint");
}
if (_WriteEndpoint.MaxPacketSize != ReadBufferLength)
{
throw new Exception("Wrong packet size for write endpoint");
}
_UsbDeviceConnection = UsbManager.OpenDevice(_UsbDevice);
if (_UsbDeviceConnection == null)
{
throw new Exception("could not open connection");
}
if (!_UsbDeviceConnection.ClaimInterface(usbInterface, true))
{
throw new Exception("could not claim interface");
}
Logger.Log("Hid device initialized. About to tell everyone.", null, LogSection);
IsInitialized = true;
RaiseConnected();
return;
}
catch (Exception ex)
{
Logger.Log("Error initializing Hid Device", ex, LogSection);
}
_IsInitializing = false;
}
public override async Task<byte[]> ReadAsync()
{
try
{
var byteBuffer = ByteBuffer.Allocate(ReadBufferLength);
var request = new UsbRequest();
request.Initialize(_UsbDeviceConnection, _ReadEndpoint);
request.Queue(byteBuffer, ReadBufferLength);
await _UsbDeviceConnection.RequestWaitAsync();
var buffers = new byte[ReadBufferLength];
byteBuffer.Rewind();
for (var i = 0; i < ReadBufferLength; i++)
{
buffers[i] = (byte)byteBuffer.Get();
}
//Marshal.Copy(byteBuffer.GetDirectBufferAddress(), buffers, 0, ReadBufferLength);
Tracer?.Trace(false, buffers);
return buffers;
}
catch (Exception ex)
{
Logger.Log(Helpers.ReadErrorMessage, ex, LogSection);
throw new IOException(Helpers.ReadErrorMessage, ex);
}
}
public override async Task WriteAsync(byte[] data)
{
try
{
var request = new UsbRequest();
request.Initialize(_UsbDeviceConnection, _WriteEndpoint);
var byteBuffer = ByteBuffer.Wrap(data);
Tracer?.Trace(true, data);
request.Queue(byteBuffer, data.Length);
await _UsbDeviceConnection.RequestWaitAsync();
}
catch (Exception ex)
{
Logger.Log(Helpers.WriteErrorMessage, ex, LogSection);
throw new IOException(Helpers.WriteErrorMessage, ex);
}
}

Heres some information, and a library: USB & C#

this site definitely help u...
http://libusbdotnet.sourceforge.net
it contains a class library and some sample codes release on 2010

If you USB device Class is HID you can also try this C# driver.

Related

how to implement retry mechanism when I got gsm modem Exception: No data received from phone?

public class GSMModemConnection
{
I made a windows service for receiving SMS I'm using Wavecom Gsm modem 1306B. But after some second I got an
Exception: No data received from phone. I have searched in StackOverflow I found this link Exception: No data received from phone
someone pointed about to create a retry mechanism but I don't know how to implement it.
static void Main(string[] args)
{
GSMModemConnection gsm = new GSMModemConnection();
var result = gsm.OpenPort();
Console.WriteLine(result.PortName);
while (true)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
ShortMessage execResult = gsm.ReadSMS(result, "AT+CMGL=\"ALL\"");
Console.WriteLine(execResult.Message);
Console.WriteLine(execResult.Status);
}
}
public class GSMModemConnection
{
public AutoResetEvent receiveNow;
//string strPortName, string strBaudRate
public SerialPort OpenPort()
{
receiveNow = new AutoResetEvent(false);
SerialPort port = new SerialPort();
port.PortName = "COM3";
port.BaudRate = 115200 /*Convert.ToInt32(strBaudRate)*/; //updated by Anila (9600)
port.DataBits = 8;
port.StopBits = StopBits.One;
port.Parity = Parity.None;
port.ReadTimeout = 300;
port.WriteTimeout = 300;
port.Encoding = Encoding.GetEncoding("iso-8859-1");
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
port.DtrEnable = true;
port.RtsEnable = true;
return port;
}
//Close Port
public void ClosePort(SerialPort port)
{
port.Close();
port.DataReceived -= new SerialDataReceivedEventHandler(port_DataReceived);
port = null;
}
//Execute AT Command
public string ExecCommand(SerialPort port, string command, int responseTimeout, string errorMessage)
{
try
{
//receiveNow = new AutoResetEvent();
port.DiscardOutBuffer();
port.DiscardInBuffer();
receiveNow.Reset();
port.Write(command + "\r");
//Thread.Sleep(3000); //3 seconds
string input = ReadResponse(port, responseTimeout);
if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
throw new ApplicationException("No success message was received.");
return input;
}
catch (Exception ex)
{
throw new ApplicationException(errorMessage, ex);
}
}
//Receive data from port
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (e.EventType == SerialData.Chars)
receiveNow.Set();
}
public string ReadResponse(SerialPort port, int timeout)
{
string buffer = string.Empty;
do
{
if (receiveNow.WaitOne(timeout, false))
{
string t = port.ReadExisting();
buffer += t;
}
else
{
if (buffer.Length > 0)
throw new ApplicationException("Response received is incomplete.");
else
throw new ApplicationException("No data received from phone.");
}
}
while (!buffer.EndsWith("\r\nOK\r\n") && !buffer.EndsWith("\r\n> ") && !buffer.EndsWith("\r\nERROR\r\n"));
return buffer;
}
public ShortMessage ReadSMS(SerialPort port, string p_strCommand)
{
// Set up the phone and read the messages
ShortMessage messages = null;
try
{
#region Execute Command
// Check connection
var a = ExecCommand(port, "AT", 300, "No phone connected");
// Use message format "Text mode"
var b = ExecCommand(port, "AT+CMGF=1\r", 300, "Failed to set message format.");
// Use character set "PCCP437"
//var c = ExecCommand(port, "AT+CSCS=\"PCCP437\"", 300, "Failed to set character set.");
// Select SIM storage
//var d = ExecCommand(port, "AT+CPMS=\"SM\"", 300, "Failed to select message storage.");
// Read the messages
string input = ExecCommand(port, p_strCommand, 5000, "Failed to read the messages.");
#endregion
#region Parse messages
messages = ParseMessages(input);
#endregion
}
catch (Exception ex)
{
throw ex;
}
if (messages != null)
return messages;
else
return null;
}
public ShortMessage ParseMessages(string input)
{
ShortMessage msg = new ShortMessage();
//ShortMessageCollection messages = new ShortMessageCollection();
try
{
Regex r = new Regex(#"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
Match m = r.Match(input);
while (m.Success)
{
//msg.Index = int.Parse(m.Groups[1].Value);
msg.Index = int.Parse(m.Groups[1].Value);
msg.Status = m.Groups[2].Value;
msg.Sender = m.Groups[3].Value;
msg.Alphabet = m.Groups[4].Value;
msg.Sent = m.Groups[5].Value;
msg.Message = m.Groups[6].Value;
//messages.Add(msg);
m = m.NextMatch();
}
}
catch (Exception ex)
{
throw ex;
}
return msg;
}
}
You DO have a retry mechanism in place with the DO-WHILE loop from the following expression:
public string ReadResponse(SerialPort port, int timeout)
{
string buffer = string.Empty;
do
{
if (receiveNow.WaitOne(timeout, false))
{
string t = port.ReadExisting();
buffer += t;
}
else
{
if (buffer.Length > 0)
throw new ApplicationException("Response received is incomplete.");
else
throw new ApplicationException("No data received from phone.");
}
}
while (!buffer.EndsWith("\r\nOK\r\n") && !buffer.EndsWith("\r\n> ") && !buffer.EndsWith("\r\nERROR\r\n"));
return buffer;
}
What you can do is reduce the granularity of the error report mechanism.
In this case, for example, the line throw new ApplicationException() will break the loop and get captured in the Exec() function, then thrown again. If you just want to wait for the loop to close and the DO-WHILE loop to get executed, I would replace the following part of the code:
else
{
if (buffer.Length > 0)
throw new ApplicationException("Response received is incomplete.");
else
throw new ApplicationException("No data received from phone.");
}
With:
else
{
if (buffer.Length > 0)
bufferError += "Response received is incomplete.\n";
else
bufferError += "No data received from phone.\n";
}
Why?
After the DO-WHILE loop, the buffer will either return string.Empty or some value.
Up in the code, you have:
string input = ReadResponse(port, responseTimeout);
if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
throw new ApplicationException("No success message was received.");
return input;
Basically, if the returned buffer is string.Empty an Exception will be thrown again.
By returning the buffer Error, you can decide later how you want to handle it but the DO-WHILE loop will run at least once up until the condition from the WHILE expression is met.
Rest of the code should look like this:
//Thread.Sleep(3000); //3 seconds
string bufferErrors = string.Empty;
string input = ReadResponse(port, responseTimeout, bufferErrors);
if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
throw new ApplicationException("No success message was received.");
if (!string.IsNullOrWhiteSpace(bufferErrors))
{
//Handle bufferErrors
}
return input;
Remember to declare the out parameter in ReadResponse
public string ReadResponse(SerialPort port, int timeout, out string bufferError)
{
string buffer = string.Empty;
bufferError = string.Empty;

Gettting error Timeout performing ZADD (10000ms), next: HSCAN in .net core 3.0 application with redis version 4

I am running my .net core 3.0 application in ubuntu 18.04 machine in same network where redis present
I am getting error
Timeout performing ZADD (10000ms), next: HSCAN InProccessingMsisdnTransaction_34234234, inst: 1, qu: 0, qs: 81, aw: False, rs: ReadAsync, ws: Idle, in: 34117, in-pipe: 0, out-pipe: 0, serverEndpoint: 10.10.10.10:6379, mgr: 10 of 10 available, clientName: SafeRedisConnection, IOCP: (Busy=0,Free=1000,Min=10,Max=1000), WORKER: (Busy=32,Free=32735,Min=2,Max=32767), v: 2.0.601.3402 (Please take a look at this article for some common client-side issues that can cause timeouts: https://stackexchange.github.io/StackExchange.Redis/Timeouts)
My implementation for redis interaction is as following
public static class RedisManager
{
private static readonly bool LogRedisRelatedActivities;
private static readonly Lazy<ConfigurationOptions> ConfigOptions = new Lazy<ConfigurationOptions>(() =>
{
ConfigurationOptions configOptions = null;
try
{
var redisInfo = ConfigurationHandler.GetSection<RedisElement>("RedisSection");
if (redisInfo != null )
{
if (redisInfo.IsActive)
{
redisInfo.RedisServerNameOrIp = ConfigurationHandler.GetSection<string>(StringConstants.EnvConfig.RedisRedisServerNameOrIp, Configurationtype.RedisSection);
redisInfo.RedisServerPort = ConfigurationHandler.GetSection<string>(StringConstants.EnvConfig.RedisRedisServerPort, Configurationtype.RedisSection);
redisInfo.RedisDefaultDatabase = ConfigurationHandler.GetSection<int>(StringConstants.EnvConfig.RedisDefaultDatabase, Configurationtype.RedisSection);
configOptions = new ConfigurationOptions();
configOptions.EndPoints.Add(redisInfo.RedisServerNameOrIp + ":" + redisInfo.RedisServerPort);
configOptions.ClientName = "SafeRedisConnection";
configOptions.ConnectTimeout = redisInfo.ConnectTimeout * 1000;
configOptions.SyncTimeout = redisInfo.SyncTimeout * 1000;
configOptions.AbortOnConnectFail = false;
configOptions.KeepAlive = redisInfo.KeepAliveDuration;
configOptions.DefaultDatabase = redisInfo.RedisDefaultDatabase;
}
else
{
Logger.Error("RedisSection is in-active");
}
}
else
{
Logger.Error("RedisSection not found");
}
}
catch (Exception ex)
{
Logger.Fatal(ex, ex);
}
return configOptions;
});
private static readonly Lazy<ConnectionMultiplexer> Conn = new Lazy<ConnectionMultiplexer>(
() =>
{
try
{
if (ConfigOptions != null && ConfigOptions.Value != null)
{
return ConnectionMultiplexer.Connect(ConfigOptions.Value);
}
return null;
}
catch (Exception ex)
{
Logger.Fatal(ex.Message, ex);
return null;
}
});
private static ConnectionMultiplexer Muxer => Conn.Value;
static RedisManager()
{
try
{
LogRedisRelatedActivities = ConfigurationHandler.GetSection<bool>(StringConstants.AppSettingsKeys.LogRedisRelatedActivities);
if (Muxer != null && Muxer.IsConnected)
{
Logger.Info("Redis Connected ");
}
else
{
Logger.Info("Redis Not Connected ");
}
}
catch (Exception ex)
{
Logger.Fatal(ex.Message, ex);
}
}
public static string GetStringItem(string key)
{
string val = null;
try
{
IDatabase getDatabase;
if (Muxer != null && Muxer.IsConnected && (getDatabase = Muxer.GetDatabase()) != null)
{
val = getDatabase.StringGet(key);
}
}
catch (Exception ex)
{
Logger.Fatal(ex.Message, ex);
}
return val;
}
public static bool AddZList(string key, object value)
{
var isAdded = false;
try
{
IDatabase getDatabase;
if (Muxer != null && Muxer.IsConnected && (getDatabase = Muxer.GetDatabase()) != null)
{
isAdded = getDatabase.SortedSetAdd(key, JsonSerializer.Serialize(value), Utility.GetCurrentSystemTime().Ticks);
}
}
catch (Exception ex)
{
Logger.Fatal(ex.Message, ex);
}
return isAdded;
}
}
When running same application from windows server i am not getting any such error
Problem was related to some threadpool implemenation in stackexchange.redis.
Workaround is to initialize high number of minimum thread in our application. done it via some configuration in .csproj file

Static methods in Web API... Correct or wrong?

I am writing an asp.net web API using Visual Studio 2019. When I write as in the example below, Visual Studio recommends me making the method static. So I followed the suggestions and made all methods of the Web API static. Is this correct? What is the advantage if it is correct and what is the disadvantage if it is wrong?
Thank you...
Severity Code Description Project File Line Suppression State
Message CA1822 Member AdresleriGetir does not access instance data and can be marked as static (Shared in VisualBasic) Devriye.WebApi**
My method:
[HttpPost]
public static Adres[] AdresleriGetir([FromBody]GirisParametresi girisParametresi)
{
if (girisParametresi != null)
{
string query = #"SELECT * FROM ADRESLER WHERE AKTIF=1";
Cagri cagri = new Cagri()
{
Proje = "Devriye.WebApi",
Modul = "AdresController",
Metot = "AdresGetir",
Nesne = new JavaScriptSerializer().Serialize(girisParametresi)
};
Log log = new Log(null, cagri, girisParametresi.Oturum);
using (DataTable dataTable = DataAccessLayer.VerileriGetir(query, null, log))
{
List<Adres> adresler = new List<Adres>();
if (dataTable.Rows.Count > 0)
{
for (int i = 0; i < dataTable.Rows.Count; i++)
{
Adres adres = new Adres();
try { adres.Cadde = Convert.ToString(dataTable.Rows[i]["Cadde".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.EklenmeTarihi = Convert.ToDateTime(dataTable.Rows[i]["EklenmeTarihi".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.ID = Convert.ToInt32(dataTable.Rows[i]["ID".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Il = Convert.ToString(dataTable.Rows[i]["Il".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Ilce = Convert.ToString(dataTable.Rows[i]["Ilce".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.KapiNo = Convert.ToString(dataTable.Rows[i]["KapiNo".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Mahalle = Convert.ToString(dataTable.Rows[i]["Mahalle".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.PostaKodu = Convert.ToInt32(dataTable.Rows[i]["PostaKodu".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Sokak = Convert.ToString(dataTable.Rows[i]["Sokak".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
adresler.Add(adres);
}
return adresler.ToArray();
}
else
{
return null;
}
}
}
else
{
return null;
}
}
This function doesn't access any instance data or call any instance methods.
I've had similar questions about R# wanting to convert this type of function to static. See this SO question for some reasons. From the accepted answer in the link;
It makes me ask myself if the method in question should actually be
part of the type or not. Since it doesn't use any instance data, you
should at least consider if it could be moved to its own type. Is it
an integral part of the type, or is it really a general purpose
utility method?
If it does make sense to keep the method on the specific type, there's
a potential performance gain as the compiler will emit different code
for a static method.

await on long service call behaves differently in Microsoft Bot Framework

I have two dialogs called from root dialog based on the prompt response.
Both dialogs internally prepare request and call a service class. Weird thing is one dialog resumes with response from service but the other though receives response from service is not resuming.
Below method works fine and resumes the call at if (searchResult != null && searchResult.Item1 != null)
public virtual async Task MessageRecievedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
if (message.Text == "quit")
{
context.Done<object>(null);
}
else
{
try
{
var srm = new CoveoRestSearchService.CoveoSearchRequestModel
{
Query = message.Text,
EnableDidYouMean = true,
QuerySource = CoveoRestSearchService.Constants.SWEATERSSOURCE
};
var searchResult = await csp.PerformSearch(srm);
if (searchResult != null && searchResult.Item1 != null)
{
await CardUtil.showHeroCard(message, searchResult.Item1);
}
else
{
await context.PostAsync($"No search results for {message.Text} found");
}
await PostSearchUsageAnalyticsToCoveo(context, srm, searchResult.Item2);
}
catch (Exception e)
{
Debug.WriteLine($"Error when searching : {e.Message}");
}
finally {
context.Wait(MessageRecievedAsync);
}
}
}
This below one though looks identical is not resuming the if (response != null)
public virtual async Task MessageRecievedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
if (message.Text == "quit")
{
context.Done<object>(null);
}
else
{
try
{
var currentDate = DateTime.UtcNow;
string toDate = currentDate.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
string fromDate = currentDate.AddDays(-7).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
MetricsQuery = MetricsQuery.Replace("{fromISODate}", fromDate);
MetricsQuery = MetricsQuery.Replace("{toISODate}", toDate);
MetricsQuery = MetricsQuery.Replace("{term}", message.Text);
var response = await cuawc.MetricSearchUsageToCoveoAsync(MetricsQuery
.Replace(" ", "%20")
.Replace("!=", "!%3D")
.Replace("==", "%3D%3D")
.Replace(":", "%3A"));
if (response != null)
{
var message_from_bot = context.MakeMessage();
}
//message_from_bot.Attachments = new List<Attachments>();
await context.PostAsync("Please enter the search term for metrics");
}
catch (Exception e)
{
Debug.WriteLine($"Error when pulling metrics : {e.Message}");
}
finally
{
context.Wait(MessageRecievedAsync);
}
}
}
Struggling from past 2 days to figure what is wrong!!

How to test if a proxy server is working or not?

I've got a pretty big list with proxy servers and their corresponding ports. How can I check, if they are working or not?
Working? Well, you have to use them to see if they are working.
If you want to see if they are online, I guess ping is a first step.
There is a Ping class in .NET.
using System.Net.NetworkInformation;
private static bool CanPing(string address)
{
Ping ping = new Ping();
try
{
PingReply reply = ping.Send(address, 2000);
if (reply == null) return false;
return (reply.Status == IPStatus.Success);
}
catch (PingException e)
{
return false;
}
}
I like to do a WhatIsMyIP check through a proxy as a test.
using RestSharp;
public static void TestProxies() {
var lowp = new List<WebProxy> { new WebProxy("1.2.3.4", 8080), new WebProxy("5.6.7.8", 80) };
Parallel.ForEach(lowp, wp => {
var success = false;
var errorMsg = "";
var sw = new Stopwatch();
try {
sw.Start();
var response = new RestClient {
//this site is no longer up
BaseUrl = "https://webapi.theproxisright.com/",
Proxy = wp
}.Execute(new RestRequest {
Resource = "api/ip",
Method = Method.GET,
Timeout = 10000,
RequestFormat = DataFormat.Json
});
if (response.ErrorException != null) {
throw response.ErrorException;
}
success = (response.Content == wp.Address.Host);
} catch (Exception ex) {
errorMsg = ex.Message;
} finally {
sw.Stop();
Console.WriteLine("Success:" + success.ToString() + "|Connection Time:" + sw.Elapsed.TotalSeconds + "|ErrorMsg" + errorMsg);
}
});
}
However, I might suggest testing explicitly for different types (ie http, https, socks4, socks5). The above only checks https. In building the ProxyChecker for https://theproxisright.com/#proxyChecker, I started w/ the code above, then eventually had to expand for other capabilities/types.
try this:
public static bool SoketConnect(string host, int port)
{
var is_success = false;
try
{
var connsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 200);
System.Threading.Thread.Sleep(500);
var hip = IPAddress.Parse(host);
var ipep = new IPEndPoint(hip, port);
connsock.Connect(ipep);
if (connsock.Connected)
{
is_success = true;
}
connsock.Close();
}
catch (Exception)
{
is_success = false;
}
return is_success;
}
string strIP = "10.0.0.0";
int intPort = 12345;
public static bool PingHost(string strIP , int intPort )
{
bool blProxy= false;
try
{
TcpClient client = new TcpClient(strIP ,intPort );
blProxy = true;
}
catch (Exception ex)
{
MessageBox.Show("Error pinging host:'" + strIP + ":" + intPort .ToString() + "'");
return false;
}
return blProxy;
}
public void Proxy()
{
bool tt = PingHost(strIP ,intPort );
if(tt == true)
{
MessageBox.Show("tt True");
}
else
{
MessageBox.Show("tt False");
}

Categories

Resources