Unable to get image details from azure container registry - azure

Unable to get image details from azure container register
I tried using azure container registry.
Can anyone assist me on this?
please let me know how to login to acr using username and password in c#?
ContainerRegistryClient client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(),
new ContainerRegistryClientOptions()
{
Audience = ContainerRegistryAudience.AzureResourceManagerPublicCloud
});
// Obtain a RegistryArtifact object to get access to image operations
RegistryArtifact image = client.GetArtifact("kube01.azurecr.io/sensor:6", "latest");
// List the set of tags on the hello_world image tagged as "latest"
Pageable<ArtifactTagProperties> tags = image.GetAllTagProperties();
// Iterate through the image's tags, listing the tagged alias for the image
Console.WriteLine($"{image.FullyQualifiedReference} has the following aliases:");
foreach (ArtifactTagProperties tag in tags)
{
Console.WriteLine($" {image.RegistryEndpoint.Host}/{image.RepositoryName}:{tag}");
}
}
}
}

I tried in my environment and got below results:
I setup an image in the container registry with two tags through portal:
Code:
I tried with same code and modified some lines to get the image detail.
using Azure;
using Azure.Containers.ContainerRegistry;
using Azure.Identity;
string registryName = "registry1";
// Create a new instance of the ContainerRegistryClient class
var credential = new DefaultAzureCredential();
var client = new ContainerRegistryClient(new Uri($"https://{registryName}.azurecr.io"), credential, new ContainerRegistryClientOptions()
{
Audience = ContainerRegistryAudience.AzureResourceManagerPublicCloud
});
RegistryArtifact image = client.GetArtifact("nginx","latest");
Pageable<ArtifactTagProperties> tags = image.GetAllTagProperties();
Console.WriteLine($"{image.FullyQualifiedReference} has the following aliases:");
foreach (ArtifactTagProperties tag in tags)
{
Console.WriteLine($"Name: {tag.Name}");
Console.WriteLine($"Digest:{tag.Digest}");
Console.WriteLine($"Lastmodifiedtime:{tag.LastUpdatedOn}");
}
Console:
registry1.azurecr.io/nginx:latest has the following aliases:
Name: latest
Digest:sha256:6650513efd1d27c1xxxxxxxxxxx
Lastmodifiedtime:15-02-2023 05:05:55 +00:00
Name: v1
Digest:sha256:6650513efd1d27c1xxxxxxxxxxx
Lastmodifiedtime:15-02-2023 06:26:16 +00:00
Reference:
Azure Container Registry client library for .NET - Azure for .NET Developers | Microsoft Learn

Related

Reference to type 'IResourceGroups' claims it is defined in 'Microsoft.Azure.Management.ResourceManager.Fluent', but it could not be found

I am getting this error when trying to call azure.ResourceGroups.List() where azure is an instance of Iazure.
project.json
Please have a try to following code to get list of resources. I test it on my side, it works correctly. We also could use the Resources - List By Resource Group Rest API to do that.
I install Microsoft.Azure.Management.ResourceManager.Fluent 1.0.0 as you and use console app to test. Here is my testing code:
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);
var subscriptionId = "your_subscriptionId";
var azure = new ResourceManagementClient(credentials) { SubscriptionId = subscriptionId };
var resource = azure.ResourceGroups.ListAsync().Result;

Xamarin text blob Azure storage

