IsNetworkavailable property always returning true - c#

How to find weather my windows phone internet or network connection is on in c# code? For me, isnetworkavailable returns true always.

You may try to use GetIsNetworkAvailable which returns a result based on the network interfaces available. Like this:
bool isNetworkAvailable=NetworkInterface.GetIsNetworkAvailable();
if(!isNetworkAvailable)
{
//your code
}

The only way to find is to subscribe to the event DeviceNetworkInformation.NetworkAvailabilityChanged.
Once you have received that event (which is guaranteed on happen on changes of the network), then you will know whether you are connected or not by querying the various apis here.
There is a sample code that will exactly tell you how to do so.
You can also check what kind of network you are on with NetworkInterface.NetworkInterfaceType, however be careful as calling this API might freeze the calling thread (or the UI if you're running off the main thread) under certain circumstances (connecting to a wifi for instance is one of them).
You should be fine however if you follow the examples, once again !

Related

TAPI TE_CALLINFOCHANGE never fires

I have been looking at TAPI, I can detect calls, make calls, answer/reject calls... however the only reason im even looking at it is to get the CallerID.
I know the hardware I am using works for CallerID as I have used other software to check before hand.
I have tired using the COM obeject directly, using JulMar's wrapper, and using TAPI 2.0 and I am yet to find a way that works.
From my understanding the callerID should come through via TE_CALLINFOCHANGE.
The problem is the event never fires, and the callerID is always blank on the other events.
Has anyone had success with this?
Thanks
May be the TSP doesn't send the message about a call info change, and the information never changes because it is present from the start of the lifetime of the call.
The call info is always present for a call and you can ask for it at any time. Just retreive it from the call, with ITCallInfo::get_CallInfoLong (lineGetCallInfo).

How to gracefully handle calling a method that may never return

In my C# MVC4 ASP.NET code (in a method on a controller) I call a function that I know has the possibility that it may never return. It is a call to a Microsoft object that does not raise and error, does not time out, just hangs (and hangs and hangs).
I think I have found the cause of the specific incidents of why this has happened, but the general problem worries me and I want to guard against it (as it causes general problems on the server, rather than just isolated problems to the individual user). I want to know the most graceful way of handling this sort of problem.
The method I am calling is LocalReport.Render and this Google search shows a number of people with a number of problems where this method never seems to return.
Maybe try calling the method on a different Thread ? and abort the thread after a timeout ?
Although not a neat solution at all, but not a lot of options available in case there is no misconception about why the method hangs.
Having looked at this answer to a similar question I think the least worse solution is to wrap the offending call (to LocalReport.Render) into a separate Process and app domain. I will then kill the process if it starts behaving erratically.

C# Eventing across IPC

Ok, long story short I have a Windows service that handles Win32_VolumeChangeEvent and logs USB disk device arrivals to the Event Log and to a SQL database. An additional component to this is a hidden UI (WinForms) which loads in the user session at login - this pops up a message box reminding users of company policy about USB keys etc. AFAIK, this was the best way to go since services can no longer run in interactive mode.
Anywho... architecturally, v1 of this little thing ran with the UI component handling WndProc messages for device insertion, then passed the device identifier through IPC (named pipes) to the service which would handle WMI methods / EventLog writing (as not all users have local admin rights). This had the downside of the UI element being process killed and no longer detecting device insertions.
So, current version is that the service handles Win32_VolumeChangeEvents and gets the needed details from the device, then logs to EventLog and SQL. All is outstanding and works perfectly. Except now I'm wondering what the best way to trigger the UI into displaying the popup is.
I've researched around Google and here, looking for ideas about eventing over IPC, so I can just subscribe to an event from the UI component and fire it within the service, but I'm not finding much that jumps out as being helpful. I'm also constrained to .net2, so WCF is out of the picture (although I'm not afraid of p/invoke if you want to go that way).
So. How would you do it? Links, thoughts, ramblings, pseudocode, actual code... all is appreciated. I'm trying to stick to what I believe is best practice, although I also think programming is a bit of an art form and my best practice may be someone else's horror story.
So SO - what would you do? Let me know if I need to clarify :)
Back in the bad old days of Windows API programming, we'd sometimes use RegisterWindowMessage to register a unique message ID that (presumably) only our window knew how to handle. We could then trigger that window from another application by calling PostMessage with a window handle of HWND_BROADCAST, and the msg parameter being that unique message value. That works great if everything you want to share between the processes can fit into two DWORD values (wparam and lparam). Sharing more data can be done if you allocate global memory and pass a reference as one of the parameters.
That should still be possible with .NET. Certainly there's no trouble calling PostMessage. As for handling the message in the UI code, you have to override the Form's WndProc. See How do I send/receive windows messages between VB6 and c#? for an example.
You could do something with named events, although that would only notify the UI that some change had occurred. It wouldn't actually tell you what happened. I suppose, if there's only a small set of possible events, you could have multiple events, but that gets complicated pretty quickly.
You could go the named event route and use shared memory (memory mapped file) to share the state.
Or, you could set up sockets, named pipes, TcpListener/TcpClient, or even a UdpClient. All should work, with varying degrees of complexity and/or reliability.
The only idea that comes to my mind is to have a service check the state of the UI application periodically and restart it if it has been killed. There seems to be no standard module that would run within user's session and let the service send notifications to this module. There exist third-party solutions but they can be killed (not saying that they should be installed in order to be used).
Update: after re-reading the question I think that maybe your UI doesn't receive windows messages, so you need another mechanism. Why not create a Semaphore synchronization object in service and wait for it in UI process (in a separate thread)?

