Azure SDK Storage assembly not found exception when publishing - c#

I try to publish a demo application to Windows Azure using Cloud Service and Azure SDK 2.9. In my service I have a Web Role and a Worker Role. Both use Azure Storage. Everything works fine on local hosting (Emulator) but when I try to publish the app I get the following error on Web Role:
Unhandled Exception: System.Runtime.Serialization.SerializationException,
Details: Exception: Unable to find assembly 'Microsoft.WindowsAzure.Storage, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf385)
In the Worker Role project everything is OK, it's using Storage too.
I tried to convert the Web Role to a standard Web Application and everything works fine but I want to resolve this problem on Cloud Application.
What I've tried:
set local copy in references to true
changed .Net Framework to 4.5.1 and 4.6 (default 4.5)
removed and added reference to Storage again
reinstalled all libraries by nuget
published with Storage 7.0 and 6.2
published by VS and by portal (package)
added dependentAssembly to web.config
On my VM I checked the bin folder, Microsoft.WindowsAzure.Storage exists.
Any ideas what is wrong?

After two days I found a solution for that problem.
In my WebRole.cs I had this:
public override bool OnStart()
{
var csa = CloudStorageAccount.Parse(RoleEnvironment
.GetConfigurationSettingValue("Credentials"));
var cqc = csa.CreateCloudQueueClient();
var inputQueue = cqc.GetQueueReference("inputqueue");
inputQueue.CreateIfNotExists();
var outputQueue = cqc.GetQueueReference("outputqueue");
outputQueue.CreateIfNotExists();
var ctc = csa.CreateCloudTableClient();
var ct = ctc.GetTableReference("last");
ct.CreateIfNotExists();
return base.OnStart();
}
When I moved this initialization to other place e.g. to RouteConfig.cs everything works perfect. I don't know why but every references to Storage from WebRole throws errors after publishing to Azure.
I hope this solution helps.

Related

Creating a CosmosDB database locally with C# code throws an Internal Server error

I try to create a database in the local cosmosDB emulator but this fails to work. It throws an exception with the following message:
Response status code does not indicate success: InternalServerError
(500); Substatus: 0; ActivityId: 36f6a95d-26d7-4ecd-9c81-f6df220f3cdc;
Reason: (Unknown server error occurred when processing this request.
ActivityId: 36f6a95d-26d7-4ecd-9c81-f6df220f3cdc,
Microsoft.Azure.Documents.Common/2.14.0,
Microsoft.Azure.Cosmos.Tracing.TraceData.ClientSideRequestStatisticsTraceDatum,
Windows/10.0.19042 cosmos-netstandard-sdk/3.24.1);
This error happens in my project as well as in an simple, empty console app only containing these lines of code:
using Microsoft.Azure.Cosmos;
namespace CosmosDBTest;
class Program
{
public static async Task Main()
{
using var client = new CosmosClient("<A local connection string>");
var response = await client.CreateDatabaseIfNotExistsAsync("test", 500);
var database = response.Database;
await database.CreateContainerIfNotExistsAsync("container1", "id");
}
}
The version of the emulator I use is 2.14.6. The version of the NuGet package is 3.26.1
What is causing this exception and how do I solve this? I has worked with older versions of the emulator in combination of an older version of the NuGet package. But before I downgrade the emulator and/or package, I want to find out if there is a better work around.
I haven't tried the demo application which is offered by the emulator. Funny enough as it is on a tab with the name ".NET" (and another tab .NET core next to it) the ".NET" example is written in the very old version .net core 2.1 which I don't have installed even.
Try resetting the Emulator, this looks like a malfunction on the Emulator itself. The HTTP 500 is coming from the Emulator, the SDK is just surfacing the response.
Reference: https://learn.microsoft.com/azure/cosmos-db/troubleshoot-local-emulator
If you installed a new version of the emulator and are experiencing errors, ensure you reset your data. You can reset your data by right-clicking the Azure Cosmos DB Emulator icon on the system tray, and then clicking Reset Data…. If that does not fix the errors, you can uninstall the emulator and any older versions of the emulator if found, remove C:\Program files\Azure Cosmos DB Emulator directory and reinstall the emulator.
Alternatively if resetting the data doesn't work, navigate to %LOCALAPPDATA%\CosmosDBEmulator location and delete the folder.

