“The application is in break mode" C# when using throw to bubble out the exception - c#-4.0

When I am throwing exception my function to bubble it out and catch it in the task exception, rather then continuation it breaks the code- below is my code
public override void Run()
{
SendRenewalsEmail("ddd#xxx.com", " Email Body from test More", "Test Email from Service another Test");
}
private async void SendRenewalsEmail(string userEmail, string emailBody, string emailSubject)
{
string replyFromEmailAddress = "renewals#xxx.net";
string cc = "";
string bcc = "ccc#xxxx.com";
SMTPMailHelperAsync sMTPMailHelperAsync = new SMTPMailHelperAsync();
var x= await sMTPMailHelperAsync.SendEmailAsync(userEmail, cc, bcc, emailSubject, SMTPMailHelperAsync.ProcessTemplate(emailBody, "Renewals.html", emailSubject), replyFromEmailAddress);
if (x.MailSent)
{
throw new Exception("after mail Test more service");
}
}
and the Task where it is being captured
var task= Task<PluginInstance>.Run<PluginInstance>(() => {
thisPlugin.LastRunStart = DateTime.Now.ToLocalTime();
try
{
thisPlugin.Plugin.Run();
thisPlugin.LastRunStatus = Enums.RunStatus.Success;
thisPlugin.LastRunMessage = "";
}
catch (Exception ex)
{
thisPlugin.LastRunStatus = Enums.RunStatus.Failed;
thisPlugin.LastRunMessage = ex.Message;
}
thisPlugin.LastRunEnd = DateTime.Now.ToLocalTime();
return thisPlugin;
});
ListOfTask.Add(task);
Now I am trying to capture the exception in the Task exception but is not. getting below exception

You must not use async void. This is a special case, reserved only for event handlers. Your async method must return a Task:
private async Task SendRenewalsEmail(…)
Then, your Plugin.Run method is broken. It should be async as well.
Once you start with async - await, you do it to the top.

Related

PromptDialog.Choice - Invalid Type Exception

I am getting an invalid Type exception when trying to utilize PromptDialog.Choice.
Here is my code from on of my dialogs:
public async Task StartAsync(IDialogContext context) {
await context.PostAsync(ConversationHelper.CreateReschedulePromptMessage());
context.Wait(MessageReceivedAsync);
}
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result) {
var message = await result;
var Options = new[] { "Location", "Date and Time", "Both" };
if (message.Text.ToUpper().CompareTo("PICKUP") == 0) {
_rescheduleType = "pickup";
string prompt = string.Format("Is the {0} location incorrect, is the date and time incorrect, or both?", _rescheduleType);
PromptDialog.Choice(context, OnResumeFromRescheduleChoice, Options, prompt, promptStyle: PromptStyle.Auto, descriptions: Options);
}
else if (message.Text.ToUpper().CompareTo("DROP") == 0) {
_rescheduleType = "drop-off";
string prompt = string.Format("Is the {0} location incorrect, is the date and time incorrect, or both?", _rescheduleType);
PromptDialog.Choice(context, OnResumeFromRescheduleChoice, Options, prompt, promptStyle: PromptStyle.Auto, descriptions: Options);
}
else {
await context.PostAsync(ConversationHelper.CreateGenericRescheduleMessage(SUPPORTNUMBER));
}
context.Done<object>(null);
}
private async Task OnResumeFromRescheduleChoice(IDialogContext context, IAwaitable<string> result) {
var choice = await result;
}
The OnResumeFromRescheduleChoice method is firing, but the result shows failed because the ResumeAfter delegate is expecting type string, but is receiving object. Is this incorrect usage of the PromptDialog? Also the user is not being prompted the choices. I am using Bot.Builder version 3.5.5.
Move the context.Done<object>(null); call inside the else clause. You cannot call to context.Done after firing a Prompt.

Universal app: Cannot bind `StreamSocketListener` after `EnableTransferOwnership`

I am following this sample to implement a background server universal app. Here is the experimental code:
void MainPage::OnConnectionReceived(StreamSocketListener^ sender, StreamSocketListenerConnectionReceivedEventArgs^ args)
{
OutputDebugString(L"Connection received\n");
// No idea how to transfer request handling from foreground to background task!
}
void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
// Code to register background task is omitted
auto listener = ref new StreamSocketListener();
listener->Control->QualityOfService = SocketQualityOfService::Normal;
try
{
listener->EnableTransferOwnership(Task->TaskId, SocketActivityConnectedStandbyAction::Wake);
}
catch (...)
{
OutputDebugString(L"Error: cannot transfer ownership\n");
}
listener->ConnectionReceived += ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(this, &MainPage::OnConnectionReceived);
create_task(listener->BindServiceNameAsync("56789", SocketProtectionLevel::PlainSocket))
.then([this]()
{
OutputDebugString(L"Server started on port 56789\n");
auto m_httpClient = ref new HttpClient();
auto request = ref new HttpRequestMessage(HttpMethod::Get, ref new Uri("http://" + ip + ":56789/"));
auto request_operation = m_httpClient->SendRequestAsync(request, HttpCompletionOption::ResponseContentRead);
return create_task(request_operation);
}).then([this](task<HttpResponseMessage^> previousTask)
{
try {
auto response = previousTask.get();
// Code to process the response is omitted as it is irrelevant to the question
}
catch (Exception^ ex)
{
OutputDebugString(("Error: " + ex->Message + "\n")->Data());
}
});
}
At run time, I get the error: The attempted operation is not supported for the type of object referenced. which suggests that BindServiceNameAsync fails and I have no idea why as I have followed the documentation to do EnableTransferOwnership before doing the binding. What did I do wrong here?
You are getting The attempted operation is not supported for the type of object referenced. because you are using SocketActivityConnectedStandbyAction::Wake. Change it to SocketActivityConnectedStandbyAction::DoNotWake.
The following pseudo-code should give you an idea what else you need to do to make StreamSocketListener working with SocketActivityTrigger:
// TODO: task = socketTaskBuilder.Register();
socketListener = new StreamSocketListener();
socketListener.ConnectionReceived += OnConnected;
await socketListener.BindServiceNameAsync(port);
socketListener.EnableTransferOwnership(
task.TaskId,
SocketActivityConnectedStandbyAction.DoNotWake);
// This is required, otherwise you may get error:
// A device attached to the system is not functioning.
// (Exception from HRESULT: 0x8007001F)
await socketListener.CancelIOAsync();
socketListener.TransferOwnership(socketId);
Then, in the background task do:
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
var details = taskInstance.TriggerDetails as
SocketActivityTriggerDetails;
var socketInformation = details.SocketInformation;
var streamSocket = socketInformation.StreamSocket;
var socketListener = socketInformation.StreamSocketListener;
switch (details.Reason)
{
case SocketActivityTriggerReason.ConnectionAccepted:
// TODO: read, write, etc.
break;
default:
// ...
break;
}
// ...
deferral.Complete();
}

