Get IP of Azure VM using SDK - c#

I have a VM powered on and running in azure. I know its name but want to retrieve its IP address programmatically using the new C# SDK and avoiding the REST API. How can I do this?

Try this:
string subId = "deadbeef-beef-beef-beef-beefbeefbeef";
string resourceGroup = "SORG01";
string vmName = "SORG01-BOX01";
using (var client = new ComputeManagementClient(credentials))
{
client.SubscriptionId = subId;
VirtualMachine vm = VirtualMachinesOperationsExtensions.Get(client.VirtualMachines, resourceGroup, vmName);
networkName = vm.NetworkProfile.NetworkInterfaces[0].Id.Split('/').Last();
}
using (var client = new NetworkManagementClient(credentials))
{
client.SubscriptionId = subId;
var network = NetworkInterfacesOperationsExtensions.Get(client.NetworkInterfaces, resourceGroup, vmName);
string ip = network.IpConfigurations[0].PrivateIPAddress;
}
To have these classes, you'll need to install from nuget:
Microsoft.Azure.Management.Compute
Microsoft.Azure.Management.Compute.Models
Microsoft.Azure.Management.Network
Note that you'll have to select "Include Prerelease" on the nuget search window in order to find these packages. credentials is a Microsoft.Rest.TokenCredentials object that you acquire in this manner:
var authContext = new AuthenticationContext("https://login.windows.net/{YourTenantId}");
var credential = new ClientCredential("{YourAppID}", "{YourAppSecret}");
var result = authContext.AcquireTokenAsync("https://management.core.windows.net/", credential);
result.Wait();
if (result.Result == null)
throw new AuthenticationException("Failed to obtain the JWT token");
credentials = new TokenCredentials(result.Result.AccessToken);

The easiest way to retrieve the public IP Address of Azure Virtual Machine is
{_VirtualMachineInstance}.GetPrimaryPublicIPAddress().IPAddress;
Very good explanation of this matter you can find here- Tom Sun answer:
Get Azure VM using resource manager deployment and rest api

Related

Using explicit credentials in a C# dialogflow application

I'm creating a C# application that uses DialogFlow's detectIntent. I need help passing the Google Cloud credentials explicitly.
It works with the GOOGLE_APPLICATION_CREDENTIALS environment variable. However I want to pass the credentials explicitly. I need a C# version of the solution provided here.
I'm using the following quick-start provided with the documentation:
public static void DetectIntentFromTexts(string projectId,
string sessionId,
string[] texts,
string languageCode = "en-US")
{
var client = df.SessionsClient.Create();
foreach (var text in texts)
{
var response = client.DetectIntent(
session: new df.SessionName(projectId, sessionId),
queryInput: new df.QueryInput()
{
Text = new df.TextInput()
{
Text = text,
LanguageCode = languageCode
}
}
);
var queryResult = response.QueryResult;
Console.WriteLine($"Query text: {queryResult.QueryText}");
if (queryResult.Intent != null)
{
Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
}
Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
Console.WriteLine();
}
}
Currently you need to create a gRPC channel directly, and pass that into the client:
GoogleCredential credential = GoogleCredential.FromFile("...");
ChannelCredentials channelCredentials = credential.ToChannelCredentials();
Channel channel = new Channel(SessionsClient.DefaultEndpoint, channelCredentials);
var client = df.SessionsClient.Create(channel);
Very soon, this will be a lot easier via a builder pattern:
var client = new SessionsClientBuilder
{
CredentialsPath = "path to file",
}.Build();
... or various other ways of specify the credential. I'm hoping that'll be out in the next couple of weeks.

How to create CallCredentials from SslCredentials and token string