ASP.NET Core 1.1 runs fine locally but when publishing to Azure says "An error occurred while starting the application."

I've been developing an ASP.NET Core web app, based largely on the MVC template provided in Visual Studio 2017 RC2. It runs just fine in local debug mode, but when I try to publish it to an Azure hosted web app, I get this error:
An error occurred while starting the application.
.NET Core X86 v4.1.1.0 | Microsoft.AspNetCore.Hosting version
1.1.0-rtm-22752 | Microsoft Windows 6.2.9200
I've tried setting stdoutLogEnabled="true" in the web.config file, but it seems to have no effect, the error is the same.
Update:
With some help I managed to retrieve the log, and it says:
Application startup exception: System.TypeLoadException: Could not load type 'System.IO.File' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'.
at Microsoft.Extensions.DependencyModel.FileWrapper.OpenRead(String path)
at Microsoft.Extensions.DependencyModel.DependencyContextLoader.LoadEntryAssemblyContext(IDependencyContextReader reader)
at Microsoft.Extensions.DependencyModel.DependencyContextLoader.Load(Assembly assembly)
at Microsoft.Extensions.DependencyModel.DependencyContext.Load(Assembly assembly)
at Microsoft.AspNetCore.Mvc.Internal.DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(String entryPointAssemblyName)
at Microsoft.Extensions.DependencyInjection.MvcCoreServiceCollectionExtensions.GetApplicationPartManager(IServiceCollection services)
at Microsoft.Extensions.DependencyInjection.MvcCoreServiceCollectionExtensions.AddMvcCore(IServiceCollection services)
at Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddMvc(IServiceCollection services)
at Bla.Api.Startup.ConfigureServices(IServiceCollection services) in C:\Users\user\Source\Workspaces\Bla\Bla.Api\src\Bla.Api\Startup.cs:line 73
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Hosting environment: Production
Content root path: D:\home\site\wwwroot
Now listening on: http://localhost:1264
Application started. Press Ctrl+C to shut down.
The line of code it refers to at line 73 is:
services.AddMvc();
Update:
My global.json file looks like this (where Bla.Api is the name of the project, and the file sits in the solution root folder).
{
"projects": [ "Bla.Api" ],
"sdk": {
"version": "1.1.0"
}
}
Since many different problems can cause this error page, I can strongly recommend the following in order to determine the root cause quickly and easily, without wrestling Azure (or any server/platform for that matter) to get logs.
You can enable extremely helpful developer friendly error messages at startup by setting the .UseSetting("detailedErrors", "true") and .CaptureStartupErrors(true) actions in your Program.cs file.
For ASP.NET Core 1.x
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseSetting("detailedErrors", "true")
.UseIISIntegration()
.UseStartup<Startup>()
.CaptureStartupErrors(true)
.Build();
host.Run();
}
(2018/07) Update for ASP.NET Core 2.1
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.CaptureStartupErrors(true)
.UseSetting("detailedErrors", "true")
.UseStartup<Startup>()
.Build();
}
These settings should be removed as soon as your troubleshooting is complete so as not to expose your application to malicious attacks.
Connect via an sftp client and delete everything in the site/wwwroot folder manually. Republish
I have had nothing but problems since I migrated an application I have hosted on Azure to .net core from MVC 4.
At one point a few weeks ago I was unable to get a project to run after a successful publish. I even tried twice to delete the entire App Service profile and recreate it with the same name. However when I appended a '2' to the App Service name (to create a never before used app service) publishing the exact same project with 0 changes worked perfectly. What exactly does a delete do if I can publish successfully to a new app service but not a deleted and recreated one? Remove Existing Files At Destination was checked in each publish, that didn't do anything either.
I had the same error today as pictured in the OP in my #2 site. It occurred after attempting to update a number of asp nuget packages and re-deploy. Really not wanting to have to move on to iteration myApp3 of my app service, I decided to use the FTP information provided in the azure overview page. I navigated to Site/wwwroot and deleted everything inside from the FTP client. I then published the application, and it worked. I can only conclude that the 'Delete' checkbox doesn't work properly.
Thanks everyone for your suggestions. The only thing that worked in the end though is deleting that Azure web app that I couldn't publish to, and creating a brand new one. I guess maybe some of the .dlls from the previous runtime environment were still hanging around or not being updated... Whatever it was, re-creating it worked. Hopefully I don't get this error again though, because you can't really do this kind of stuff in production.
Making changes to the global.json file seemed to have no effect.
Creating an entirely new API from a template didn't help either, the issue was with the Azure Web App itself, as everything was running fine locally.
Another very helpful tip was to add logging (and the "logs" file in the root) as per the other answer. That at least pointed me in the right direction. Also checking your runtime with dotnet --version.
Again thanks for everyone's help!
I've got the same problem. Just not deployed at Azure, I'm using my local machine as server and host it in IIS.
An error occurred while starting the application.
.NET Core X64 v4.1.1.0 | Microsoft.AspNetCore.Hosting version 1.1.1 | Microsoft Windows 10.0.14393 | Need help?
And this was solved by changing web.config.
First set stdoutLogEnabled = "true"
Then make sure stdoutLogFile=".\logs\stdout" /> this folder exists.
And then restart IIS, you can find the real problem in log file.
DELETE all existing dll from wwwroot/your_application_folder, then copy all of the publish output files&folders.
The problem occurs when the NUGETS update it self. If you don't clean the existing files under wwwroot/your_application_folder IIS gives the error above.
Clean and rebuild fixed everything.
Question is probably duplicated - please refer to ASP.NET Core hosting - 500 internal server error.
Quick answer:
You need to set: stdoutLogEnabled="true" and stdoutLogFile=".\logs\stdout". Also, you need to create logs folder manually.
In my case, it was because I was trying to publish user secrets for use with Fabook OAuth. I know that's a very situational specific answer, but OAuth seems pretty common these day. User Secrets, it turns out, are not meant to be published. Who knew.
So to test this I temporarily changed the following code in startup.cs. This data should be not hard coded as a part of best practice, as it would end up in clear text in source control.
Before
app.UseFacebookAuthentication(new FacebookOptions()
{
AppId = Configuration["Authentication:Facebook:AppId"],
AppSecret = Configuration["Authentication:Facebook:AppSecret"]
});
After
app.UseFacebookAuthentication(new FacebookOptions()
{
AppId = "0000000000000", // your value
AppSecret = "0000000000000000000000000000000" // your value
});
Then it worked.
In My case, that was because I was trying to get a some data in Startup, and dbcontext was not updated in production environment.
Changed my ConnectionString to Production and runned Update-Database, and problem solved.
In my case there was a directory named Resources that was missing in app directory.