Could Func<TResult> and Func<T, TResult> have 1 name in method signature?

I have 2 methods:
private static async Task<T> GetInfoAsync<T>(MyClient service, Func<Task<T>> funcAsync, string resultText)
{
var result = default(T);
if (service != null) {
try {
service.Open();
result = await funcAsync();
service.Close();
Console.WriteLine(resultText);
} catch (Exception ex) {
service.Abort();
}
}
return result;
}
private static async Task<T> GetInfoAsync<T>(MyClient service, Func<string,Task<T>> funcAsync, string resultText, string param)
{
var result=default(T);
if (service != null) {
try {
service.Open();
result = await funcAsync(param);
service.Close();
Console.WriteLine(resultText);
} catch (Exception ex) {
service.Abort();
}
}
return result;
}
Is is possible to create 1 method for 2 functions?
Something like
"private static async Task GetInfoAsync(MyClient service, Something??, string resultText, string param)"
No, but in general you can do a partial function (see for example http://blogs.msdn.com/b/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx) that, given a function with a parameter, calls it with a fixed value for that parameter.
// The original function
Func<string, Task<T>> fullFunction = x => ...;
// The partial function
string param = "...";
Func<Task<T>> partialFunction = () => fullFunction(param);
So it would be the caller of GetInfoAsync that would need to create this partialFunction and pass it to GetInfoAsync.

MonoTouch return a string from a Task

I am using following code to call a web service in update UI using Task
//------- REFRESH BOOK LIST ------
public Task<string> GetBookList()
{
return Task.Factory.StartNew(() => {
// GET BOOK LIST
WebServiceController webServices = new WebServiceController ();
string bookList = webServices.GetBookList ();
if (bookList.Contains("BooksList")) {
// PARSE
ParseListData parseData = new ParseListData ();
parseData.ParseList (bookList);
}
return bookList;
});
}
I call this code using
GetBookList ().ContinueWith (task => {
if (task.IsFaulted) {
// STOP ACTIVITY INDICATOR
RemoveActivityIndicator (true);
throw new AggregateException (task.Exception.InnerException.Message);
}
// RUNS WHEN TASK IS FINISHED
InvokeOnMainThread (() => {
// STOP ACTIVITY INDICATOR
RemoveActivityIndicator (true);
string bookList = task.Result;
if (bookList.Contains("Error:") || !bookList.Contains("BooksList"))
{
// SHOW ERROR MESSAGE
}
});
});
If there is an error in the return string (bookList) then i want to check for bookList.Contains("Error:") as above and show error message. The problem in that is bookList string is assigned in the Task GetBookList() function. How do i get that value in GetBookList ().ContinueWith to show error.
How to write a Task in above situation to return a string.
Use Task<string>, then the Task's Result property can be used to store your String value.

Problems reading from Microsoft Messaging Queues in C#

I have problems reading from my MSMQ. When I write to the queue, it works perfectly, but when I try to read that message from the queue, I get the following exception: "The queue does not exist or you do not have sufficient permissions to perform the operation." The queue does exists, and I have full permissions on the machine and queue. Here is my code:
public string path = #".\private$\";
public void WriteToQueue(string QueueName, object messageObject)
{
try
{
path = path + QueueName;
MessageQueue msmq = null;
if (!MessageQueue.Exists(path))
{
msmq = MessageQueue.Create(path);
}
else
{
msmq = new MessageQueue(path);
}
msmq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string)});
msmq.Send(messageObject);
msmq.Close();
}
catch (MessageQueueException ex)
{
System.ArgumentException argEx = neArgumentException(ex.ToString());
throw argEx;
}
path = #".\private$\";
}
public string ReadQueue(string QueueName)
{
try
{
path = path + QueueName;
MessageQueue msmq = new MessageQueue(path);
string msg;
msmq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string)});
msg = msmq.Receive().Body.ToString(); //exception is thrown here
path = #".\private$\";
return msg;
}
catch (Exception ex)
{
return null;
}
}
can the problem maybe be with reading it as type of string? Maybe not in the right format?
Try this:
public string path = ".\\private$\\";
'#' doesn't work for me too.

Resources