Any new method on checking internet connectivity using .NET? [closed] - c#

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
}

Related

Getting Wifi RSSI or signal strength using WlanAPI and IpHlpAPI [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 24 days ago.
Improve this question
I'm trying to recreate the functionality of the wifi icon inside the Windows task bar using this library and C#.
https://github.com/dahall/Vanara
To get the current network interface I am calling GetBestInterface from IpHlpAPI and it seems to be returning the right index. However I'm struggling on how to get the RSSI or signal strength value of the wifi network that's attached to this interface. Using this data I could recreate the wifi icon with 1 bars, 2 bars, 3 bars, ect..
Using WlanAPI I can call WlanGetAvailableNetworkList which returns a list that has the signal strength value for each network. There doesn't seem to be any data to connect these two things, so obviously I'm missing something.
Anyone have any ideas on the approach I should take?
You could try to use WlanQueryInterface function with wlan_intf_opcode_current_connection to query various parameters of a specified interface. You could get a percentage value that represents the signal quality of the network from WLAN_ASSOCIATION_ATTRIBUTES structure.

Server response best practice [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 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

Wrap method in other method with different name to make code more readable - Good or Bad? [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 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.

Clear garbage memory of other software in c# [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
this is a strange question.
In my work I use a software (that NO one can modify or take vision of source code), this software, unfortunately, is very bad. It uses, when launched, about 1 gb RAM, but running and being used, it accumulates data in ram and after few hours it occupies over 4gb of ram, and can accumulates more and more if not stopped. Since not all pc of my company can handle this, they crash. Is there a way to clear data unused in ram from other software programming in c#?
I just need an hint, i program in c#.
I'm sorry for my English, and if this question is somehow wrong.
Thanks for time.
Edit: I will add some information about this software understand better what I can do, and what I cant't.
Since i would not gain anything hacking this software, but I would have a better life (and not only me but my co-workers and employees too), i don't see any issue in hacking this software. (well, my chief has no problems, and his chief too).
I will try the Arunasr hint, I program in c# and know this function. I will only have to decompile it.
I have to delete this question?
Thanks for all replies and all help you gave to me.
There is no such way, outside of killing and restarting that task. If it is a Windows Service, you can use Powershell, command line utility SC.exe, or this c# code:
public static void RestartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}
Reference: http://www.csharp-examples.net/restart-windows-service/
.NET runtime garbage collector tends to be lazy and only collects when free memory is about to run out. You can force garbage collection with GC.Collect(), but mind the performance: it is expensive if you do it frequently.
If the library really accumulates data (i.e. data remains references and GC cannot touch it), there is little you can do other than hack up the library, figure out what eats up the memory and release the unnecessary objects. It is not difficult to decompile the .NET bytecode. In the extreme, you can modify the assembly bytecode using reflection after it has been loaded. I would not recommend it unless you are desperate.
You can use GC to track real memory usage stats.

What's the most professional way for login control in ASP.NET? [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
Say, we are not using forms authentication or membership. When a user requests for any of the pages of the application, she needs to be redirected to login page.
This way, each page needs to have an authentication check on the Page_Load(). But what if we have over 500 pages.
Any chance to use sth like static classes with static properties or creating your own http handlers?
This is too broad of a question with a few aspects, including :
How to manage a User's Session
How to manage multiple user accounts being logged in
How to perform the login process
Managing a user's state must be independent of anyone else's actions. Therefor, you cannot rely on static properties. This presents the question of "Well, how do I keep track of it without it being static?" One of the answers is to use Session information. For example, during an Ajax request to the server you could do this :
if (HttpContext.Current.Session["LoggedIn"] != null)
{
object oValue = HttpContext.Current.Session["LoggedIn"];
bool bResult;
if (bool.TryParse((string)oValue, out bResult) == true)
return bResult
return false;
}
else
return false;
This solves the first two issues and opens a door to creating a hanlder class that knows YOUR specific session keys and patterns for getting different kinds of values.
As for the third issue you will face - No one can give you a concrete answer. Your design and data structure will determine how you validate and track your users.

Categories