Error Publishing to Azure 2.7 in VS 2015

I'm trying to do an Azure deployment with two web roles in it. I'm getting the following error after it builds and at the very beginning of the deployment.
Error CloudServices41 : The entrypoint ODataHQ.Query.dll is not a valid assembly. Please provide a relative path to the binary that implements the entrypoint. ODataHQ.Query.Azure C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Windows Azure Tools\2.7\Microsoft.WindowsAzure.targets 1057
This error is happening on a co-workers machine as well. We just recently upgraded to Azure 2.7 inside of Visual Studio 2015 Enterprise and this is the first deployment we've attempted.
Can't find anything about it on the Internet, any thoughts?
Ok, I figured out the issue. I had added another worker role to my Azure deployment project, then I wanted to remove that worker role and add a web role in its place, but keep all the settings. So I manually renamed the worker role to the name of the web role in the ServiceDefinition.csdef, but I didn't change the tag to be a web role.
<WorkerRole name="MyProjectName" vmsize="Small">
Should have been changed back to
<WebRole name="MyProjectName" vmsize="Small">

Unable to create DataCacheFactory instance in debug

I'm working on web project that will run on Windows Azure Web role;
In the cloud, there will be 2 instances of the role;
I'm using co-located named cache (In-Role Cache) spread between 2 role instances;
Locally, I debug with single instance;
In the cloud, cache client is created successfully and work fluently;
When debug locally, I am unable to create instance of DataCacheFactory, because when the constructor is called, the program flow "stops" and doesn't continue to the following statement. There is no exception!
That's the code where I'm creating Factory and cache client:
var cacheFactoryConfig = new DataCacheFactoryConfiguration
{
ChannelOpenTimeout = TimeSpan.FromMinutes(2),
TransportProperties = {ReceiveTimeout = TimeSpan.FromSeconds(45)}
};
DataCacheFactory cacheFactory;
try
{
cacheFactory = new DataCacheFactory(cacheFactoryConfig);// <--stops here
}
catch (Exception e)
{
Trace.WriteLine(string.Format("--> Message-> {0}; --> Stack Trace->{1}", e.Message, e.StackTrace));
throw;
}
cacheClient = cacheFactory.GetDefaultCache();
Service configuration:
Cache client and server configuration in web.config
I would give any additional information if such is requested in order to resolve the problem shortly.
------EDIT 1------------------
Due to related post Making Windows Azure Caching Work in Compute Emulator I have to add some info:
Operating sistem -> Windows 7 Professional
IDE -> Visual Studio 2013 Ultimate Update 4
Windows Azure Caching package 2.4.0.0
Windows Azure SDK Version 2.4
I don't have Windows Server AppFabric installed, so I'm going for it!
After few days of investigation, I managed to solve the issue and successfully create instance of DataCacheFactory and DataCache and so on. The problem is described and solved in the following 2 posts:
https://social.msdn.microsoft.com/Forums/azure/en-US/8580689a-a1a1-4db7-bba9-f42c1a90e0db/windows-azure-webrole-caching-preview-hangs-makes-the-emulator-stuck-in-deploy-loop?forum=windowsazuredevelopment
http://blog.elastacloud.com/2012/06/09/using-the-windows-azure-cache-preview-with-sdk-1-7/
In my case, I had Microsoft Server AppFabric installed, so I removed it.
Just in case, I removed all available Windows Azure SDKs (2.4 was installed) and
all old nuget packages related to Azure Caching.
I did verify that all assemblies are removed from GAC too.
After "cleaning" I install again latest Azure SDK available which is 2.5. http://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-in-role/
I would like to point out, that windows Event Viewer helped a lot. In Windows Azure logs I found an error that was happening when I start the web role with Azure Emulator. Error was thrown by CacheInstaller.exe -> MissingMethodExceprion with message:
Method not found:
'Microsoft.ApplicationServer.Caching.ClusterConfigElement

