This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you retrieve a list of logged-in/connected users in .NET?
I have hosted WCF service in IIS on a machine. Now i want to write a method in the service by which I could detect whether the hosted machine is currently being used by any Remote Desktop Connection or not.
Is there any other better way to find out this, and what are the exact code APIs by which RDC connection is detected.
I am using C#.net, framework 3.5
There are two options for you. You can use the P/Invoke Calls to the WSTAPI library however it is easy to mess stuff up and get resource leaks.
Your other option is to use the WTSAPI wrapper library Cassia. I have used that before and it is easy to use and the classes are fairly self documenting.
In Cassia your function would simply be
public bool IsComputerUsedByTS()
{
var tsMgr = new TerminalServicesManager();
var localSvr = tsMgr.GetLocalServer();
var sessions = localSvr.GetSessions();
foreach(var session in sessions)
{
if(session.ConnectionState == ConnectionState.Active ||
session.ConnectionState == ConnectionState.Connected) //Add more states you want to check for as needed
{
return true;
}
}
return false;
}
I did not test the above, and I think "active" is used if you are a console session where "Connected" is for RDP sessions. there are lot more states, look at the enum for all of the options.
RDP servers listen on port 3389 by default (but can be configured differently).
Therefore (even not being 100% reliable) this can be used to check any active RDP connections.
bool inUse = IPGlobalProperties.GetIPGlobalProperties()
.GetActiveTcpConnections()
.Any(tcp => tcp.LocalEndPoint.Port == 3389);
EDIT
I added #t3hn00b's suggestion.
int port = 3389;
using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(#"SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp", false))
{
if (key != null)
{
object value = key.GetValue("PortNumber");
if (value != null) port = Convert.ToInt32(value);
}
}
namespace: System.Net.NetworkInformation
Related
I am trying to reference "Windows.Networking.Connectivity" classes in my desktop application. I am basically interested in handling metered connections in my app.
Basically what I am trying to do is simple:
var connectionCost = NetworkInformation.GetInternetConnectionProfile().GetConnectionCost();
if (connectionCost.NetworkCostType == NetworkCostType.Unknown
|| connectionCost.NetworkCostType == NetworkCostType.Unrestricted)
{
//Connection cost is unknown/unrestricted
}
else
{
//Metered Network
}
The only method I know of that allows a desktop application to reference UWP assemblies is by manually editing the project file and adding the following line to the csproj file:
<TargetPlatformVersion>8.0</TargetPlatformVersion>
Applying the code and "hack" works fine but the problem is that doing so will prevent my app from running on Windows 7 which I need to support.
I was wondering if there is a way to reference UWP assemblies in a desktop application without having to drop support for Windows 7.
And since for the time being I only want to check if a connection is metered, I am open to suggestions about how to get this information without referencing Windows assemblies.
I found a way to use reflection and call UWP methods without having to specify a target platform. For my case this is what I did:
var networkInfoType = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType=WindowsRuntime");
var profileType = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType=WindowsRuntime");
var profileObj = networkInfoType.GetTypeInfo().GetDeclaredMethod("GetInternetConnectionProfile").Invoke(null, null);
dynamic profDyn = profileObj;
var costObj = profDyn.GetConnectionCost();
dynamic dynCost = costObj;
var costType = (NetworkCostType)dynCost.NetworkCostType;
if (costType == NetworkCostType.Unknown
|| costType == NetworkCostType.Unrestricted)
{
//Connection cost is unknown/unrestricted
}
else
{
//Metered Network
}
I am writing a external application for Attachmate's Reflection for IBM 2014, In that application I am trying to create relfection application with exisiting session file. The application is getting created successfully but its not visible to user, I tried several way to do that but had no luck yet.
If anybody has done this or know what needs to be done to make terminal visible please reply.
Following is piece of code that I am using to do so,
using Attachmate.Reflection;
using Attachmate.Reflection.Framework;
using Attachmate.Reflection.Emulation.IbmHosts;
using Attachmate.Reflection.UserControl.IbmHosts;
using Attachmate.Reflection.UserInterface;
Application reflectionApplication;
reflectionApplication = MyReflection.CreateApplication("app", true);
IIbmTerminal terminal =(IIbmTerminal)reflectionApplication.CreateControl(#"C:\mypath\test.rd3x");
reflectionApplication = MyReflection.ActiveApplication;
IFrame frame = (IFrame) reflectionApplication.GetObject("Frame");
frame.Visible = true;
The best way to do this is to leverage an existing session file (that you would normally load within Reflection). This way you don't have to worry about hostname, port via code.
Here is a boilerplate for this, which I have successfully been using.
Attachmate.Reflection.Framework.Application reflectionApplication = null;
reflectionApplication = MyReflection.CreateApplication("myWorkspace", true);
if (reflectionApplication != null)
{
IIbmTerminal terminal = (IIbmTerminal)reflectionApplication.CreateControl(
#"C:\ProgramData\Attachmate\Reflection\<your session file>.rd3x");
if (terminal != null)
{
terminal.Connect();
//You can also use AfterConnect event to wait for the connection.
while (!terminal.IsConnected)
{
System.Threading.Thread.Sleep(500);
}
IView sessionView;
IFrame theFrame = (IFrame)reflectionApplication.GetObject("Frame");
sessionView = theFrame.CreateView(terminal);
IIbmScreen screen = terminal.Screen;
screen.WaitForHostSettle(6000, 3000);
}
else
Console.WriteLine("Can not create the control.");
}
else
Console.WriteLine("Failed to get Application object.");
This question already has answers here:
Check internet connection in Silverlight
(3 answers)
Closed 7 years ago.
I created silverlight project.That is dashboard information project.
I created two types of dashboard, One is Dashboard.Xaml another one is Dashboard.Html.
Now requirement is If internet connection available means we show Dashboard.Html other wise if
internet connection is not available means we show Dashboard.Xaml
How to check Internet connection is connected or not connected in c#?
How to trigger automatically internet is Connected means-Dashboard.Html or not-connected means-Dashboard.Xaml?
Please Help Me...
Using
bool IsNetIn= NetworkInterface.GetIsNetworkAvailable();
You can ping valid address on the internet.
public bool PingHost(string nameOrAddress)
{
PingReply reply;
using (var pinger = new Ping())
{
reply = pinger.Send(nameOrAddress);
}
bool pingable=false;
if (reply != null) pingable = reply.Status == IPStatus.Success;
return pingable;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SqlDataSourceEnumerator.Instance.GetDataSources() does not locate local SQL server 2008 instance
I am using code below to get all instance names and server names in my local machine, but it seems it is returning only one instance; how to get all list of instance name and server name in my local machine?
string myServer = Environment.MachineName;
DataTable servers = SqlDataSourceEnumerator.Instance.GetDataSources();
for (int i = 0; i < servers.Rows.Count; i++)
{
if (myServer == servers.Rows[i]["ServerName"].ToString())
{
if ((servers.Rows[i]["InstanceName"] as string) != null)
{
CmbServerName.Visibility = Visibility.Visible;
CmbServerName.Items.Add(servers.Rows[i]["ServerName"] + "\\" + servers.Rows[i]["InstanceName"]);
}
else
{
CmbServerName.Visibility = Visibility.Visible;
CmbServerName.Items.Add(servers.Rows[i]["ServerName"]);
}
}
}
Thanks in advance!
Another way to get the installed instance names of sql server is to read your machine registry. It will fetch all the instances of sql from your local machine.
RegistryKey rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server");
String[] instances = (String[])rk.GetValue("InstalledInstances");
if (instances.Length > 0)
{
foreach (String element in instances)
{
if (element == "MSSQLSERVER")
Console.WriteLine(System.Environment.MachineName);
else
Console.WriteLine(System.Environment.MachineName + #"\" + element);
}
Console.ReadLine();
}
This might not be it, but worth a try. Is the SQL Server Browser service running on your machine?
GetDataSource() retrieves all the instance visible from your machine. The ServerName is the name of the machine where the istance is hosted, and it appears you have only one istance on your machine.
What do you mean with the bolded part: "How to get all list of instance name and server name in my local machine" ? If you want to see every server visible from your machine you have to remove the if statement
if (myServer == servers.Rows[i]["ServerName"].ToString())
because there is only one server with your local machine name so you can't get any other server name.
Note that documentation reports
Due to the nature of the mechanism used by SqlDataSourceEnumerator to
locate data sources on a network, the method will not always return a
complete list of the available servers, and the list might not be the
same on every call. If you plan to use this function to let users
select a server from a list, make sure that you always also supply an
option to type in a name that is not in the list, in case the server
enumeration does not return all the available servers. In addition,
this method may take a significant amount of time to execute, so be
careful about calling it when performance is critical.
so it could be due to this problem.
A alternative solution:
Microsoft.SqlServer.Management.Smo.SmoApplication.EnumAvailableSqlServers
How can I check for 3G, wifi, EDGE, Cellular Networks in Windows Phone 7 using C#?
If you can use the Mango (7.1) SDK, and if your scenario involves using sockets, there's a trivial way to get the NetworkInterfaceType/SubType information for the connection you just made:
NetworkInterfaceInfo netInterfaceInfo = socket.GetCurrentNetworkInterface();
var type = netInterfaceInfo.InterfaceType;
var subType = netInterfaceInfo.InterfaceSubtype;
No need to use the NetworkInterface.NetworkInterfaceType property (which notoriously takes up to 30sec to return); no need to trigger a hostname resolution just to determine the network type; no need to listen to network change events.
Of course, this works best in conjunction with DeviceNetworkInformation.IsNetworkAvailable or NetworkInterface.GetIsNetworkAvailable() - those calls return immediately whether you're on a network or not. If you are, you connect the socket first and ask questions when it's connected :-)
A final note: beware of Mango's DeviceNetworkInformation.IsWiFiEnabled - I thought it would return whether I was on a wifi network, but instead it returns whether wifi is turned on or off in the phone settings... not super useful.
take a look at phoney tools, they have class PhoneNetworking for this:
http://wildermuth.com/2011/03/05/Phoney_Tools_Updated_(WP7_Open_Source_Library)
its open source you can check the source code
As of the Mango release (beta 2 and RC), this information is now available but it requires you to actually make a connection, presumably because it doesn't check until something needs it.
You can either perform a DNS resolution (see below) or use the GetCurrentNetworkInterface WebRequest extension method, which will throw an InvalidOperationException if the request hasn't connected yet.
There are also some events to follow in the Microsoft.Phone.Net.NetworkInformation namespace, but I wouldn't be surprised if those events didn't fire until a connection was made.
Interestingly, it seems you can also prefer or require on a per-connection basis using the SetNetworkPreference and SetNetworkRequirement extension methods, though it doesn't go beyond wifi vs cellular.
DeviceNetworkInformation.ResolveHostNameAsync(
new DnsEndPoint("microsoft.com", 80),
new NameResolutionCallback(nrr =>
{
var info = nrr.NetworkInterface;
var type = info.InterfaceType;
var subType = info.InterfaceSubtype;
}), null);
The enumeration values for NetworkInterfaceType (wifi/gsm) and NetworkInterfaceSubType (edge/3g) are available on MSDN.
Without socket:
var currentList = new NetworkInterfaceList().Where(i => i.InterfaceState == ConnectState.Connected).Select(i => i.InterfaceSubtype);
if (currentList.Contains(NetworkInterfaceSubType.WiFi))
Debug.WriteLine("WiFi");
if (currentList.Intersect(new NetworkInterfaceSubType[]
{
NetworkInterfaceSubType.Cellular_EVDO,
NetworkInterfaceSubType.Cellular_3G,
NetworkInterfaceSubType.Cellular_HSPA,
NetworkInterfaceSubType.Cellular_EVDV,
}).Any())
Debug.WriteLine("3G");
if (currentList.Intersect(new NetworkInterfaceSubType[]
{
NetworkInterfaceSubType.Cellular_GPRS,
NetworkInterfaceSubType.Cellular_1XRTT,
NetworkInterfaceSubType.Cellular_EDGE,
}).Any())
Debug.WriteLine("2G");
Unfortunately the api's don't provide very limited information about the kind of network connection you have. You can tell if you are on 3G, Cellular or Ethernet (i.e. USB connection to PC) but that is all the information you get.
Check out this for more info Better way to check for an network connection on WP7
To get Network Data for windows phone app i.e it is connected to a ethernet, wifi or cellular network also getting the subtype i.e 2G or 3g network following program can be used.
Using Microsoft.Phone.Net.NetworkInformation
Using Microsoft.Phone.net.NetworkInfromation
var Newlist = new NetworkInterfaceList();
foreach (NetworkInterfaceInfo x in Newlist)
{
if(x.InterfaceState==ConnectState.Connected)
{
if(x.InterfaceSubtype.Equals(NetworkInterfaceSubType.WiFi))
{
Interface = x.InterfaceType.ToString();
SubInterface = x.InterfaceSubtype.ToString();
break;
}
else if(x.InterfaceSubtype.Equals(NetworkInterfaceSubType.Cellular_EVDO) || x.InterfaceSubtype.Equals(NetworkInterfaceSubType.Cellular_3G) || x.InterfaceSubtype.Equals(NetworkInterfaceSubType.Cellular_HSPA) || x.InterfaceSubtype.Equals(NetworkInterfaceSubType.Cellular_EVDV))
{
Interface = x.InterfaceType.ToString();
SubInterface= “3G Network”;
break;
}
else if(x.InterfaceSubtype.Equals(NetworkInterfaceSubType.Cellular_GPRS) || x.InterfaceSubtype.Equals(NetworkInterfaceSubType.Cellular_1XRTT) || x.InterfaceSubtype.Equals(NetworkInterfaceSubType.Cellular_EDGE))
{
Interface = x.InterfaceType.ToString();
SubInterface= “2G Network”;
break;
}
else
{
Interface = “Ethernet”;
SubInterface= “Unknown” ;
break;
}
}
else
{
Interface=”not connected”;
SubInterface=”unknown”;
}
Here, Interface and SubInterface gives the network information.