Looking for best practise for writing a serial device communication app

I am pretty new to serial comms, but would like advise on how to best achieve a robust application which speak to and listens to a serial device.
I have managed to make use of System.IO.SerialPort, and successfully connected to, sent data to and recieved from my device. The way things work is this.
My application connects to the Com Port and opens the port.... I then connect my device to the com port, and it detects a connection to the PC, so sends a bit of text. it's really just copyright info, as well as the version of the firmware. I don't do anything with that, except display it in my 'activity' window.
The device then waits.
I can then query information, but sending a command such as 'QUERY PARAMETER1'. It then replies with something like:
'QUERY PARAMETER1\r\n\r\n76767\r\n\r\n'
I then process that. I can then update it by sending 'SET PARAMETER1 12345', and it will reply with 'QUERY PARAMETER1\r\n\r\n12345\r\n\r\n'.
All pretty basic.
So, what I have done is created a Communication Class. this call is called in it's own thread, and sends data back to the main form... and also allows me to send messages to it.
Sending data is easy. Recieving is a bit more tricky. I have employed the use of the datarecieved event, and when ever data comes in, I echo that to my screen. My problem is this:
When I send a command, I feel I am being very dodgy in my handling. What I am doing is, lets say I am sending 'QUERY PARAMETER1'. I send the command to the device, I then put 'PARAMETER1' into a global variable, and I do a Thread.Sleep(100).
On the data received, I then have a bit of logic that checks the incoming data, and sees if the string CONTAINS the value in the global variable. As the reply may be 'QUERY PARAMETER1\r\n\r\n76767\r\n\r\n', it sees that it contains my parameter, parses the string, and returns the value I am looking for, but placing it into another global variable.
My sending method was sleeping for 100ms. It then wakes, and checks the returned global variable. If it has data... then I'm happy, and I process the data. Problem is... if the sleep is too short.. it will fail. And I feel it's flaky.. putting stuff into variables.. then waiting...
The other option is to use ReadLine instead, but that's very blocking. So I remove the data received method, and instead... just send the data... then call ReadLine(). That may give me better results. There's no time, except when we connect initially, that data comes from the device, without me requesting it. So, maybe ReadLine will be simpler and safer? Is this known as 'Blocking' reads? Also, can I set a timeout?
Hopefully someone can guide me.
Well, Thread.Sleep() is blocking too. Much worse, actually, because you'd have to specify a sleep time that is always safe, even if the machine is under heavy load. Using ReadLine() is always better, it will be quicker and it cannot fail.
Note that your example doesn't require the client code to wait for a response. It can simply assume that the command was effective. All you need is an Error event to signal that something went wrong.
If there is a command that requires the client code to get the response that you should offer the option to wait as well as get the result asynchronously. That gives the client code options: waiting is slow but easy, async is difficult to program. It is a very common pattern in the .NET framework, the asynchronous method name starts with "Begin". Check the MSDN Library article about it.
You also should consider delivering asynchronous notifications on the thread that the client code prefers. The SynchronizingObject property is a good pattern for that.
If you do all of your reads on a background thread, then I don't see any problem with using ReadLine. It's the simplest and most robust solution.
You can use the ReadTimeout property to set the timeout for read operations.
You may want to read this Serial Port

How to implement a SoapHttpClientProtocol

Since this question tells me that SoapHttpClientProtocol is not thread safe. And, my real life testing tells me this is true, as my SoapHeader properties keep getting mixed up between calls. Is there a way to make sure that I can use this across threads and keep my properties correct? And make sure I don't run into the example given in that question of one thread thinking the connection is open, when another thread has closed it? Do I need to worry about the soap header values after my request has been made? How can I verify the properties are as I set them until the request has been issued?
The first thing I would ask is does your service work correctly if you do not make it multi-threaded. If you make subsequent calls do they all work correctly and give you the desired results? If not then there is a problem on the server side more than likely.
To see what you are sending you could serialize down the soap message before it goes. Make sure it's getting generated correctly.
My job blocks access to a lot of websites but CodeProject has some examples if I remember correctly.
If the single thread works have the serialization layer in place and have it write the files to disk in your multi-threaded scenario. Then you can see what is working and what is not by what your code thinks it's sending.
More than likely your calls are getting mixed by the server since you are trying to establish multiple connections while it may be seeing your endpoint as one value, kind of like being behind a NAT firewall. Which means you may be getting a connection but one of your other threads gets its message through first. If that is the case you could try spinning each thread up in it's own app domain and see if it does anything for you. Not saying that it will work, but not sure off the top of my head what else may be available for you to try.

Categories

Resources