Why can't i access the RoleEnvironment in Application_Start when using a RoleEntryPoint?

I have a Azure WebRole which I'm trying to configure logging for using the DiagnosticMonitor.
According to the documentation at windowsazure.com the logging should be implemented in OnStart:
Note: The code in the following steps is typically added to the OnStart method of the role.
https://www.windowsazure.com/en-us/develop/net/common-tasks/diagnostics/
In order to access the OnStart method I have to define a RoleEntryPoint. But once it is defined I can't access the RoleEnvironment in web applications Application_Start.
How can I make the RoleEnvironment available to the application while still being able to use the DiagnosticMonitor?
I store the applications connection-strings in the service configuration.
public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
// config
var config = DiagnosticMonitor.GetDefaultInitialConfiguration();
LocalResource localResource = RoleEnvironment.GetLocalResource("MyCustomLogs");
DirectoryConfiguration dirConfig = new DirectoryConfiguration();
dirConfig.Container = "wad-mycustomlogs-container";
dirConfig.DirectoryQuotaInMB = localResource.MaximumSizeInMegabytes;
dirConfig.Path = localResource.RootPath;
DiagnosticMonitorConfiguration diagMonitorConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();
diagMonitorConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);
diagMonitorConfig.Directories.DataSources.Add(dirConfig);
DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", config);
return base.OnStart();
}
I've solved it.
After cleaning my solution, rebuilding, restarting IIS, shutting down the azure emulators and restarting Visual Studio it suddenly started working.
I changed no code at all.
(I even did all of those things before posting as well but it only worked when I did it all at the same time)
This is defintely the right example set of code. You need to set all of this in the Role though NOT in your web application.
NOTE: since Azure now has full IIS the context is different between the RoleEntryPoint On_start and the Web application, which is running in it's own worker pool within IIS.
Just a quick sanity checklist:
The code you're writing is in your class that inherits from RoleEntryPoint (typically WebRole.cs NOT in the Global.asax)?
You're running the project in the Azure Emulator (not inadvertently starting a web project directly?)
If you're running the application in the Azure emulator or deployed to Azure itself RoleEnvironment is available from within your IIS application as long as you have the relevant DLLs reference. If you can build with RoleEnvironment.IsAvailable in your code, then the libraries are included. The only thing I can think is that you're running the web site directly, not within the Azure emulator.
Set the Cloud project to be your startup in Visual Studio and you should be golden.

Categories

Resources