C# Async Function Not Returning Value [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am integrating MailChimp API using ASYNC and JSON
****1 - Caller Section****
internal class MCReportsOverview
{
internal async Task<ReportOverview_CampaignSpecific> CampaignSpecificOverviewAsync(string campaignId)
{
string endpoint = Authenticate.EndPoint(TargetTypes.reports, SubTargetType.not_applicable, SubTargetType.not_applicable, campaignId);
var jsonTask= await BaseOperation.GetAsync<ReportOverview_CampaignSpecific>(endpoint);
return jsonTask;
}
}
**** 2 - Called Section ****
F11 hangs on the last line and doesn't return value to #1.
The data is all correct. The code for the called function is
public static async Task<T> GetAsync<T>(string endpoint) where T : class
{
string content;
using (HttpClient client = new HttpClient())
{
try
{
Authenticate.ClientAuthentication(client);
content = await client.GetStringAsync(endpoint).ConfigureAwait(false);
}
}
return JsonConvert.DeserializeObject<T>(content); // F11 hangs here and doesnt return to the calling function
}
Function Calling
This is how I am calling #1
MCCampaignsOverview overview = new MCCampaignsOverview();
var yy = overview.GetCampaignByIdAsync("aaaa1111").Result;

Related

Why is the next Line of Code Not Executing C#? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
I am new to C#. The next line of code is not executing in my small program and I am unable to figure out why.
Main method
static void Main(string[] args)
{
Console.WriteLine("Loan Approval Software");
Customer inputCustomer = new Customer();
inputCustomer.Name = Console.ReadLine();
Console.WriteLine($"Hello {inputCustomer.Name}");
}
Class
public class Customer
{
// property
public string? Name { get; set; }
}
I just ran your code and it worked fine.
Please note this line: inputCustomer.Name = Console.ReadLine();
Will halt code execution until you enter in a name to the CLI.
You can see below it worked just fine. If you are getting some kind of other error or have questions about a specific line feel free to comment, but so far code is running as it should.
EDIT FOR DEMO
static void Main(string[] args)
{
while(true)
{
Console.WriteLine("Loan Approval Software");
Customer inputCustomer = new Customer();
inputCustomer.Name = Console.ReadLine();
Console.WriteLine($"Hello {inputCustomer.Name}");
}
}

