Application Settings Azure - azure

i'm new to azure and i have the following issue:
i have this key in my web.config:
add key="BlobStorageConnectionString" value="xxxxxxxx"
The thing is when i add it to app settings in azure app service, when i search in the logs i get this:
Getting "BlobStorageConnectionString" from ServiceRuntime: FAIL
Getting "BlobStorageConnectionString" from ConfigurationManager: PASS.
i've already tried a few tutorials, but i still can't find a reason.
I'm running out of ideas, any suggestions?

If you add the Storage Account string in the Application Settings, it will be stored as an environment.So you could read it with Environment.GetEnvironmentVariable("storageconnectionstring").
Then parse it the code will be like below shows.
string storageConnectionString = Environment.GetEnvironmentVariable("storageconnectionstring");
// Check whether the connection string can be parsed.
if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
{
try
{
// Create the CloudBlobClient that represents the Blob storage endpoint for the storage account.
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
........
........
}
}
And you could also configure your connection in your app like WebJob, you could use JobHostConfiguration(). And the code would be like this.And the connection name should be AzureWebJobsStorage.
var config = new JobHostConfiguration();
config.DashboardConnectionString = "";
Also you could choose to use Configuration Classes,about the details you could refer to this article.
Hope this could help you, if you still have other questions,please let me know.

Related

How does Azure BlobStorage connection data have to be stored to support all available addressing modes?

I am using libraries Microsoft.Azure.Storage.Blob 11.2.3.0 and Microsoft.Azure.Storage.Common 11.2.3.0 to connect to an Azure BlobStorage from a .NET Core 3.1 application.
Users of my application are supposed to supply connection information to an Azure BlobStorage to/from where the application will deposit/retrieve data.
Initially, I had assumed allowing users to specify a connection string and a custom blob container name (as an optional override of the default) would be sufficient. I could simply stuff that connection string into the CloudStorageAccount.Parse method and get back a storage account instance to call CreateBlobCloudClient on.
Now that I'm trying to use this method to connect using a container-specific SAS (also see my other question about that), it appears that the connection string might not be the most universal way to go.
Instead, it now seems a blob container URL, plus a SAS token or an account key (and possibly an account name, thought that seems to be included in the blob container URL already) are more versatile. However, I am concerned that the next way of pointing to a blob storage that I need to support (whichever that may be) might require yet another kind of information - hence my question:
What set of "fields" do I need to support in the configuration files of my application to make sure my users can point to their BlobStorage whichever way they want, as long as they have a BlobStorage?
(Is there maybe even a standard solution or best practice recommendation by Microsoft?)
Please note that I am exclusively concerned with what to store. An arbitrarily long string? A complex object of sorts? If so, with what fields?
I am not asking how to store that configuration once I know what it must comprise. For example, this is not about securely encrypting credentials etc.
On Workaround To access the Storage account using the SAS Token you need to pass the Account Name along with the SAS Token and Blob Name if you trying to upload and You need give the permission for your SAS Token .
Microsoft recommends using Azure Active Directory (Azure AD) to authorize requests against blob and queue data if possible, instead of Shared Key. Azure AD provides superior security and ease of use over Shared Key. For more information about authorizing access to data with Azure AD, see Authorize access to Azure blobs and queues using Azure Active Directory..
Note: Based on my testes you need to pass the Storage Account Name And SAS Token and the Container Name And Blob name
Example: I tried with uploading file to container using container level SAS Token . able to upload the file successfully.
const string sasToken = "SAS Token";
StorageCredentials storageCredentials = new StorageCredentials(sasToken);
const string accountName = "teststorage65";//Account Name
const string blobContainerName = "test";
const string blobName = "test.txt";
const string myFileLocation = #"Local Path ";
var storageAccount = new CloudStorageAccount(storageCredentials, accountName, null, true);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer blobContainer = blobClient.GetContainerReference(blobContainerName);
//blobContainer.CreateIfNotExists();
CloudBlockBlob cloudBlob = blobContainer.GetBlockBlobReference(blobName);
cloudBlob.UploadFromFile(myFileLocation);
As you already know You can use the Storage connection string to connect with Storage.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("Connection string");
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("test");
Your application needs to access the connection string at runtime to authorize requests made to Azure Storage.
You have several options for storing your connection string Or SAS Token
1) You can store your connection string in an environment variable.
2) An application running on the desktop or on a device can store the connection string in an app.config or web.config file. Add the connection string to the AppSettings section in these files.
3) An application running in an Azure cloud service can store the connection string in the Azure service configuration schema (.cscfg) file. Add the connection string to the ConfigurationSettings section of the service configuration file.
Reference: https://learn.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string

