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);
}
}
Related
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);
}
}
}
I'm getting a OutOfMemory exception when running the following code, it happens on the File.ReadLines line, it processes most files fine until it hits larger files.
It's consistantly using tons of memory and cpu during the whole process though.
The file it crashed on is only 156,000KB, which is 156mb
static void Main(string[] args)
{
Console.CursorVisible = false;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine();
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Connected to the Cassandra Database");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.White;
string filepath = #"C:\Users\admin\Desktop\wecrack lists";
DirectoryInfo directory = new DirectoryInfo(filepath);
int fileCount = 0;
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("cracking");
var collection = database.GetCollection<Password>("passwords");
foreach (var file in directory.GetFiles("*"))
{
fileCount++;
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Working through file: {" + file + "} {" + fileCount + "/" + directory.GetFiles("*").Count() + "}");
List<Password> entitys = new List<Password>();
foreach (string line in File.ReadLines(filepath + #"\" + file.ToString()))
{
entitys.Add(new Password { password = line });
}
collection.InsertManyAsync(entitys);
}
Console.WriteLine();
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Finished inserting records, press any key to get the count.");
Console.ReadKey(true);
while (true)
{
Console.ReadKey(true);
}
}
Try batching your updates. That way you won't have all that data in memory at the same time. It may also help you not totally lock up your database.
...
foreach (var file in directory.GetFiles("*"))
{
fileCount++;
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Working through file: {" + file + "} {" + fileCount + "/" + directory.GetFiles("*").Count() + "}");
System.IO.StreamReader file = new System.IO.StreamReader(filepath + #"\" + file.ToString());
while(!file.EndOfStream)
{
int passwordBatchCount = 0;
List<Password> entitysBatch = new List<Password>();
while ((string line = file.ReadLine()) != null && passwordBatchCount < BATCH_SIZE)
{
entitysBatch.Add(new Password { password = line });
passwordBatchCount++;
}
collection.InsertManyAsync(entitysBatch);
}
file.Close();
}
}
...
I'm doing a WCF service with GUI as client, however I have a problem with printing list of current items added. I have a code to add new entries to the list:
public bool Add_Data(Data sample)
{
container.Add(sample);
Console.WriteLine("New record added!");
return true;
}
And it's working, however when I'm trying to view added records with first try it works, however if I want to view it again list is adding same element. To show you how it works:
I'm adding new entry and I "print" list:
IMAGE CLICK [works how it should]
However I want to see it again, so I'm pressing same button in my form, and here is what happens:IMAGE CLICK as you can see, we have our list + additional same record, if I will press button again, I will have 3 same records.
Here is my "show records" code:
public string Show_Data()
{
Console.WriteLine("Printing records");
foreach (Data record in container)
{
string final_result = ("\nID: "+ + record.ID + " " + "product: " + record.product + " " + "category: " + record.category + " " + "price: " + record.price + " " + "quantity: " + record.quantity + " " + "\n ");
result += final_result;
}
return result;
}
Let me know if you know how to solve it.
You need to look into variable scope. You have result declared outside of the Show_Data() method. Each time the method is called you are doing result += final_result; which is adding to result. Try the code below and you will get different results.
public string Show_Data()
{
Console.WriteLine("Printing records");
var output = string.Empty;
foreach (Data record in container)
{
string final_result = ("\nID: "+ + record.ID + " " + "product: " + record.product + " " + "category: " + record.category + " " + "price: " + record.price + " " + "quantity: " + record.quantity + " " + "\n ");
output += final_result;
}
return output;
}
Also, I would consider using a string builder and string format as well.
public string Show_Data()
{
Console.WriteLine("Printing records");
var output = new StringBuilder();
foreach (Data record in container)
{
string final_result = string.Format("ID: {0} product: {1} category: {2} price: {3} quantity: {4}", record.ID, record.product, record.category, record.price, record.quantity);
// if using C# 6
// string final_result = string.Format($"ID: {record.ID} product: {record.product} category: {record.category} price: {record.price} quantity: {record.quantity)}";
output.AppendLine(final_result);
}
return output.ToString();
}
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.