Throw Exception or Return [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have a function which my controller is calling to check if an account is valid or not.
I was wondering whats the best design to return in the function. Would it be better to throw an exception or return a error message?
Option 1, which im currently using
public void ValidateLocalAccount(Login dto) {
var user = _userService.GetUserByUsername(dto.username);
if (user == null)
throw new Exception("User does not exist");
if (user.accountType != AccountType.Local)
throw new Exception("Account is not local");
}
Controller:
[HttpPost("Login")]
public async Task<ActionResult> Login([FromBody] Login loginDto)
{
try
{
_accountService.ValidateLocalAccount(loginDto);
return Ok(await _accountService.GetToken(loginDto));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
Option 2, this seems unconventional to me
public <bool, string> ValidateLocalAccount(Login dto) {
var user = _userService.GetUserByUsername(dto.username);
if (user == null)
return (false,"User does not exist");
if (user.accountType != AccountType.Local)
return (false,"Account is not local");
return (true,string.empty);
}
Controller:
[HttpPost("Login")]
public async Task<ActionResult> Login([FromBody] Login loginDto)
{
var res = _accountService.ValidateLocalAccount(loginDto);
if(!res.item1)
return BadRequest(res.item2)
return Ok(await _accountService.GetToken(loginDto));
}
Would i be mis-using exceptions from option 1, since im kinda using it to control the flow? Thus my question is when should i choose exceptions over error codes or return null ? Which option is a better design ?. Cheers.
A failed login attempt is by no means exceptional, and therefor you should not use exceptions in such a case. That would be what Eric Lippert is calling a vexing exception - so I would definitely go with option #2.
If you are using C# 7.0 or higher, you can return a value tuple, so you could use meaningful names to it's items (rather than Item1 and Item2 in System.Tuple). If you are using an earlier version of c#, you might want to return your own struct or class, for the sake of future maintenance and code readability.
Best practice is returning proper status code like 404 (Not found), 401 (Unauthorized) or 500 (Internal Server Error).
Check out the list of HTTP status codes.
P.S. In case of writing an API, Returning status code is best practice but if you are writing web apps like razor pages then it is best to return error messages, not an exception.

How to check error message in C#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Is that a way to check error message shown after negative values? I can check if the correct exception was thrown, but what if my method won't throw an exception with negative numbers, just WriteLine to Error output stream.
public List<int> MyMethod()
{
...
try
{
//add elements to list
}
catch(Exception e)
{
Error.WriteLine("Element cannot be negative, but other elements are ok");
}
...
}
[TestMethod]
public void TestWithNegatives()
{
try
{
List<int> list = MyMethod();
//there is a negative int in list, so there'll be an error message
}
catch (Exception e)
{
//Can I check here the error message, if there isn't exception thrown in mymethod?
}
}
Since you already handled the exception and it is not rethrown, you cannot handle it again in your test.
But since you know that a message is written to Console.Error, you can check this by redirecting Console.Error to a custom StringWriter and check what was written to it like that:
public void TestWithNegatives()
{
using (StringWriter sw = new StringWriter())
{
Console.SetError(sw);
List<int> list = MyMethod();
// Check output in "Error":
Assert.IsFalse(string.IsNullOrEmpty(sw.ToString()));
}
}

Invoke method, Converting [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I'm new here. I have a question for you, maybe just easy, but I can't do it well. I have a few fields in my class:
public Player player;
public Run run;
And a code:
public void doit(string method)
{
foreach (var prop in this.GetType().GetFields())
{
foreach (var meth in prop.FieldType.GetMethods())
{
if (meth.Name == method)
{
meth.Invoke(prop, null);
}
}
}
But when I'm trying to run this problem, I have a error while running:
Object does not match target type.
In line:
meth.Invoke(prop, null);
Error appears, because "prop" isn't an Class object.
When i'm trying to do this:
Player testPlayer;
testPlayer = prop;
I have an error:
'System.Reflection.FieldInfo' to 'WindowsFormsApplication.Player'
I tried many things, but nothing work.
Can you help me plz? It's important for me :)
Thanks.
You're trying to invoke the method passing in the actual FieldInfo object, rather than the value of the field.
A simple fix would be:
if (meth.Name == method)
{
meth.Invoke(prop.GetValue(this), null);
}
However, if you're trying to find a method by name, there's an easier way:
public void doit(string method)
{
foreach (var prop in this.GetType().GetFields())
{
// Get the method by name
var meth = prop.FieldType.GetMethod(method);
if (meth != null)
{
meth.Invoke(prop.GetValue(this), null);
}
}
}
Sounds like you need to get the value of that property:
meth.Invoke(prop.GetValue(this), null);

Monotouch.Dialog takes a long time to refresh the screen [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I still working on learning Xamarin.iOs, and for a little proof on concept, I'm using Monotouch.Dialog to create an employee directory. It works great on the iPhone simulator but when I execute it on the physical devices, 3 weird things happen:
Randomly (sometime on the simulator but more often on the device), I've a timeout exception calling HttpWebRequest.GetRequestStream() in an async method. However, I create a new HttpWebRequest each time the method is called and I think I properly close and dispose everything. Here's a snippet of the code :
var wr = HttpWebRequest.Create(url);
byte[] streamContent = System.Text.Encoding.UTF8.GetBytes(body);
Stream dataStream = wr.GetRequestStream(); //timeout on that statement !
dataStream.Write(streamContent, 0, streamContent.Length);
dataStream.Close();
using (var response = (await wr.GetResponseAsync().ConfigureAwait(false)))
{
if (response != null)
{
try
{
var webResponse = response as HttpWebResponse;
if (webResponse != null && webResponse.StatusCode == HttpStatusCode.OK)
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
var responseText = reader.ReadToEnd();
result = JsonConvert.DeserializeObject<T>(responseText);
reader.Close();
}
}
}
finally
{
if (response != null)
{
response.Close();
}
}
}
}
I load my data asynchronously but if I use the async / await keywords, my application failed to launch on the device because it looks like the UI thread is waiting for my load to complete at it takes too much time. I fixed this problem by using Task.Factory.StartNew instead but I was wondering why the behavior is different on the device and on the simulator.
My last problem is that when I receive the answer from my web service, I build a list of Element that I add to my section. I've many elements but not that much (about 700). It take about 2 seconds to refresh the screen in the simulator but more than 1 minute on the device (a fourth gen ipod touch). There's the code I use to create my elements and refresh the screen (it runs async so that's why I use InvokeOnMainThread()) :
private void updateEmployeeList(IEnumerable<EmployeSummary> list, Section section)
{
if (list != null && list.Any())
{
var q = list.Select(item =>
{
StyledStringElement newCell = new StyledStringElement(item.FullName) { Accessory = UITableViewCellAccessory.DisclosureIndicator };
newCell.Tapped +=
() => _detailScreenVM.ShowDetail(item);
return newCell;
}).ToList();
_logger.Log("Items to add : {0}", q.Count);
InvokeOnMainThread(() =>
{
_logger.Log("Starting updating screen");
section.AddAll(q);
_logger.Log("Ending updating screen.");
});
}
}
Here the result of the console at execution time :
Items to add : 690 at 15:29:57.896041
Starting updating screen at 15:29:57.903079
Ending updating screen at 15:31:03.548430
It's probably something I do wrong with the async programming model but I can't figure out what exactly.
Thanks
I guess the timeout is a System.Net.WebException: The operation has timed out at System.Net.HttpWebRequest.GetRequestStream(). If you look at the Response.StatusCode property of the exception, you'll certainly find that it's a 4xx http error. Which means the server and not the client is responsible for this. So fix this server side.
You have very little time (17 seconds) for your AppDelegate.FinishedLaunching to return. If you exceed this time, your app is killed. Starting a background thread is the way to go. The restriction might be slightly different on the simulator, as it's well known that debug code in the simulator is slower than running release code on the device.
I don't know what's wrong here and don't know the internals of MonoTouch.Dialog, but a way to fix it would be to use a UITableView so the rendering of the cell only happens when required.

Categories

Resources