I have been using TLSharp library for a week but recently I am encountering the Exception:
CHANNELS_TOO_MUCH
My code can't get pass the await client.connect() function even. I haven't found any documentation on the GitHub repository of the library that describes why this exception occurs. I seems it's not a Exception that occurs because of telegram limitation because it gives me this exception at connect function.
Here is my code:
public static async Task<TelegramClient> connectTelegram()
{
store = new FileSessionStore();
client = new TelegramClient(store, numberToAuthenticate, apiId, apiHash);
try
{
await client.Connect();
}
catch (InvalidOperationException e)
{
Debug.WriteLine("Invalid Operation Exception");
if (e.Message.Contains("Couldn't read the packet length"))
{
Debug.WriteLine("Couldn't read the packet length");
Debug.WriteLine("Retying to Connect ...");
}
await connectTelegram();
}
catch (System.IO.IOException)
{
Debug.WriteLine("IO Exception while Connecting");
Debug.WriteLine("Retrying to Connect ...");
await connectTelegram();
}
catch(Exception e)
{
Debug.WriteLine(e.Message):
}
return client;
}
This exception is not documented yet. I encountered this exception when I tried to use the same session file for connecting to telegram and calling requests. It seems when a session file is used by different and multiple clients the session file becomes corrupted. All you have to do is deleting the session file and recreate it as you have created it before.
Here is an example of doing that:
FileSessionStore store;
TelegramClient client;
store = new FileSessionStore();
client = new TelegramClient(store, numberToAuthenticate, apiId, apiHash);
await client.Connect();
Related
I use FluentFTP in my code to transfer data internally to a FTP server. If the connection to the FTP server breaks down during the upload, then there is no exception.
But oddly enough, that doesn't happen with all dates! If I take a *.7z file, there is an exception when the connection is broken.
I'm confused!
When transferring a *.7z file, why does it recognize that the connection was interrupted (service stopped) and restart the connection when the service is available again and with a *.opus file does the program stop in an await?
public class FileWatcher
{
public static async Task Main(string[] args)
{
do
{
Console.WriteLine("Und los geht es!");
await UploadFileAsync();
await Task.Delay(15000);
} while (true);
}
static async Task UploadFileAsync()
{
try
{
string[] filePath = Directory.GetFiles(#"C:\temp\ftpupload", "*",
SearchOption.AllDirectories);
var token = new CancellationToken();
using (AsyncFtpClient client = new AsyncFtpClient())
{
client.Host = "192.168.1.100";
client.Port = 21;
client.Credentials.UserName = "test";
client.Credentials.Password = "test123";
client.Config.EncryptionMode = FtpEncryptionMode.None;
client.Config.InternetProtocolVersions = FtpIpVersion.IPv4;
client.Config.ValidateAnyCertificate = true;
client.Config.ConnectTimeout = 10000;
Console.WriteLine("Connecting......");
await client.AutoConnect(token);
Console.WriteLine("Connected!");
foreach (var erg in filePath)
{
Console.WriteLine("File is uploading: " + erg.GetFtpFileName());
await client.UploadFile(erg, "/" + erg.GetFtpFileName(),
FtpRemoteExists.Overwrite, true, token: token);
Console.WriteLine("File successfully uploaded: " +
erg.GetFtpFileName());
System.IO.File.Delete(erg);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Error while uploading the file to the server. See InnerException for more info.
I think the problem is that you are not catching the exception from the Main method. The code inside the try-catch block will execute correctly, but if an exception occurs outside the try-catch block, the program will terminate without reporting the error.
So to fix it, you should add a try-catch block in the Main method and inside it, call the UploadFileAsync() method with the await keyword.
Another reason may be the size of the file, or the delay you set in the Main method.
I've recently discovered the System.IO.Pipelines namespace and it looks interesting. I've been trying to implement the IDuplexPipe interface in the context of a simple TCP server which accepts connections and then communicates back and forth with the connected client.
However, I'm struggling to make it stable. It feels like I've misunderstood something fundamental. I've also been googling for reference implementations of the interface to guide me in the right direction.
This is to my knowledge the most complete document on System.IO.Pipelines out there. The exmple I've provided below is heavily borrowing from it.
https://github.com/davidfowl/DocsStaging/blob/master/Pipelines.md
https://devblogs.microsoft.com/dotnet/system-io-pipelines-high-performance-io-in-net/
My question: what would a typical implementation of the IDuplexPipe interface look like in the context of a TCP server?
Btw, this is what I have currently. The idea is to setup a new "duplex communication" by providing an established SslStream:
public class DuplexCommunication : IDuplexPipe
{
public PipeReader Input => _receivePipe.Reader;
public PipeWriter Output => _transmitPipe.Writer;
private readonly SslStream _stream;
// Data received from the SslStream will end up on this pipe
private readonly Pipe _receivePipe = new Pipe();
// Data that is to be transmitted over the SslStream ends up on this pipe
private readonly Pipe _transmitPipe = new Pipe();
private readonly CancellationToken _cts;
private Task _receive;
private Task _transmit;
public DuplexCommunication(SslStream stream, CancellationToken cts)
{
_stream = stream;
_cts = cts;
_receive = Receive();
_transmit = Transmit();
}
private async Task Receive()
{
Exception error = null;
try
{
while (!_cts.IsCancellationRequested)
{
var buffer = _receivePipe.Writer.GetMemory(1);
var bytes = await _stream.ReadAsync(buffer, _cts);
_receivePipe.Writer.Advance(bytes);
if (bytes == 0) {
break;
}
var flush = await _receivePipe.Writer.FlushAsync(_cts);
if (flush.IsCompleted || flush.IsCanceled)
{
break;
}
}
}
catch (Exception ex)
{
// This might be "stream is closed" or similar, from when trying to read from the stream
Console.WriteLine($"DuplexPipe ReceiveTask caugth an exception: {ex.Message}");
error = ex;
}
finally
{
await _receivePipe.Writer.CompleteAsync(error);
}
}
private async Task Transmit()
{
Exception error = null;
try
{
while (!_cts.IsCancellationRequested)
{
var read = await _transmitPipe.Reader.ReadAsync(_cts);
var buffer = read.Buffer;
if (buffer.IsEmpty && read.IsCompleted)
{
break;
}
foreach (var segment in buffer)
{
await _stream.WriteAsync(segment, _cts);
}
_transmitPipe.Reader.AdvanceTo(buffer.End);
await _stream.FlushAsync(_cts);
}
}
catch (Exception e)
{
Console.WriteLine($"DuplexPipe Transmit caught an exception: {e.Message}");
error = e;
}
finally
{
await _transmitPipe.Reader.CompleteAsync(error);
}
}
}
So, I spent some more time searching around the internet and found something that sort of solves my problem. I found, among some other things, this question: How to handle incoming TCP messages with a Kestrel ConnectionHandler?
Here it seems like the ConnectionHandler class provides exactly what I need, including some very handy plumbing for handling SSL certificates, port listening, etc that comes for free when building an ASP.NET application.
I am currently working on an UWP app, that will run on a Raspberry PI. Most of my application can be used without an internet connection, but parts of it rely on fetching data from a server ran locally.
My issue is that whenever the server is offline, I can not handle the exceptions raised by the HttpClient.
To avoid using async tasks in the constructor of the ViewModel, I've moved it to the OnLoaded method of the View.
These are the methods that I use:
HomeAssistantView
private async void OnLoaded(object sender, RoutedEventArgs e)
{
await ViewModel.LoadEntities();
}
HomeAssistantViewModel
public async Task LoadEntities()
{
var entityList = await _homeAssistantService.LoadEntities();
Switches = new ObservableCollection<HomeAssistantSwitchEntity>(entityList.OfType<HomeAssistantSwitchEntity>());
Entities = new ObservableCollection<HomeAssistantEntity>(entityList.Where(entity =>!(entity is HomeAssistantSwitchEntity)));
}
HomeAssistantService
public async Task<List<HomeAssistantEntity>> LoadEntities()
{
_client.BaseAddress = new Uri(_homeAssistantURL);
_client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_homeAssistantToken}");
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = await _client.GetAsync("api/states");
if (response.IsSuccessStatusCode)
{
return DeserializeConfigFile(await response.Content.ReadAsStringAsync());
}
}
catch (HttpRequestException e)
{
Debug.WriteLine(e.Message);
}
return new List<HomeAssistantEntity>();
}
Even though I've added a try block, the application raises a System.Exception, with the message "The server name or address could not be resolved". After disabling the generic Exception type in the settings, Visual Studio told me it was a type of HttpRequestException with the message An error occurred while sending the request.
In a different part of my application, where I use a weather API, I got away with using the NetworkInformation.GetInternetConnectionProfile() to check whether there is an internet connection available prior to sending a request, but it's not a viable option here. Also, I've thought of sending a ping to the server prior to trying to fetch the data, but as far as I'm concerned, pinging is not available on the Windows 10 IoT Core.
I understood, that, you don't want the exception to be thrown, is this correct?
If yes just replace
catch (HttpRequestException e)
{
Debug.WriteLine(e.Message);
}
with
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
this will catch all occuring exceptions
I have made a game that connects to a server to get some high scores. It works fine in the first connection (and then I close the datawriter/reader, and the streamsocket as the connection is supposed to retrieve data in one shot).
But after I attempt a second connection I get a "InvalidOperationException was unhandled by user code". A method was called at a unexpected time.
I used the template for the client connection from the following:
StreamSocket sample
So how can I kill all of the all the threads in the thread pool after this operation, since I think that is what is blocking the second connection?
Also this seems to be a timing issue since it will work on the second connection if I set a break point at the loadasync methods, and step through the code?
Thanks
public async void ScoreUpdate(string input)
{
DataWriter writer = new DataWriter(socket.OutputStream);
DataReader reader = new DataReader(socket.InputStream);
string stringToSend = input;
writer.WriteString(stringToSend);
try
{
uint returnLength = await writer.StoreAsync();
uint sizeFieldCount = await reader.LoadAsync(4);
if (sizeFieldCount != sizeof(uint))
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
uint stringLengthSize = reader.ReadUInt32();
uint stringLength = await reader.LoadAsync((uint)stringLengthSize -4);
UpdateScore = reader.ReadString(stringLength);
socket.Dispose();
socket = null;
}
catch (Exception exception)
{
// If this is an unknown status it means that the error if fatal and retry will likely fail.
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
socket.Dispose();
socket = null;
}
}
}
Is there any possible that I can ensure that the application does not fall if app can not connect to the server using await socket.ConnectAsync(server) I get this exc:
But the biggest problem is I get this exception only occasionally and randomly. Try and catch completely unresponsive and applications fall. So I need something if I cannot connect firts time dont go to exception but try it again.
My code:
public async Task _connect(string token, string idInstalation, string lang)
{
try
{
if (token != null)
{
socket.SetRequestHeader("Token", token);
socket.SetRequestHeader("Lang", lang);
socket.SetRequestHeader("idInstallation", idInstalation);
}
await socket.ConnectAsync(server);
System.Diagnostics.Debug.WriteLine("Connected");
writer = new DataWriter(socket.OutputStream);
messageNumber = 1;
}
catch (Exception)
{
var dialog = new MessageDialog("Cannot connect to UNIAPPS server", "Error").ShowAsync();
}
}