Azure function cannot get blob container

I have function app which connect to blob , read file content and post content to API. The function works perfect on debug from Visual Studio . The problem I am having is does not work from Azure when deployed . The error I ma getting is:
Exception while executing function: MyFunctionManager
Problem Id:System.ArgumentNullException at MYFUNCTION.FA.FileManager.BlobContainerManager.GetCloudBlobContainer
It seems cannot connect and find the blob storage. In the code I am getting the container using connection string set in the local.settings.json:
public static CloudBlobContainer GetCloudBlobContainer(string blobContainer)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
App.Settings.AzureFileStorageConnectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(blobContainer);
container.CreateIfNotExistsAsync();
return container;
}
Any help appreciated
Thanks
The local.settings.json file is just for local development.
When running on Azure, make sure you have an Application Setting with key AzureFileStorageConnectionString and value to your storage account's connection string.
And you would have to do the same for the container name too since you mentioned that you are getting it from Application Settings.

Using Azure Blobs with Azure Website

I'm in the process of making an MVC Windows Azure website which involves users uploading images.
I wanted to store the images in blobs.
I searched for tutorials but most of them deal with Webapps rather than MVC websites.
The only useful tutorial I found was: http://www.codeproject.com/Articles/490178/How-to-Use-Azure-Blob-Storage-with-Azure-Web-Sites
I'm new to the whole MVC/Windows Azure/Visual Studio scene and I got confused at Step 7 where I had to connect to Cloud Storage Account.
var storageAccount = CloudStorageAccount.Parse(
ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);
I can't figure out where I'm supposed to put that bit of a code.
Same for the code in Step 8: Creating a container
blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
if (container.CreateIfNotExist())
{
// configure container for public access
var permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);
}
And Step 9: Save the Image to a BLOB
string uniqueBlobName = string.Format("productimages/image_{0}{1}",
Guid.NewGuid().ToString(), Path.GetExtension(image.FileName));
CloudBlockBlob blob = blobStorage.GetBlockBlobReference(uniqueBlobName);
blob.Properties.ContentType = image.ContentType;
blob.UploadFromStream(image.InputStream);
Any help will be really appreciated. Any other links to relevant tutorials are also welcome.
Thanks a lot!
I assume you've added the Windows Azure Storage NuGet package to your Web App project? That didn't seem explicit in the reference you quoted, but if you hadn't you'd be seeing a bunch of unresolved compiler errors.
In terms of where the code goes, it's rather up to you. The assignment to storageAccount is like setting a database connection string; nothing is going across the wire, so you could set it once perhaps and make it available throughout your application as part of some static class instance.
In terms of creating a container, you'd do this whenever you want to store data - consider it tantamount to creating a folder in a file system or maybe a table in a relational database. If your application is always storing information in the same "hard-coded" container, you could set your container up ahead of time in the portal and not create in code.
Putting code like this in though provides a bit of resiliency in case the container got deleted through some external process; the same way that an app using SQL Server could check for the existence of an Employee table before doing updates/retrieves, since it's possible (but not likely) someone deleted the Employee table via some other SQL tool.
Saving the image to the blob would be put directly behind whatever controller is responsible for initiating that action. This is where you're doing the 'real' work. The code in your sample specifically references a container productimages, so it could be immediately preceded by the code in Step 8 if you wanted to be certain that there no chance the container was deleted (through the portal, for instance). Again, that would be similar to checking for the existence of a database table in traditional client/server code everytime you accessed data in it (which most of us might consider overkill and we'd resort to exception handling to cover that contingency).
Old question but still may help noobs!
Azure Webapps do accept MVC apps. Webapps on Azure are just a container which Im sure can take different types of ASP.NET based applications, Forms or MVC, C# or VB.net.
Assuming you know the basics of an MVC application you can just create the Azure Webapp and publish it to there. It's as straight forward as that.
This code:
var storageAccount = CloudStorageAccount.Parse(
ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);
And this:
blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
if (container.CreateIfNotExist())
{
// configure container for public access
var permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);
}
Can go in a new class specifically for Blob services e.g. call it something like blobServices.cs and save it in the root of your MVC app and it can look like so:
var storageAccount = CloudStorageAccount.Parse(
ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);
blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
if (container.CreateIfNotExist())
{
// configure container for public access
var permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);
}
Which is probably the best practice. From there on in the Controller/s of your MVC app you can do something like this:
namespace blabla.cs
{
public controller myBlobController
{
//instantiate the blob service
BlobProfileImageServices _blobServices = new BlobProfileImageServices();
public public ActionResult Index()
{
//call your blob storage service
//and loop through each blob
CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();
List<string> blobs = new List<string>();
foreach (var blobItem in blobContainer.ListBlobs())
{
blobs.Add(blobItem.Uri.ToString());
}
}
}
}

