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 1 year ago.
Improve this question
I'm developing a RESTFUL web server that have some API REST used by android clients. It's the first time I've done API REST so i followed several guides to made it. Now when client make a GET request to get something, the server return the data in JSON, but not additionals information. Now that I'm making the android application I understand that this type of managment isn't good because i can't handle the errors like 401, 404, etc from application to show errors to the user (I use retrofit 2 with coroutines).
Can someone explain me the best method to make the responses from the server? I understand that I have to make a generic class like Response that have a Code and an Error_Message, and I have to extend this class for all my responses to add the data required from the client. But after that how I handle the response from my application? I can't make two different classes (one for errors and one for success responses).
Can someone help me?
The type of solution you propose, is not REST. A common practice in the past was to use only 200 success responses and POST everything. REST APIs by convention use the status codes to convey a meaning. You should also always think of error 500, because this will happen and your application should handle it.
You also might be interested in this: Microsoft best-practices api-design
I understand that this type of managment isn't good because i can't handle the errors like 401, 404, etc from application to show errors to the user
I don't see why you can't do that. There is perfectly good code to handle the requests.
#Override
public void onResponse(Call<YourModel> call, Response<YourModel> response) {
// All the 20x responses
if (response.isSuccessful()) {
} else if (response.code() == 401) {
} else {
}
}
You can also use an interceptor, if you are using OkHttp Check here for interceptor code
Related
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 2 years ago.
Improve this question
I'm working with Anonymous Pipes to be able to communicate between 2 applications. I have 3 classes. A base class Node which holds the incoming and outgoing streams and methods like Read and Write. Deriving from this class are Client and Server. They each initialize respectively their AnonymousPipeClientStream and AnonymousPipeServerStream and have a method to sync with each other.
Having above code allows me to communicate between the 2 applications. I start the "server" application. This application starts the "client".
When both applications are started I need to send some arguments from the server to the client. The client is basically waiting for messages from the server. On the server I need to start the reading of the arguments on the client, then send the arguments and end the reading on the client so it's free to start another task. To do this I simply need to
write the start command,
write the arguments,
write the end command and
wait for the client to confirm the task is finished.
public void ServerStartClientTask()
{
Write(ReadInputs); // (1)
Write(Arg1); // (2)
Write(Arg2); // (2)
Write(ReadInputs); // (3)
while (WaitFor(ReadInputs)); // (4)
}
This is "straightforward" when you're the writer of the code (in my opinion) and is the convention how communication with the client has to happen. I wanted to make it more clear for myself and my colleagues so I came up with the following:
public void StartClientTask(Flag flag)
{
Write(flag);
}
public void EndClientTask(Flag flag)
{
Write(flag);
while (WaitFor(flag)) { }
}
public void ServerStartClientTask()
{
StartClientTask(ReadInputs); // (1)
Write(Arg1); // (2)
Write(Arg2); // (2)
EndClientTask(ReadInputs); // (3) and (4)
}
This code merely wraps code into another method to make it more readable how the communication is dome with the client.
Now for the question.
This example is not limiting to my question but just the use case I have now and to introduce my question. Is doing this wrapping of code with just other names a good or bad practice? Both examples work perfectly fine, they're just written differently. Is there a benefit to doing the 2nd approuch or would you rather just write a comment at (1), (3) and (4) in the 1st example?
In my opinion this is a very good practice and I use it all the time.
Makes the code very readable for other developers.
this way I rarely have to use comments inside my methods because the names of the methods explain what is happening.
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 4 years ago.
Improve this question
I already read some of the questions posted here and I found this post to be the most reliable regarding this matter: What is the best way to check for Internet connectivity using .NET?
But what if the network where the interface is connected have google blocked? (e.g. Internet in China)
If you're checking for internet connectivity, you probably have a reason... meaning you're looking to use some specific web resource. So check against that resource.
Even better, don't check at all. Internet services can go up or down at any moment... including the moment in between when you run your check and when you try to use the service. That means anything you do has to be able to handle failure anyway. So just don't run the check; put the work into your exception handler instead.
I know that may sound slow, or strange to use exception handling for flow control. But the main reason not to use exceptions for flow control is it's nearly the slowest thing you can do in all of computer science. You know what's even worse? Waiting for network packets to travel half way around the world or timeout, that's what.
In the rare case when you just want to show general internet status to the user, you can do it the same way Microsoft does, and use www.msftncsi.com.
If what you want is to check the state of the internet in .Net without depending on WebClient class or Google, this is the best way
First, import the DLL wininet
[System.Runtime.InteropServices.DllImport("wininet.dll")]
Then, call the static extern bool InternetGetConnectedState(...)
This returns true if the internet connects and false if it can not connect, regardless of Google:
[System.Runtime.InteropServices.DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
public static bool IsConnected()
{
return InternetGetConnectedState(out int description, 0);
}
Where:
if(IsConnected())
{
//Internet is connected
}
else
{
//Internet is not connected
}
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 4 years ago.
Improve this question
I have hard time finding the best way to deal with default values, when deserializing json into a class model in my AspNetCore WebApi.
Whenever a client makes a PUT request to the api, how should i figure out if a property was set to null in the request - or not set at all in the request?
At this moment I use the [FromBody] Attribute for deserialization into a class type, along with ModelValidation for requiring fields etc. But once the json request has been deserialized, how can i tell if eg. a "string name" property was explicitly set to null, or not set at all in the json requst, but defaulted to null?
It the case it was not set at all, i don't want to change the state of the actual model being saved in DB, for that property.
The problem arises when a client uses PUT, and a new field has been implemented, which the client does not know about. I don't want clients overwriting a "new" value to null, that they have no intention of setting in the first place.
Is there any standard or best practice for handling this? I can't imagine i'm the only one with this problem. Implementing my own json deserializer, or, implementing versioning for the endpoint for the sake of adding an additional field, seems a bit over the top.. And coordinating a deploy for all the clients at the same time (where the handling of the new property/value is handled), is not an option either.
All suggestions appreciated.
Regards Frederik
I think you're not using proper HTTP method and that is source of your problem. HTTP PUT means that you want to overwrite resource at request url with what is in request body. And because C# doesn't have undefined then it cannot differentiate NULL from not provided property.
If you need to do partial modification then you should use PATCH instead
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 8 years ago.
Improve this question
I am building an MVC app and in this appllication there are actions that implies some things. So we wish to warn our customers / users using mailing system. I'm building both a local application and a web store, so I'll need to send a lot of mails sometimes.
I am currently using MvcMailer why does nicely its job, but my main concern is that since it occurs during a normal method call (ex: result of an operation, then:
MvcMailMessage msg = mailer.NewOrder(emailTo);
msg.Send();
And the message goes, it takes a while. And since this kind of operation might be called quite a few times, it will overall slow down the whole process, which I do not wish.
So my question is: how should I handle mail processing? Is there an asynchroneous thing I may use that will do the job? Do I store them in a database table and send them sometimes? I've heard about Task in windows .Net, but I've never used any, is that an option?
I'm looking for suggestions, so feel free to share your opinion! Thank you!
You can use SmtpClient.SendMailAsync using the async-await keywords
public async Task SendSmtpMailAsync()
{
SmtpClient smtpClient = new SmtpClient();
MailMessage mailMessage = new MailMessage("FromAddress", "ToAddress", "Subject", "Body");
await smtpClient.SendMailAsync(mailMessage);
// Possibly do more stuff here.
}
When you await on an asynchronous method, control yields back to the caller. What that means is that the ASP.NET can process messages in the meantime using the thread that returned to the ASP
NET ThreadPool from that same method. When the method finishes, it will return back to the awaited line and continue execution.
Note that using this async alone wont return the request to the caller, it will simply let you process more requests in the meanwhile. What you can do is use this method in correlation with a producer-consumer style collection, like BlockingCollection<T>, add your messages to it and return the response to you caller. In the background, use SendMailAsync to execute these requests.
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 4 years ago.
Improve this question
Here's an example. I saw a "ReadOnlyDictionary" class online and it had the following code:
void ICollection.CopyTo(Array array, int index)
{
ICollection collection = new List<KeyValuePair<TKey, TValue>>(this._source);
collection.CopyTo(array, index);
}
For example, should I check array for a null argument, or should I let the the CopyTo method do that for me? It just seems a bit redundent, but if best practices say to check everything in your own method, then that's what I want to do. I'm just not sure what "best practices" says to do.
I think it wise to say if you plan to do something with array that relies on it NOT being null then you should check this. But if it just a pass through then I don't see a reason why you should check.
Another thought is if the method gets complicated in the future. You might still want to check for it because someone may modify the code and use array without realizing that it might be null. This is only for maintaining good code in my opinion.
If somebody else's library or API* is going to complain about my inputs, I don't want to give it those inputs, I want to validate and/or complain first. This is especially important if calls into external APIs are expensive, such as a database or web service call.
You know what inputs the API is going to reject. Don't send those, invalidate them in your own public API.
*Note: I consider my own public boundaries to be the same thing. If I have class Foo that does not like given arguments, if I invoke Foo, at some level before doing so, I'm going to validate my arguments. You don't do this at every level (assume there are layers of indirection, maybe, private methods calling into private methods, etc.), but at some reasonable public boundary, I will validate. Validate early, don't let complicated logic or work be done when it's just going to be rejected anyway.