I am using Azure storage blob to store image and I am trying to display it in my Xamrin.form application. I have find a simple tutorial and the code on github.
I have succeed to implement it by following the steps and and create an account on azure storage blob.
The problem is : I can see the name of the file but not the "image"
here is the error:
read started: <Thread Pool> #9
[0:] HTTP Request: Could not retrieve https://xxxxxx.blob.core.windows.net/yyyy/kakashi.jpg, status code NotFound
[0:] ImageLoaderSourceHandler: Could not retrieve image or image data was invalid: Uri: https://lxxxxxx.blob.core.windows.net/yyyy/kakashi.jpg
Thread finished: <Thread Pool> #4
Here is the tutorial:
click to see
Here is the Github:
click to see
Here is the output on screen:
and I have this error when I put the Urlof the image (https://lxxxxxx.blob.core.windows.net/yyyy/kakashi.jpg
) on my bronwser:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>ResourceNotFound</Code>
<Message>
The specified resource does not exist. RequestId:97933c69-a01e-014f-6669-f0502e000000 Time:2018-05-20T18:33:28.4774584Z
</Message>
</Error>
The error means you don't set Public access level to Blob.
See this requirement in your tutorial.
Code you use requires this setting, because it accesses the blob directly using blob Uri.
See PhotosBlobStorageService.cs
return blobList.Select(x => new PhotoModel { Title = x.Name, Uri = x.Uri }).ToList();
If you do want to keep Private level, you have to make some changes to the statement above. Here's the reference.
return blobList.Select(x => new PhotoModel { Title = x.Name,
Uri = new Uri(x.Uri+x.GetSharedAccessSignature(
new SharedAccessBlobPolicy {
Permissions = SharedAccessBlobPermissions.Read|SharedAccessBlobPermissions.Write,
// you can modify the expiration to meet your requirement
SharedAccessExpiryTime = DateTime.UtcNow.AddYears(1)
} ))
}).ToList();
This change allows you to visit private blob with a SAS.
1.Please check your subscription first.
2.Check the access policy of your container.
3.Here is the steps to Save and get blobs through the code.
1)Using NuGet we can install required Assembly packages.
Go to "Manage Package for Solution Menu" and search for WindowsAzure.Storage and WindowsAzure.ConfigurationManager and click on install.
2)Get access keys in the configuration.
3)Sample code to Create blob through the code:
public async Task<string> SaveImagesToAzureBlob(HttpPostedFileBase imageToUpload)
{
try
{
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("sampleimage");
if (await cloudBlobContainer.CreateIfNotExistsAsync())
{
await cloudBlobContainer.SetPermissionsAsync(
new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
}
);
}
string imageFullPath = null;
string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(imageToUpload.FileName);
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);
cloudBlockBlob.Properties.ContentType = imageToUpload.ContentType;
await cloudBlockBlob.UploadFromStreamAsync(imageToUpload.InputStream);
imageFullPath = cloudBlockBlob.Uri.ToString();
return imageFullPath;
}
catch (Exception ex)
{
throw ex;
}
}
Now, check your storage account, you can see the container sample generated.
By default, the container will be private, no one can access from outside. To set the permissions we should use the SetPermission method as below.
CloudBlobContainer .SetPermissions( new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
Please try different permissions in the list.
Please note the permission level settings.In your case it may cause the issue.
For more details :
Reference
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-deployment-model
https://learn.microsoft.com/en-us/azure/storage/blobs/storage-dotnet-how-to-use-blobs

Not able to run Azure Data Factory Pipeline using Visual Studio 2015

I have followed the Azure documentation steps to create a simple Copy Data Factory from Blob to SQL.
Now I want to run the pipeline through VS code.
I have checked the authentication keys and Roles assigned are correct.
Below is the code -
var context = new AuthenticationContext("https://login.windows.net/" + tenantID);
ClientCredential cc = new ClientCredential(applicationId, authenticationKey);
AuthenticationResult result = context.AcquireTokenAsync("https://management.azure.com/", cc).Result;
ServiceClientCredentials cred = new TokenCredentials(result.AccessToken);
var client = new DataFactoryManagementClient(cred) { SubscriptionId = subscriptionId };
Console.WriteLine("Creating pipeline run...");
var st = client.Pipelines.Get(resourceGroup, dataFactoryName, pipelineName);
CreateRunResponse runResponse = client.Pipelines.CreateRunWithHttpMessagesAsync(resourceGroup, dataFactoryName, pipelineName).Result.Body;
Console.WriteLine("Pipeline run ID: " + runResponse.RunId);
However, I get Forbidden error.
The client 'xxxx' with object id 'xxxx' does not have authorization to perform action 'Microsoft.DataFactory/factories/pipelines/read' over scope '/subscriptions/xxxxx/resourceGroups/'
How can I fix this?
How can I fix this?
According to the exception message that it indicates that you don't assign the corresponding role to application to access the data factory.
I test your code with Azure Datafactory(V2) on my side , it works correctly. The following is my details steps.
Registry an Azure AD WebApp application.
Get the clientId and clientscret from created Application.
Assign the role the application to access the datafactory.
Test code on my side.

Upload Azure Batch Job Application Package programmatically

I have found how to upload/manage Azure Batch job Application Packages through the UI:
https://learn.microsoft.com/en-us/azure/batch/batch-application-packages
And how to upload and manage Resource Packages programmatically:
https://github.com/Azure/azure-batch-samples/tree/master/CSharp/GettingStarted/02_PoolsAndResourceFiles
But I can't quite seem to put 2 and 2 together on how to manage Application Packages programmatically. Is there an API endpoint we can call to upload/manage an Application Package when setting up a batch job?
Since this is not quite straightforward, I'll write down my findings.
These are the steps to programmatically upload Application Packages via an application that is unattended - no user input (e.g. Azure credentials) is needed.
In Azure Portal:
Create the Azure Batch application
Create a new Azure AD application (as Application Type use Web app / API)
Follow these steps to create the secret key and assign the role to the Azure Batch account
Note down the following credentials/ids:
Azure AD application id
Azure AD application secret key
Azure AD tenant id
Subscription id
Batch account name
Batch account resource group name
In your code:
Install NuGet packages Microsoft.Azure.Management.Batch, WindowsAzure.Storage and Microsoft.IdentityModel.Clients.ActiveDirectory
Get the access token and create the BatchManagementClient
Call the ApplicationPackageOperationsExtensions.CreateAsync method, which should return an ApplicationPackage
ApplicationPackage contains the StorageUrl which can now be used to upload the Application Package via the storage API
After you have uploaded the ApplicationPackage you have to activate it via ApplicationPackageOperationsExtensions.ActivateAsync
Put together the whole code looks something like this:
private const string ResourceUri = "https://management.core.windows.net/";
private const string AuthUri = "https://login.microsoftonline.com/" + "{TenantId}";
private const string ApplicationId = "{ApplicationId}";
private const string ApplicationSecretKey = "{ApplicationSecretKey}";
private const string SubscriptionId = "{SubscriptionId}";
private const string ResourceGroupName = "{ResourceGroupName}";
private const string BatchAccountName = "{BatchAccountName}";
private async Task UploadApplicationPackageAsync() {
// get the access token
var authContext = new AuthenticationContext(AuthUri);
var authResult = await authContext.AcquireTokenAsync(ResourceUri, new ClientCredential(ApplicationId, ApplicationSecretKey)).ConfigureAwait(false);
// create the BatchManagementClient and set the subscription id
var bmc = new BatchManagementClient(new TokenCredentials(authResult.AccessToken)) {
SubscriptionId = SubscriptionId
};
// create the application package
var createResult = await bmc.ApplicationPackage.CreateWithHttpMessagesAsync(ResourceGroupName, BatchAccountName, "MyPackage", "1.0").ConfigureAwait(false);
// upload the package to the blob storage
var cloudBlockBlob = new CloudBlockBlob(new Uri(createResult.Body.StorageUrl));
cloudBlockBlob.Properties.ContentType = "application/x-zip-compressed";
await cloudBlockBlob.UploadFromFileAsync("myZip.zip").ConfigureAwait(false);
// create the application package
var activateResult = await bmc.ApplicationPackage.ActivateWithHttpMessagesAsync(ResourceGroupName, BatchAccountName, "MyPackage", "1.0", "zip").ConfigureAwait(false);
}
Azure Batch Application Packages management operations occur on the management plane. The MSDN docs for this namespace are here:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.management.batch
The nuget package for Microsoft.Azure.Management.Batch is here:
https://www.nuget.org/packages/Microsoft.Azure.Management.Batch/
And the following sample shows management plane operations in C#, although it is for non-application package operations:
https://github.com/Azure/azure-batch-samples/tree/master/CSharp/AccountManagement

Windows Azure Blob

I've been trying to create a Windows Azure Blob containing an image file. I followed these tutorials: http://www.nickharris.net/2012/11/how-to-upload-an-image-to-windows-azure-storage-using-mobile-services/ and http://www.windowsazure.com/en-us/develop/mobile/tutorials/upload-images-to-storage-dotnet/. Finally the following code represents a merging of them. On the last line, however, an exception is raised:
An exception of type 'System.TypeLoadException' occurred in
mscorlib.ni.dll but was not handled in user code
Additional information: A binding for the specified type name was not
found. (Exception from HRESULT: 0x80132005)
Even the container is created the table, but It doesn't work properly.
private async void SendPicture()
{
StorageFile media = await StorageFile.GetFileFromPathAsync("fanny.jpg");
if (media != null)
{
//add todo item to trigger insert operation which returns item.SAS
var todoItem = new Imagem()
{
ContainerName = "mypics",
ResourceName = "Fanny",
ImageUri = "uri"
};
await imagemTable.InsertAsync(todoItem);
//Upload image direct to blob storage using SAS and the Storage Client library for Windows CTP
//Get a stream of the image just taken
using (var fileStream = await media.OpenStreamForReadAsync())
{
//Our credential for the upload is our SAS token
StorageCredentials cred = new StorageCredentials(todoItem.SasQueryString);
var imageUri = new Uri(todoItem.SasQueryString);
// Instantiate a Blob store container based on the info in the returned item.
CloudBlobContainer container = new CloudBlobContainer(
new Uri(string.Format("https://{0}/{1}",
imageUri.Host, todoItem.ContainerName)), cred);
// Upload the new image as a BLOB from the stream.
CloudBlockBlob blobFromSASCredential =
container.GetBlockBlobReference(todoItem.ResourceName);
await blobFromSASCredential.UploadFromStreamAsync(fileStream.AsInputStream());
}
}
}
Please use Assembly Binding Log Viewer to see which load is failing. As also mentioned in the article, the common language runtime's failure to locate an assembly typically shows up as a TypeLoadException in your application.

Resources