How to connect Azure blob storage through website MVC4

I develop a website on Windows Azure, MVC4. I try to upload and get photos from blobs.
My related code (that I got from other examples on web):
var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);
var blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("abc");
container.CreateIfNotExists();
var permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);
My related web.config code:
<add name="StorageConnection" connectionString="DefaultEndPointsProtocol=https;AccountName=abc;AccountKey=*******"/>
When I run I got a format exception. Please note that it is web site.
As per some posts, when I put my connection string to app.config, no solution.
Thank you very much for any assistance.
You shall not use connectionStrings section to store Azure Storage Connection string!
Use appSettings instead and you will have no issues. It is confusion that the Storage credentials is also named "Connection string", but it has nothing to do with the connectionStrings section in your configuration file. connectionStrings section is intended solely for use DataBase connection strings.

Windows Azure Diagnostics Error:

I am working with Windows Azure Diagnostics. I add the below code in Webrol.cs
try
{
string wadConnectionString = "Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(wadConnectionString));
RoleInstanceDiagnosticManager roleInstanceDiagnosticManager = storageAccount.CreateRoleInstanceDiagnosticManager(RoleEnvironment.DeploymentId, RoleEnvironment.CurrentRoleInstance.Role.Name, RoleEnvironment.CurrentRoleInstance.Id);
DiagnosticMonitorConfiguration config = DiagnosticMonitor.GetDefaultInitialConfiguration();
//Windows Azure logs
config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1D);
config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Undefined;
//IIS 7.0 logs
config.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1D);
////Failed Request logs
config.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1D);
//Windows Event logs
// config.WindowsEventLog.DataSources.Add("System!*");
config.WindowsEventLog.DataSources.Add("Application!*");
config.WindowsEventLog.ScheduledTransferPeriod = TimeSpan.FromMinutes(1D);
////Crash dumps
CrashDumps.EnableCollection(true);
//update the config with changes
roleInstanceDiagnosticManager.SetCurrentConfiguration(config);
}
catch (Exception ee)
{
System.Diagnostics.Trace.TraceWarning("Diagnostics failed");
}
and the remaining neccesary things in Web.config and the connection string in the .cscfg file.
Now I am able to log the Diagnostics in the from the Development environment using the Deployment Storage. But when i host the same application in Cloud I am not able to log the Diagnostics. I am getting an error like
"500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed."
I tried by changing Copy local to true for the namespaces, but that doesn't work.
I want the application to work in the deployment environment.
If anyone have any idea to resolve this please reply me.
Thanks in advance.
The problem looks like you are not changing the connection string for "Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString". You can change this in the settings for the web role project or you service configuration file. Set it to your account name and key. I normally do this with a build script so I can change this when I push to production. You can check out the post here and the code here.

Resources