I am porting a gRPC client from python to c#. Both the python client and the c# client are using the gRPC Framework from grpc.io.
The python client uses the following code to open a secure, non-authenticated channel, which it then uses to procure a token string, which it then uses to create call credentials with the grpc.composite_channel_credentials() function:
channel = grpc.secure_channel(url_server_address, ssl_creds)
stub = gateway.GatewayStub(channel)
# Acquire access token via password authentication
pw_cmd = gateway.PasswordAuthenticateCmd(account_name=url.username, password=url.password)
auth_rsp = stub.PasswordAuthenticate(pw_cmd)
# Open a secure, authenticated channel
auth_creds = grpc.access_token_call_credentials(auth_rsp.access_token)
composite_creds = grpc.composite_channel_credentials(ssl_creds, auth_creds)
channel = grpc.secure_channel(url_server_address, composite_creds)
stub = gateway.GatewayStub(channel)
In c#, I have been able to compile the protocol buffer definitions, and connect with the generated client to successfully acquire the access token:
SslCredentials secureChannel = new SslCredentials(File.ReadAllText(SSLCertificatePath));
Channel channel = new Channel(ServerURL, PortNum, secureChannel);
var client = new GrpcClient(new Grpc.Gateway.GatewayClient(channel));
var response = client.client.PasswordAuthenticate(new PasswordAuthenticateCmd() { AccountName = UserName, Password = UserPassword });
Console.WriteLine(response.AccessToken);
From here, however, I can't find the c# analog to the grpc.composite_channel_credentials() function to take the SslCredentials and the access token string to create combined credentials.
None of the examples here https://grpc.io/docs/guides/auth.html here use a token string, and I haven't been able to find any other examples out there.
What you're looking for is:
https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Core/CallCredentials.cs#L49 and https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Core/ChannelCredentials.cs#L67.
Feel free to also look at:
https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Auth/GoogleAuthInterceptors.cs#L58
I solved my problem using CallCredentials.FromInterceptor().
The grpc.access_token_call_credentials() python call adds an authorization entry to the metadata, and sets its value to "Bearer " + AccessToken, so I just had to do the same:
SslCredentials secureCredentials = new SslCredentials(File.ReadAllText(SSLCertificatePath));
Channel secureChannel = new Channel(ServerURL, PortNum, secureCredentials);
var client = new GrpcClient(new Grpc.Gateway.GatewayClient(secureChannel));
var response = client.client.PasswordAuthenticate(new PasswordAuthenticateCmd() { AccountName = UserName, Password = UserPassword });
var accessTokenCredentials = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) =>
{
metadata.Add("authorization", "Bearer " + passwordResponse.AccessToken);
return TaskUtils.CompletedTask;
}));
var authenticatedCredentials = ChannelCredentials.Create(secureCredentials, accessTokenCredentials);
Channel authenticatedChannel = new Channel(hostURL, hostPort, authenticatedCredentials);
As Jan pointed out in his answer, there is a function in the Grpc.Auth namespace that does the same thing as the function that I wrote: https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Auth/GoogleAuthInterceptors.cs#L58

Awssdk works on .net dotnetcore (IAM and GatewayAPI) but throws Amazon.CognitoIdentity.Model.NotAuthorizedException on Xamarin Android APP

