Connect to server with connect async - c#

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();
}
}

Related

FluentFTP connection broke but no exception

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.

TLsharp CHANNELS_TOO_MUCH Exception

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();

Mono Async WCF Exception--Broken or My Mistake?

I have a WCF service running on CentOS 6.6 + Mono 4.2.1. The service works if contract methods are synchronous, but I would like to make use of async if possible (since there is a lot of I/O intensive tasks that go into each request). When I try and implement any of the service as async, though, I get an exception when I run under Mono. I've included a dummy test method for repro:
Server:
[OperationContract]
Task<string> GetUrl(string url);
async public Task<string> GetUrl(string url)
{
MailUtils.LogText(LogLevel.Verbose, () => String.Format("Got request for {0}", url));
string result = String.Empty;
try
{
using (var client = new WebClient())
result = await client.DownloadStringTaskAsync(url);
}
finally
{
MailUtils.LogText(LogLevel.Verbose, () => String.Format("Leaving GetUrl(); Got {0} byte(s)", result.Length));
}
return result;
}
Client (command line utility):
static void Main(string[] args)
{
if (args.Length == 2 && args[0] == "-testasync")
{
try
{
MailSorterServiceClient client = new MailSorterServiceClient();
var task = client.GetUrlAsync(args[1]);
task.Wait();
Console.WriteLine(String.Format("Success: Got {0} byte(s)", (task.Result ?? "").Length));
}
catch(Exception ex)
{
Console.WriteLine(ex.InnerException.Message);
Console.WriteLine(ex.InnerException.StackTrace);
}
return;
}
So far as I can tell the server does not receive the request and the client gets an exception:
Object reference not set to an instance of an object
at System.ServiceModel.Dispatcher.BaseMessagesFormatter.DeserializeReply (System.ServiceModel.Channels.Message message, System.Object[] parameters) [0x000ea] in /root/src/mono-4.2.1/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/BaseMessagesFormatter.cs:289
Additional:
The client generated by Visual Studio has two methods:
Task GetUrlAsync(string url)
and string GetUrl(string url)
If I change my client code to call GetUrl() the request makes it through to the server process and the server log shows:
[12/11/2015 3:06 PM]: Got request for http://www.google.com/
[12/11/2015 3:06 PM]: Leaving GetUrl(); Got 188337 byte(s)
... but the client returns before it receives the response from the server (client gets back an empty string and no indication of an error).
The async code works as expected under Windows.
Is this a bug in Mono or am I doing something wrong?
I am okay with blocking (with a timeout_ on the client but want the server to be async). Any help is appreciated.
Note: A did see a similar sounding problem on Stack Overflow but it sounds like it was addessed in Mono 4.2.
Change your code like this;
Your main method;
if (args.Length == 2 && args[0] == "-testasync")
{
CallWebService(args[1]);
}
Then your web service call;
private static async void CallWebService(string url)
{
try
{
using (MailSorterServiceClient client = new MailSorterServiceClient())
{
var result = await client.GetUrlAsync(url);
Console.WriteLine(result.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.Message);
Console.WriteLine(ex.InnerException.StackTrace);
}
}

Do not allow incoming call Lync Api or disabling sounds for incoming call

I have developed a windows application using Lync api. My client want to disable incoming calls to this application. So i have added some thing like this. I am able to cut the call but there are few rings before im able to do that
private void ClientInitialized(IAsyncResult result)
{
try
{
//registers for conversation related events
//these events will occur when new conversations are created (incoming/outgoing) and removed
client.ConversationManager.ConversationAdded += ConversationManager_ConversationAdded;
client.ConversationManager.ConversationRemoved += ConversationManager_ConversationRemoved;
}
catch (Exception ex)
{
MessageBox.Show("Problem in adding/removing conversation", "Bella IVIS", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void ConversationManager_ConversationAdded(object sender, ConversationManagerEventArgs e)
{
try
{
var _client = client;
if (e.Conversation.State == ConversationState.Active)
{
for (int intLoop = 0; intLoop < _client.ConversationManager.Conversations.Count; intLoop++)
{
_client.ConversationManager.Conversations[intLoop].End();
}
_client = null;
return;
}
}
}
I do not know if there is a way to capture conversation before Conversation_Added event. However, if the Lync status is not of any relevance to you then you change the Lync Status to "Do not disturb". This way you would never get any incoming request (unless the user Lync setting allow to do so)
var newInformation =new Dictionary<PublishableContactInformationType, object>();
newInformation.Add(PublishableContactInformationType.Availability, ContactAvailability.DoNotDisturb);
try
{
this.lyncClient.Self.BeginPublishContactInformation(newInformation,(result) => this.lyncClient.Self.EndPublishContactInformation(result) , null);
} catch {}

Windows 8 Store App and Visual Studio 2012, how to stop loadasync() method?

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;
}
}
}

Categories