I am trying to record telemetry to Application Insights from a WPF app. Events and page views are being logged but the context properties are not being logged alongside them.
I have intitialised the client like:
internal InsightsLogging(string instrumentationKey)
{
TelemetryConfiguration configuration = TelemetryConfiguration.Active;
configuration.InstrumentationKey = instrumentationKey;
QuickPulseTelemetryProcessor processor = null;
configuration.TelemetryProcessorChainBuilder
.Use((next) =>
{
processor = new QuickPulseTelemetryProcessor(next);
return processor;
})
.Build();
var QuickPulse = new QuickPulseTelemetryModule();
QuickPulse.Initialize(configuration);
QuickPulse.RegisterTelemetryProcessor(processor);
Client = new TelemetryClient(configuration);
Client.InstrumentationKey = instrumentationKey;
Client.Context.Session.Id = Guid.NewGuid().ToString();
Client.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
Client.Context.Device.Id = EnvironmentUtility.GetMACAddress();
Client.Context.Component.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
Client.Context.User.Id = LoggingDataProvider.User;
Client.Context.User.AuthenticatedUserId = LoggingDataProvider.User;
Client.Context.User.AccountId = LoggingDataProvider.Account;
Client.Context.Component.Version = Assembly.GetEntryAssembly().GetName().Version.ToString();
Client.Context.User.UserAgent = "App";
}
The logs end up looking like:
Notice that none of the "user_*" columns are not populated. And it is worth noting that the appName is incorrect as well - it is the name of the application insights instance on Azure.
Related
I'm attempting to create a VM programmatically...actually, following an example in a book. Before running the program I went ahead and created an Azure AD application and service principal via the portal https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal. (On a side note, maybe someone can explain to me why one needs to do this, but can create a VM straightaway via the portal without creating a service principal/AD app.)
While running the app, I'm able to successfully create the management client. Next step is to create the resource group, and that's where it fails with a "System.Net.Http.HttpRequestException: 'No such host is known.'" error. Please advise as to what could be the problem here. Thank you.
//Create the management client. This will be used for all the operations we will perform in Azure.
var credentials = SdkContext.AzureCredentialsFactory.FromFile("../../../azureauth.properties");
var azure = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic).Authenticate(credentials).WithDefaultSubscription();
//Create a resource group
var groupName = "az204-ResourceGroup";
var vmName = "az204VMTesting";
var location = Region.USEast;
var vNetName = "az204VNET";
var vNetAddress = "172.16.0.0/16";
var subnetName = "az204Subnet";
var subnetAddress = "172.16.0.0/24";
var nicName = "az204NIC";
var adminUser = "azureadminuser";
var adminPassword = "Pa$$w0rd!2019";
Console.WriteLine($"Creating resource group {groupName} ... ");
//Below fails with 'No such host is known'
var resourceGroup = azure.ResourceGroups.Define(groupName).WithRegion(location).Create();
I tried this code in my system .Try with this code
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
namespace AzureVirtualMachine
{
class Program
{
static void Main(string[] args)
{
var credentials = SdkContext.AzureCredentialsFactory
.FromServicePrincipal("clientId", "clientSecret", "tenantId", AzureEnvironment.AzureGlobalCloud);
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithSubscription("SubscriptionID”)
var groupName = "sampleResourceGroup";
var vmName = "VMWithCSharp";
var location = Region.EuropeWest;
var resourceGroup = azure.ResourceGroups.Define(groupName)
.WithRegion(location)
.Create();
var network = azure.Networks.Define("sampleVirtualNetwork")
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithAddressSpace("10.0.0.0/16")
.WithSubnet("sampleSubNet", "10.0.0.0/24")
.Create();
var publicIPAddress = azure.PublicIPAddresses.Define("samplePublicIP")
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithDynamicIP()
.Create();
var networkInterface = azure.NetworkInterfaces.Define("sampleNetWorkInterface")
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithExistingPrimaryNetwork(network)
.WithSubnet("sampleSubNet")
.WithPrimaryPrivateIPAddressDynamic()
.WithExistingPrimaryPublicIPAddress(publicIPAddress)
.Create();
var availabilitySet = azure.AvailabilitySets.Define("sampleAvailabilitySet")
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithSku(AvailabilitySetSkuTypes.Aligned)
.Create();
azure.VirtualMachines.Define(vmName)
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithExistingPrimaryNetworkInterface(networkInterface)
.WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
.WithAdminUsername("sampleUser")
.WithAdminPassword("Sample123467")
.WithComputerName(vmName)
.WithExistingAvailabilitySet(availabilitySet)
.WithSize(VirtualMachineSizeTypes.StandardB1s)
.Create();
}
}
}
Output:
I resolved the issue by replacing AzureCredentialsFactory.FromFile with AzureCredentialsFactory.FromServicePrincipal. Thanks ShrutiJoshi-MT for the input. I simply created a json file with the necessary credentials.
I still had some issues related to authorization. It turns out I didn't give the App Service appropriate authorization level. This post helped resolve that issue: The client with object id does not have authorization to perform action 'Microsoft.DataFactory/datafactories/datapipelines/read' over scope.
Final code:
string jsonString = File.ReadAllText("../../../azureauth.json");
AuthItem authItem = JsonSerializer.Deserialize<AuthItem>(jsonString);
var credentials = SdkContext.AzureCredentialsFactory
.FromServicePrincipal(authItem.ClientId, authItem.SecretValue, authItem.TenantId, AzureEnvironment.AzureGlobalCloud);
//Create the management client. This will be used for all the operations we will perform in Azure.
var azure = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic).Authenticate(credentials).WithSubscription(authItem.Subscription);
//Create a resource group
var groupName = "az204-ResourceGroup";
var vmName = "az204VMTesting";
var location = Region.USEast;
var vNetName = "az204VNET";
var vNetAddress = "172.16.0.0/16";
var subnetName = "az204Subnet";
var subnetAddress = "172.16.0.0/24";
var nicName = "az204NIC";
var adminUser = "azureadminuser";
var adminPassword = "Pa$$w0rd!2019";
Console.WriteLine($"Creating resource group {groupName} ... ");
var resourceGroup = azure.ResourceGroups.Define(groupName).WithRegion(location).Create();
//Every VM needs to be connected to a virtual network
Console.WriteLine($"Creating virtual network {vNetName} ...");
var network = azure.Networks.Define(vNetName)
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithAddressSpace(vNetAddress)
.WithSubnet(subnetName, subnetAddress)
.Create();
//Any VM needs a network interface for connecting to the virtual network
Console.WriteLine($"Creating network interface {nicName} ... ");
var nic = azure.NetworkInterfaces.Define(nicName)
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithExistingPrimaryNetwork(network)
.WithSubnet(subnetName)
.WithPrimaryPrivateIPAddressDynamic()
.Create();
//Create the VM
Console.WriteLine($"Creating VM {vmName} ... ");
azure.VirtualMachines.Define(vmName)
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithExistingPrimaryNetworkInterface(nic)
.WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
.WithAdminUsername(adminUser)
.WithAdminPassword(adminPassword)
.WithComputerName(vmName)
.WithSize(VirtualMachineSizeTypes.StandardDS2V2)
.Create();
I create an App Service using "classic" Pulumi.Azure:
var appservice=new AppService(appserviceName, new AppServiceArgs
{
Name = appserviceName,
Location = _resourceGroup.Location,
AppServicePlanId = _servicePlan.Id,
ResourceGroupName = _resourceGroup.Name,
SiteConfig = new Pulumi.Azure.AppService.Inputs.AppServiceSiteConfigArgs
{
DotnetFrameworkVersion = "v5.0",
ScmType = "None",
},
Tags = { { "environemnt", "dev" } },
Logs = new AppServiceLogsArgs
{
HttpLogs = new AppServiceLogsHttpLogsArgs
{
FileSystem = new AppServiceLogsHttpLogsFileSystemArgs { RetentionInDays = 14, RetentionInMb = 35 }
}
}
,
AppSettings = appSettings
});
I also create a keyvault:
var currentConfig=Output.Create(GetClientConfig.InvokeAsync());
var keyVault = new KeyVault(vaultname, new KeyVaultArgs
{
Name = vaultname,
Location = _resourceGroup.Location,
ResourceGroupName = _resourceGroup.Name,
TenantId = currentConfig.Apply(q => q.TenantId),
SkuName="standard"
, AccessPolicies=
{
new Pulumi.Azure.KeyVault.Inputs.KeyVaultAccessPolicyArgs
{
TenantId=currentConfig.Apply(q=>q.TenantId),
ObjectId=currentConfig.Apply(q=>q.ObjectId),
KeyPermissions={"get", "create", "list"},
SecretPermissions={"set","get","delete","purge","recover", "list"}
}
}
});
Both work as expected. KeyVault and App Service are being created and accessable by me. Now I need that the App Service also can access the KeyVault.
But when adding a new Access Policy I am stuck at the ObjectId. The App Service does not seem to have a valid object id I can assign to the vault. When checking the service on Azure Portal I also see the Identy is missing:
So what has to be done as pulumi code that would achieve the same thing as clicking onto "On" in Azure and retrieve the ObjectId afterwards?
You need to set the following property on AppService to enable the managed identity:
Identity = new AppServiceIdentityArgs {Type = "SystemAssigned"},
This example illustrates the end-to-end implementation: https://github.com/pulumi/examples/blob/327afe30ce820901f210ed2a01da408071598ed6/azure-cs-msi-keyvault-rbac/AppStack.cs#L128
How do i fix this. I want to set my authentication in my code and not on the machine.
I have checked almost every answer on stackoverflow and github, but none has a good explanation.
How do i pass the credentials to the create intent, it throws this error.
InvalidOperationException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
GoogleCredential credential =
GoogleCredential.FromFile(file);
//var credential = GoogleCredential.FromStream(
// Assembly.GetExecutingAssembly().GetManifestResourceStream("chatbot-a90a9-8f2fb910202d.json"))
// .CreateScoped(IntentsClient.DefaultScopes);
var storage = StorageClient.Create(credential);
var client = IntentsClient.Create();
var text = new Intent.Types.Message.Types.Text();
text.Text_.Add("Message Text");
var message = new Intent.Types.Message()
{
Text = text
};
var trainingPhrasesParts = new List<string>
{
"Book a fligt",
"check cheap flights"
};
var phraseParts = new List<Intent.Types.TrainingPhrase.Types.Part>();
foreach (var part in trainingPhrasesParts)
{
phraseParts.Add(new Intent.Types.TrainingPhrase.Types.Part()
{
Text = part
});
}
var trainingPhrase = new Intent.Types.TrainingPhrase();
trainingPhrase.Parts.AddRange(phraseParts);
var intent = new Intent();
intent.DisplayName = "test";
intent.Messages.Add(message);
intent.TrainingPhrases.Add(trainingPhrase);
var newIntent = client.CreateIntent(
parent: new AgentName("chatbot-a90a9"),
intent: intent
);
SOLVED.
I change
var client = IntentsClient.Create();
To
IntentsClientBuilder builder = new IntentsClientBuilder
{
CredentialsPath = file, // Relative to where the code is executing or absolute path.
// Scopes = IntentsClient.DefaultScopes // Commented out because there's no need to specify this since you are using the defaults and all default values will be automatically used for values not specified in the builder.
};
IntentsClient client = builder.Build();
I have a problem with the Microsoft.Web.Deployment package. someone here could tell me, how i must write / configure the sync-process, that the target will be shutdown, before updating it with the new version?
here is my snippet:
var publishSettings = GetPublishSettings(subscriptionId, resourcegroupName, websiteName);
var sourceBaseOptions = new DeploymentBaseOptions();
var targetBaseOptions = new DeploymentBaseOptions
{
ComputerName = publishSettings.ComputerName,
UserName = publishSettings.Username,
Password = publishSettings.Password,
AuthenticationType = "basic",
TraceLevel = Verbose
};
targetBaseOptions.Trace += TargetBaseOptions_Trace;
var syncOptions = new DeploymentSyncOptions
{
DoNotDelete = false,
WhatIf = false,
UseChecksum = true
};
using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, Path.GetFullPath(websitePath), sourceBaseOptions))
{
var summary = deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, publishSettings.SiteName, targetBaseOptions, syncOptions);
if (summary.Errors > 0) throw new Exception("Website Deployment failed");
if (summary.Errors == 0)
{
Console.WriteLine($"{publishSettings.SiteName}: erfolgreich");
}
}
i could imagine that it is something in the DeploymentSyncOptions
thank you guys
From Microsoft.Web.Deployment, I could not find it provides method or option to manage (stop, restart etc) Azure web site. If you’d like to stop your Azure web site before you do deployment, you could try to use Microsoft.Azure.Management.WebSites that provides website management capabilities for Microsoft Azure.
WebSiteManagementClient websiteManagementClient = new WebSiteManagementClient(cred);
websiteManagementClient.SubscriptionId = "your subscription id here";
websiteManagementClient.Sites.StopSite(AzureResourceGroup, siteName);
and you could use websiteManagementClient.Sites.GetSite(AzureResourceGroup, siteName).State to check the site state.
I'm trying to implement a pure WCF scenario where I want to call Dynamics CRM WCF service without relying on the SDK helper classes. Basically, I would like to implement federated authentication against Dynamics CRM 2011 using only native WCF support from the .net framework.
The reason I'm doing this is that I would like to port this scenario later-on to BizTalk.
I've successfully generated proxy classes with SvcUtil, but the part of the policies and security assertions are not compatible with the configuration schema. SvcUtil suggests to build the binding from code instead, which is what I'm trying to do.
The resulting code is here:
private static void CallWcf()
{
OrganizationServiceClient client = null;
try
{
// Login Live.com Issuer Binding
var wsHttpBinding = new WSHttpBinding();
wsHttpBinding.Security = new WSHttpSecurity();
wsHttpBinding.Security.Mode = SecurityMode.Transport;
// Endpoint Binding Elements
var securityElement = new TransportSecurityBindingElement();
securityElement.DefaultAlgorithmSuite = SecurityAlgorithmSuite.TripleDes;
securityElement.IncludeTimestamp = true;
securityElement.KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy;
securityElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
securityElement.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
var securityTokenParameters = new IssuedSecurityTokenParameters();
securityTokenParameters.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
securityTokenParameters.ReferenceStyle = SecurityTokenReferenceStyle.Internal;
securityTokenParameters.RequireDerivedKeys = false;
securityTokenParameters.TokenType = null;
securityTokenParameters.KeyType = SecurityKeyType.SymmetricKey;
securityTokenParameters.KeySize = 192;
securityTokenParameters.IssuerAddress = new EndpointAddress("https://login.live.com/extSTS.srf");
securityTokenParameters.IssuerMetadataAddress = null;
securityTokenParameters.DefaultMessageSecurityVersion = null;
securityTokenParameters.IssuerBinding = wsHttpBinding;
securityElement.EndpointSupportingTokenParameters.Signed.Add(securityTokenParameters);
var textMessageEncodingElement = new TextMessageEncodingBindingElement();
textMessageEncodingElement.MaxReadPoolSize = 64;
textMessageEncodingElement.MaxWritePoolSize = 16;
textMessageEncodingElement.MessageVersion = MessageVersion.Default;
textMessageEncodingElement.WriteEncoding = System.Text.Encoding.UTF8;
textMessageEncodingElement.ReaderQuotas.MaxStringContentLength = 8192;
textMessageEncodingElement.ReaderQuotas.MaxArrayLength = 16384;
textMessageEncodingElement.ReaderQuotas.MaxBytesPerRead = 4096;
textMessageEncodingElement.ReaderQuotas.MaxNameTableCharCount = 16384;
var httpsTransportElement = new HttpsTransportBindingElement();
httpsTransportElement.ManualAddressing = false;
httpsTransportElement.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
CustomBinding binding = new CustomBinding();
binding.Elements.Add(securityElement);
binding.Elements.Add(textMessageEncodingElement);
binding.Elements.Add(httpsTransportElement);
client = new OrganizationServiceClient(binding, new EndpointAddress(EndpointUri));
client.ClientCredentials.UserName.UserName = Username;
client.ClientCredentials.UserName.Password = Password;
client.Open();
var columnSet = new schemas.microsoft.com.xrm._2011.Contracts.ColumnSet();
var identifier = new Guid("fbf8240e-2c85-e011-ad55-1cc1de0878eb");
columnSet.Columns = new string[] { "name" };
var entity = client.Retrieve("account", identifier, columnSet);
}
finally
{
if (client != null)
client.Close();
}
}
I'm new to federated authentication and am having a hard time figuring out the potential differences between the many available bindings, so I would be grateful for any help in this regard.
It is probably possible, but hugely complicated. We had a project using Dynamics which moved to ADFS, and required adding lots of extra code around refreshing tokens (code form autorefreshsecuritytoken.cs, deviceidmanager.cs and toolserviceproxies.cs from the SDK) and that was still using the SDK for everything.
Bare in mind you also need windows.identification installed in the OS which is another load of functionality to copy.
In the end you can always just use JustDecompile or similar to see what the SDK is doing.