I have a problem with Awssdk lib from Amazon that I can't understand.
I made an easy Class to authorized and obtain resources from Amazon.
It uses the configuration from user sessionConfig: clientId, identitypoolId,userpoolId, username, password, secret.
And also the request config (signRequest) host, absolutpath, method, region.
var client = AmazonClient(sessionConfig, requestconfig);
With this I can easyly
client.GetClientTokens();
That makes a call to CognitoAuth userpools:
var cred = new CognitoAWSCredentials(_sessionConfig.IdentityPoolId,` RegionEndpoint.EUCentral1);
var provider = new AmazonCognitoIdentityProviderClient(cred, RegionEndpoint.EUCentral1);
CognitoUserPool userPool = new CognitoUserPool(_sessionConfig.UserPoolId, _sessionConfig.ClientId, provider);
CognitoUser user = new CognitoUser(_sessionConfig.UserPoolId, _sessionConfig.ClientId, userPool, provider, _sessionConfig.Secret, _sessionConfig.UserName);
var authRequest = new InitiateSrpAuthRequest()
{
Password = _sessionConfig.Password
};
AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
Then I just call
client.GetApiResource(absolutpath);
And I can get with this auth info the resource from the api.
_requestConfig.AbsolutePath = absolutePath;
//Signmethod from Amazon
GetSignedRequest();
var responses = _webRequest.GetResponse();
var result = responses.GetResponseStream();
var data = string.Empty;
using (var sr = new StreamReader(result))
{
data = sr.ReadToEnd();
}
return data;
This code works like a charm on my dotnetcore console app, I become tokens access data and user or other api resources.
When I want to use it on a Xamarin.Android solution.
I become, when trying to get the credentials:
user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
Amazon.CognitoIdentity.Model.NotAuthorizedException: Access to
Identity 'eu-central-1:xxxxxxxxxxxxxxxxxxxxx' is forbidden.
System.Net.HttpStatusCode.BadRequest
errorCode "NotAuthorizedException"
The only thing I could see it is different is the UserAgent from provider config:
console program:
aws-sdk-dotnet-coreclr/3.3.11.22 aws-sdk-dotnet-core/3.3.29.12 .NET_Core/4.6.26606.02 OS/Microsoft_Windows_10.0.14393
Xamarin.Android app:
aws-sdk-dotnet-pcl/3.3.4.3 aws-sdk-dotnet-core/3.3.29.13 Mono/5.10.1(tarball) OS/ANDROID_7.0 PCL/Xamarin.Android
Console works xamarin throw this exception. Any ideas?

How to create a new Microsoft Azure HybridConnection via code?

I am using HybridConnectionNamespace and create multiple HybridConnections via Azure portal. The question is quite simple. How can I create it programmatically (Azure SDK, PowerShell scripts, etc.)?
According to this article, there are currently two different ways to create a relay namespace.
Azure portal and Azure Resource Manager templates
If you want to create it programmatically, I suggest you could use azure rest api to send the deployment templates by codes.
More details, you could refer to this article and codes:
Notice: If you want to use rest api to send request to azure, you need firstly create an Azure Active Directory application and service principal. After you generate the service principal, you could get the applicationid,access key and talentid. More details, you could refer to this article.
Rest Body(json.txt):
Notice: You need change the parameters' name and location value.
{"properties":{"mode":"incremental","debugSetting":{"detailLevel":"RequestContent, ResponseContent"},"parameters":{"name":{"value":"yourrelayname"},"location":{"value":"location"}},"template":{"$schema":"http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#","contentVersion":"1.0.0.0","parameters":{"name":{"type":"string"},"location":{"type":"string"}},"resources":[{"apiVersion":"2016-07-01","name":"[parameters('name')]","location":"[parameters('location')]","type":"Microsoft.Relay/namespaces","properties":{"namespaceType":"Relay"}}]}}}
Code:
string body = File.ReadAllText(#"D:\json.txt");
// Display the file contents to the console. Variable text is a string.
string tenantId = "tenantId";
string clientId = "clientId(applicationid)";
string clientSecret = "applicationSecret";
string subscription = "subscriptionId";
string resourcegroup = "Youresourcegroup";
string authContextURL = "https://login.windows.net/" + tenantId;
var authenticationContext = new AuthenticationContext(authContextURL);
var credential = new ClientCredential(clientId, clientSecret);
var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Resources/deployments/Microsoft.Relay?api-version=2016-07-01", subscription, resourcegroup));
request.Method = "PUT";
request.Headers["Authorization"] = "Bearer " + token;
request.ContentType = "application/json";
try
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(body);
streamWriter.Flush();
streamWriter.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//Get the response
var httpResponse = (HttpWebResponse)request.GetResponse();
Console.WriteLine(httpResponse.StatusCode);
Console.ReadLine();
Result:
Use PowerShell CmdLets | Hybrid Connection Manager:
Add-HybridConnection
Update-HybridConnection
Remove-HybridConnection
Get-HybridConnection
Set-HybridConnectionManagerConfiguration
https://msdn.microsoft.com/en-us/library/azure/dn789178.aspx
GoodLuck

Amazon MWS client library C# AWS Access Key Id error

I am using Amazon C# client library to get product information and keep getting an error " The AWS Access Key Id you provided does not exist in our records." (Yes, I tried the seller forum, but didn't get an answer there). When I use the same Access Key using their scratchpad, I get the correct response. I did see this post (Getting 'The AWS Access Key Id you provided does not exist in our records' error with Amazon MWS) and tried swapping the parameters and that didn't work. Here is my C# code. Any help would be greatly appreciated
string AccessKey = "xxx";
string SecretKey = "xxx";
string AppName = "ProductFunctionsApp";
string AppVersion = "1.0";
string ServiceURL = "https://mws.amazonservices.com/Products/2011-10-01";
string SellerId="xxxx";
string MarketPlaceId = "xxx";//US
//right now MWSAuthToken is only if a developer is using a sellers account
MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig();
config.ServiceURL = ServiceURL;
config.SignatureMethod = "HmacSHA256";
config.SignatureVersion = "2";
MarketplaceWebServiceProductsClient client = new MarketplaceWebServiceProductsClient(AppName, AccessKey, SecretKey, AppVersion, config);
ASINListType type = new ASINListType();
List<string> ASINList = new List<string>();
ASINList.Add("B001E6C08E");
type.ASIN = ASINList;
;
GetCompetitivePricingForASINRequest request = new GetCompetitivePricingForASINRequest();
request.SellerId = SellerId;
request.ASINList = type;
request.MarketplaceId = MarketPlaceId;
GetCompetitivePricingForASINResponse response = client.GetCompetitivePricingForASIN(request);
Some of their API Clients have the class initialization parameters defined in different orders.
So if you copy and paste the initialization code you'll end up with the application name being sent instead of the access key.
var service = new MarketplaceWebServiceProductsClient(
applicationName, applicationVersion, accessKeyId, secretAccessKey, config);
And it's different here:
var service = new FBAInventoryServiceMWSClient(
accessKeyId, secretAccessKey, applicationName, applicationVersion, config);
Just check each one carefully.

Categories