I need validate that a Bluetooth LE 5.0 device is connected to a computer. I have been reviewing all the properties I can query for a device but I haven't found one that contains the Bluetooth version of the device. Can this be done using UWP or any other method?
This is the code I am using to explore the data I can get using UWP:
string aqsFilter = "System.Devices.DevObjectType:=5 AND (System.Devices.Aep.ProtocolId:=\"{BB7BB05E-5972-42B5-94FC-76EAA7084D49}\" OR System.Devices.Aep.ProtocolId:=\"{E0CBF06C-CD8B-4647-BB8A-263B43F0F974}\") AND (System.Devices.Aep.IsConnected:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.Bluetooth.IssueInquiry:=System.StructuredQueryType.Boolean#False)";
string[] requestedProperties = {
"System.Devices.Aep.Category",
"System.DeviceInterface.Bluetooth.DeviceAddress",
"System.DeviceInterface.Bluetooth.Flags",
"System.Devices.Aep.Bluetooth.Le.AddressType",
"System.Devices.Aep.Bluetooth.Le.Appearance",
"System.Devices.Aep.Bluetooth.Le.Appearance.Category",
"System.Devices.Aep.Bluetooth.Le.Appearance.Subcategory",
"System.Devices.Aep.DeviceAddress",
"System.Devices.AepService.ServiceClassId",
"System.Devices.Aep.ProtocolId",
"System.Devices.AepService.ProtocolId"
};
DeviceInformationCollection ConnectedBluetoothDevices = await DeviceInformation.FindAllAsync(aqsFilter, requestedProperties); //aqsFilter
foreach (DeviceInformation connectedBluetoothDevice in ConnectedBluetoothDevices)
{
Console.WriteLine(connectedBluetoothDevice.Name);
Console.WriteLine(" " + connectedBluetoothDevice.Id);
Console.WriteLine(" " + connectedBluetoothDevice.Kind.ToString());
Console.WriteLine(" " + connectedBluetoothDevice.Properties.Count);
foreach (KeyValuePair<string, object> property in connectedBluetoothDevice.Properties)
{
if (property.Value != null && property.Value.GetType().IsArray)
{
String[] array = (String[])property.Value;
Console.WriteLine(" " + property.Key + " = " + array[0]);
}
else
{
Console.WriteLine(" " + property.Key + " = " + property.Value);
}
}
}
Related
I do simple app like database management and because from server to client. Here is my method below:
public PracownikDane GetPracownik(string imie)
{
PracownikDane pracownikDane = null;
using (NORTHWNDEntities database = new
{
try
{
var query = from pros in database.Employees
where pros.Title == imie
select pros;
List<string> pracownicy = new List<string>();
foreach (var ps in query)
{
Console.WriteLine(ps.Title);
Console.WriteLine(ps.FirstName);
Console.WriteLine(ps.LastName);
Console.WriteLine(ps.Address);
}
}
catch (System.InvalidOperationException)
{
string blad="It's an error";
}
}
return pracownikDane;
}
And it's shows my this data in server Console like this:
And here is my code in a client:
string pdane = Console.ReadLine();
PracownikDane data = proxy.GetPracownik(pdane);
Console.WriteLine(" ");
Console.WriteLine("Zawód:" + " " + data.Tytul);
Console.WriteLine("Imie:" + " " + data.Imie);
Console.WriteLine("Nazwisko:" + " " + data.Nazwisko);
Console.WriteLine("Kraj Pochodzenia:" + " " + data.Kraj);
Console.WriteLine("Miasto:" + " " + data.Miasto);
Console.WriteLine("Adres:" + " " + data.Adres);
Console.WriteLine("Telefon:" + " " + data.Telefon);
Console.WriteLine("Strona WWW:" + " " + data.WWW);
Console.ReadLine();
I would like to know how to put this data in Client.
I am developing an application which will use Azure Management API to show details about the VM's, Start, stop the VM and so on.
I am able to authenticate the user, but once i try to get information about the vm it shows,
user not authorized to perform Microsoft.Compute/virtualMachines/read
But i am the admin on my azure account, and it has owner+reader permission. I am able to do same thing using powershell but not by application.
I referred this link for development:
https://azure.microsoft.com/en-in/documentation/articles/virtual-machines-windows-csharp-manage/
My sample code is below:
static void Main(string[] args)
{
var groupName = "XYZ";
var vmName = "DC1";
var location = "Southeast Asia";
var subscriptionId = "My Subscription ID";
var token = GetAccessTokenAsync();
var credential = new TokenCredentials(token.Result.AccessToken);
GetVirtualMachineAsync( credential, groupName, vmName, subscriptionId);
}
private static async Task<AuthenticationResult> GetAccessTokenAsync()
{
var cc = new ClientCredential("{client-id}", "{client-secret}");
var context = new AuthenticationContext("https://login.windows.net/{tenant-id}");
var result = await context.AcquireTokenAsync("https://management.azure.com/", cc);
if (result == null)
{
throw new InvalidOperationException("Could not get the token");
}
return result;
}
public static async void GetVirtualMachineAsync( TokenCredentials credential, string groupName, string vmName string subscriptionId)
{
Console.WriteLine("Getting information about the virtual machine...");
var computeManagementClient = new ComputeManagementClient(credential)
{ SubscriptionId = subscriptionId };
var vmResult = await computeManagementClient.VirtualMachines.GetAsync(
groupName,
vmName,
InstanceViewTypes.InstanceView);
Console.WriteLine("hardwareProfile");
Console.WriteLine(" vmSize: " + vmResult.HardwareProfile.VmSize);
Console.WriteLine("\nstorageProfile");
Console.WriteLine(" imageReference");
Console.WriteLine(" publisher: " + vmResult.StorageProfile.ImageReference.Publisher);
Console.WriteLine(" offer: " + vmResult.StorageProfile.ImageReference.Offer);
Console.WriteLine(" sku: " + vmResult.StorageProfile.ImageReference.Sku);
Console.WriteLine(" version: " + vmResult.StorageProfile.ImageReference.Version);
Console.WriteLine(" osDisk");
Console.WriteLine(" osType: " + vmResult.StorageProfile.OsDisk.OsType);
Console.WriteLine(" name: " + vmResult.StorageProfile.OsDisk.Name);
Console.WriteLine(" createOption: " + vmResult.StorageProfile.OsDisk.CreateOption);
Console.WriteLine(" uri: " + vmResult.StorageProfile.OsDisk.Vhd.Uri);
Console.WriteLine(" caching: " + vmResult.StorageProfile.OsDisk.Caching);
Console.WriteLine("\nosProfile");
Console.WriteLine(" computerName: " + vmResult.OsProfile.ComputerName);
Console.WriteLine(" adminUsername: " + vmResult.OsProfile.AdminUsername);
Console.WriteLine(" provisionVMAgent: " + vmResult.OsProfile.WindowsConfiguration.ProvisionVMAgent.Value);
Console.WriteLine(" enableAutomaticUpdates: " + vmResult.OsProfile.WindowsConfiguration.EnableAutomaticUpdates.Value);
Console.WriteLine("\nnetworkProfile");
foreach (NetworkInterfaceReference nic in vmResult.NetworkProfile.NetworkInterfaces)
{
Console.WriteLine(" networkInterface id: " + nic.Id);
}
Console.WriteLine("\nvmAgent");
Console.WriteLine(" vmAgentVersion" + vmResult.InstanceView.VmAgent.VmAgentVersion);
Console.WriteLine(" statuses");
foreach (InstanceViewStatus stat in vmResult.InstanceView.VmAgent.Statuses)
{
Console.WriteLine(" code: " + stat.Code);
Console.WriteLine(" level: " + stat.Level);
Console.WriteLine(" displayStatus: " + stat.DisplayStatus);
Console.WriteLine(" message: " + stat.Message);
Console.WriteLine(" time: " + stat.Time);
}
Console.WriteLine("\ndisks");
foreach (DiskInstanceView idisk in vmResult.InstanceView.Disks)
{
Console.WriteLine(" name: " + idisk.Name);
Console.WriteLine(" statuses");
foreach (InstanceViewStatus istat in idisk.Statuses)
{
Console.WriteLine(" code: " + istat.Code);
Console.WriteLine(" level: " + istat.Level);
Console.WriteLine(" displayStatus: " + istat.DisplayStatus);
Console.WriteLine(" time: " + istat.Time);
}
}
Console.WriteLine("\nVM general status");
Console.WriteLine(" provisioningStatus: " + vmResult.ProvisioningState);
Console.WriteLine(" id: " + vmResult.Id);
Console.WriteLine(" name: " + vmResult.Name);
Console.WriteLine(" type: " + vmResult.Type);
Console.WriteLine(" location: " + vmResult.Location);
Console.WriteLine("\nVM instance status");
foreach (InstanceViewStatus istat in vmResult.InstanceView.Statuses)
{
Console.WriteLine("\n code: " + istat.Code);
Console.WriteLine(" level: " + istat.Level);
Console.WriteLine(" displayStatus: " + istat.DisplayStatus);
}
}
Thank you.
I solved this problem myself. I was missing to give appropriate rights to the app created under active directory using azure portal. In my case i gave owner access.
I need to fetch details of VM instance in Azure using the Azure SDK APIs'.
These details include various parameters like...
* Host Name
* IP address
* Instance Name
* Location
* Tag name etc.
There are two types of VMs' in Azure...
* Classic VM (through the older portal)
* VM (using the new portal)
The classic VM used to have a cloud service created with the same name.
I was able to get the above mentioned parameter details for the classic VM using the Microsoft.WindowsAzure.Management.Compute library and the HostedService class.
Code Snippet:
var cert = new X509Certificate2(Constants.PFXCertificatePath, Constants.CertificatePassword);
var cred = new CertificateCloudCredentials(Constants.SubscriptionID, cert);
var computeClient = CloudContext.Clients.CreateComputeManagementClient(cred);
List<HostedServiceListResponse.HostedService> hostedServiceOperations = computeClient.HostedServices.List().HostedServices.ToList<HostedServiceListResponse.HostedService>();
foreach (HostedServiceListResponse.HostedService hostedService in hostedServiceOperations)
{
HostedServiceGetDetailedResponse detailedResponse = computeClient.HostedServices.GetDetailed(hostedService.ServiceName);
List<HostedServiceGetDetailedResponse.Deployment> deployments = detailedResponse.Deployments.
ToList<HostedServiceGetDetailedResponse.Deployment>();
foreach (HostedServiceGetDetailedResponse.Deployment deployment in deployments)
{
List<RoleInstance> roleInstances = deployment.RoleInstances.ToList<RoleInstance>();
foreach (RoleInstance roleInstance in roleInstances)
{
string privateId = deployment.PrivateId;
Console.WriteLine($"Host Name: {roleInstance.HostName}");
Console.WriteLine($"Instance Name: {roleInstance.InstanceName}");
Console.WriteLine($"Instance size: {roleInstance.InstanceSize}");
Console.WriteLine($"Private IP: {roleInstance.IPAddress}");
foreach (RoleInstance.PublicIP publicIP in roleInstance.PublicIPs)
{
Console.WriteLine($"Public IP: {publicIP.Address}");
}
Console.WriteLine($"Role Name: {roleInstance.RoleName}");
Console.WriteLine($"Power state: {roleInstance.PowerState}");
Console.WriteLine($"Instance status: {roleInstance.InstanceStatus}");
foreach (InstanceEndpoint instanceEndpoint in roleInstance.InstanceEndpoints)
{
Console.WriteLine($"Instance endpoint name: {instanceEndpoint.Name}, port: {instanceEndpoint.Port}, protocol: {instanceEndpoint.Protocol}");
Console.WriteLine($"Instance Virtual IP address: {instanceEndpoint.VirtualIPAddress}, local port: {instanceEndpoint.LocalPort}");
}
}
}
}
However, I've found that this approach does not work for the new VM (i.e. the one created from the new portal) as a cloud service is not created for it.
Using the new ARM library (Microsoft.Azure.Management.Resources) I'm able to get basic information of this VM which is limited to Name and location information using the GenericResource class.
var token = GetAuthorizationHeader(Constants.TenantID);//Uses Active Directory authentication token
var tokenCred = new Microsoft.Rest.TokenCredentials(token);
ResourceManagementClient resourceClient = new ResourceManagementClient(tokenCred);
resourceClient.SubscriptionId = Constants.SubscriptionID;
var resourceGroups = resourceClient.ResourceGroups;
IResourcesOperations resources = resourceClient.Resources;
List<GenericResource> vmResources = resources.List().Where(r => r.Type == "Microsoft.Compute/virtualMachines").ToList<GenericResource>();
foreach (GenericResource resource in vmResources)
{
Console.WriteLine($"Resource Name: {resource.Name}, Resource Location: {resource.Location},Resource Plan: {resource.Plan}");
}
I have used this code to get instance information:
public static void GetVirtualMachine(TokenCredentials credential, string groupName, string vmName, string subscriptionId)
{
Console.WriteLine("Getting information about the virtual machine...");
var computeManagementClient = new ComputeManagementClient(credential);
computeManagementClient.SubscriptionId = subscriptionId;
var vmResult = computeManagementClient.VirtualMachines.Get(groupName, vmName, "instanceview");
Console.WriteLine("hardwareProfile");
Console.WriteLine(" vmSize: " + vmResult.HardwareProfile.VmSize);
Console.WriteLine("\nstorageProfile");
Console.WriteLine(" imageReference");
Console.WriteLine(" publisher: " + vmResult.StorageProfile.ImageReference.Publisher);
Console.WriteLine(" offer: " + vmResult.StorageProfile.ImageReference.Offer);
Console.WriteLine(" sku: " + vmResult.StorageProfile.ImageReference.Sku);
Console.WriteLine(" version: " + vmResult.StorageProfile.ImageReference.Version);
Console.WriteLine(" osDisk");
Console.WriteLine(" osType: " + vmResult.StorageProfile.OsDisk.OsType);
Console.WriteLine(" name: " + vmResult.StorageProfile.OsDisk.Name);
Console.WriteLine(" createOption: " + vmResult.StorageProfile.OsDisk.CreateOption);
Console.WriteLine(" uri: " + vmResult.StorageProfile.OsDisk.Vhd.Uri);
Console.WriteLine(" caching: " + vmResult.StorageProfile.OsDisk.Caching);
Console.WriteLine("\nosProfile");
Console.WriteLine(" computerName: " + vmResult.OsProfile.ComputerName);
Console.WriteLine(" adminUsername: " + vmResult.OsProfile.AdminUsername);
Console.WriteLine(" provisionVMAgent: " + vmResult.OsProfile.WindowsConfiguration.ProvisionVMAgent.Value);
Console.WriteLine(" enableAutomaticUpdates: " + vmResult.OsProfile.WindowsConfiguration.EnableAutomaticUpdates.Value);
Console.WriteLine("\nnetworkProfile");
foreach (NetworkInterfaceReference nic in vmResult.NetworkProfile.NetworkInterfaces)
{
Console.WriteLine(" networkInterface id: " + nic.Id);
}
Console.WriteLine("\nvmAgent");
Console.WriteLine(" vmAgentVersion" + vmResult.InstanceView.VmAgent.VmAgentVersion);
Console.WriteLine(" statuses");
foreach (InstanceViewStatus stat in vmResult.InstanceView.VmAgent.Statuses)
{
Console.WriteLine(" code: " + stat.Code);
Console.WriteLine(" level: " + stat.Level);
Console.WriteLine(" displayStatus: " + stat.DisplayStatus);
Console.WriteLine(" message: " + stat.Message);
Console.WriteLine(" time: " + stat.Time);
}
Console.WriteLine("\ndisks");
foreach (DiskInstanceView idisk in vmResult.InstanceView.Disks)
{
Console.WriteLine(" name: " + idisk.Name);
Console.WriteLine(" statuses");
foreach (InstanceViewStatus istat in idisk.Statuses)
{
Console.WriteLine(" code: " + istat.Code);
Console.WriteLine(" level: " + istat.Level);
Console.WriteLine(" displayStatus: " + istat.DisplayStatus);
Console.WriteLine(" time: " + istat.Time);
}
}
Console.WriteLine("\nVM general status");
Console.WriteLine(" provisioningStatus: " + vmResult.ProvisioningState);
Console.WriteLine(" id: " + vmResult.Id);
Console.WriteLine(" name: " + vmResult.Name);
Console.WriteLine(" type: " + vmResult.Type);
Console.WriteLine(" location: " + vmResult.Location);
Console.WriteLine("\nVM instance status");
foreach (InstanceViewStatus istat in vmResult.InstanceView.Statuses)
{
Console.WriteLine("\n code: " + istat.Code);
Console.WriteLine(" level: " + istat.Level);
Console.WriteLine(" displayStatus: " + istat.DisplayStatus);
}
}
Windows 7 domain network.
I get the domain computer names:
List<String> compNames = new List<String>();
// If it isn't possible to be connected to a domain
// network then we will receive an exception.
using (DirectoryEntry domainEntry = domain.GetDirectoryEntry())
using (DirectorySearcher searcher = new DirectorySearcher(
domainEntry, "objectClass=computer", new[] { "Name" }))
using (SearchResultCollection resultCollection =
searcher.FindAll()) {
foreach (SearchResult searchResult in resultCollection) {
compNames.Add(searchResult.Properties["Name"][0]
.ToString());
}
}
This code returns also the names of computers which already are not existing many years and the computers which are off. How can I recive only the computer names which are accessible for me at this time? Is it possible?
I recommend you to ping each computer on domain to check their accessibility.
Below function you can use to ping computer:
public String PingTest(string asMac)
{
String lsReturn = "";
try
{
Ping pingreq = new Ping();
PingReply rep = pingreq.Send(asMac);
if (rep.Status == IPStatus.Success)
{
lsReturn = "Success"
return lsReturn;
}
else
{
lsReturn = "Error Pinging " + asMac + " " + rep.Status;
}
}
catch (PingException pEx)
{
lsReturn = "PingException Error Pinging " + asMac + " " + pEx.Message + Environment.NewLine + pEx.StackTrace;
}
catch (NetworkInformationException nEx)
{
lsReturn = "NetworkInformationException Error Pinging " + asMac + " " + nEx.Message + Environment.NewLine + nEx.StackTrace;
}
catch (Exception ex)
{
lsReturn = "Error Pinging " + asMac + " " + ex.Message + Environment.NewLine + ex.StackTrace;
}
return lsReturn;
}
I'm getting the following exception:
"Input string was not in the correct format."
I'm taking a Json response which is comma delimited and storing it in a database. I'm not sure what is wrong.
Here is the code:
foreach (string s in skaters)
{
skaterData = s.Split(stringSeparator2, StringSplitOptions.None);
Console.WriteLine(skaterData[0] + " " + skaterData[1] + " " + skaterData[2] + " " + skaterData[3] + " " + skaterData[4] + " " + skaterData[5] +
" " + skaterData[6] + " " + skaterData[7] + " " + skaterData[8] + " " + skaterData[9] + " " + skaterData[10] + " " + skaterData[11] + " " + skaterData[12]
+ " " + skaterData[13] + " " + skaterData[14] + " " + skaterData[15]);
try
{
using (var _temp_Player = new FetcherEntities())
{
//int validPlayer;
//int validTeam;
//Skater_Season existingPlayer = _temp_Player.Skater_Season.FirstOrDefault(x => x.player_id == Convert.ToInt32(skaterData[1]) && x.team_id = Convert.ToInt32(skaterData[2]));
// if (existingPlayer != null)
// {
// Console.WriteLine("Existing player: " + existingPlayer.NAME);
// }
// else
// {
_temp_Player.Skater_Season.Add(new Skater_Season
{
player_id = Int32.Parse(skaterData[0]), //stuck here
team_id = Int32.Parse(team),
season_id = season,
Number = Int32.Parse(skaterData[1]),
POS = skaterData[2],
NAME = skaterData[3],
GP = Int32.Parse(skaterData[4]),
G = Int32.Parse(skaterData[5]),
A = Int32.Parse(skaterData[6]),
P = Int32.Parse(skaterData[7]),
plusminus = Int32.Parse(skaterData[8]),
PIM = Int32.Parse(skaterData[9]),
S = Int32.Parse(skaterData[10]),
TOIG = skaterData[11],
PP = Int32.Parse(skaterData[12]),
SH = Int32.Parse(skaterData[13]),
GWG = Int32.Parse(skaterData[14]),
OT = Int32.Parse(skaterData[15])
});
try
{
_temp_Player.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}
}
}
catch (DbEntityValidationException forwardDB)
{
foreach (DbEntityValidationResult entityError in forwardDB.EntityValidationErrors)
{
foreach (DbValidationError error in entityError.ValidationErrors)
{
Console.WriteLine("Error Name: {0} : Message: {1}", error.PropertyName, error.ErrorMessage);
return false;
}
}
}
}
Also I've attached some screen shots of what the data looks like.
Its hard to tell you exactly where the error is but that message is being thrown by one of the Int32.Parse methods receiving data that it cant parse.
The best solution is to use TryParse which allows you to gracefully continue if a problem occurs.