asp.net-mvc-4azureazure-cachingazure-in-role-cache

Azure In Role Caching Doesn't start on server with "Not running in a hosted service or the Development Fabric."


I started to use Azure in-role caching and everything works great in Azure compute emulator on my local machine, but not on server. I've already dealed with some problems, like lack of msshrtmi.dll on server, but now can't understand why get this error:

Not running in a hosted service or the Development Fabric. 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.InvalidOperationException: Not running in a hosted service or the Development Fabric.

Source Error: 


 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace: 



[InvalidOperationException: Not running in a hosted service or the Development Fabric.]
   Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitor.GetDefaultStartupInfoForCurrentRoleInstance() +535
   Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener..ctor() +34

[ConfigurationErrorsException: Could not create Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.]
   System.Diagnostics.TraceUtils.GetRuntimeObject(String className, Type baseType, String initializeData) +1588
   System.Diagnostics.TypedElement.BaseGetRuntimeObject() +103
   System.Diagnostics.ListenerElement.GetRuntimeObject() +825
   System.Diagnostics.ListenerElementsCollection.GetRuntimeObject() +261
   System.Diagnostics.TraceInternal.get_Listeners() +256
   System.Diagnostics.Trace.get_Listeners() +79
   Microsoft.ApplicationServer.Caching.DataCacheServerLogManager..cctor() +97

[TypeInitializationException: The type initializer for 'Microsoft.ApplicationServer.Caching.DataCacheServerLogManager' threw an exception.]
   Microsoft.ApplicationServer.Caching.DataCacheServerLogManager.ChangeLogLevel(TraceLevel traceLevel) +0
   Microsoft.ApplicationServer.Caching.ServiceConfigurationManager..cctor() +24

[TypeInitializationException: The type initializer for 'Microsoft.ApplicationServer.Caching.ServiceConfigurationManager' threw an exception.]
   Microsoft.ApplicationServer.Caching.ServiceConfigurationManager.GetHostDefaults() +0
   Microsoft.ApplicationServer.Caching.OMCacheNodeProperties..ctor(IHostConfiguration props, Int32 maxNC, Boolean perfCounterRequired) +69
   Microsoft.ApplicationServer.Caching.LocalCacheStore..ctor(EvictionParametrs evictionParams) +50
   Microsoft.ApplicationServer.Caching.DataCacheFactory..ctor(DataCacheFactoryConfiguration configuration) +555
   Microsoft.Web.DistributedCache.DataCacheFactoryWrapper.CreateDataCacheFactoryFromConfiguration(DataCacheFactoryConfiguration config) +35
   Microsoft.Web.DistributedCache.CacheHelpers.RunCacheCreationHooks(CacheConnectingEventArgs fetchingEventArgs, IDataCacheFactory dataCacheFactory, Object sender, EventHandler`1 fetchingHandler, EventHandler`1 fetchedHandler) +70
   Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider.CreateInternalProvider(IHttpRuntime httpRuntime, OutputCacheInitializationData initData, IDataCacheFactory dataCacheFactory, EventHandler`1 cacheFetching, EventHandler`1 cacheFetched) +123
   Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider.GetInternalProvider() +224
   Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider.Get(String key) +13
   System.Web.Caching.OutputCache.Get(String key) +80
   System.Web.Caching.OutputCacheModule.OnEnter(Object source, EventArgs eventArgs) +321
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +182
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165

All I found about this error is that it occurs if you start local Azure compute emulator with in-role caching and without administrative rights. But in emulator everything works fine and problem occurs only after I publish to staging environment. (if switch to production, error remains).

I use cache for resolving routes like /username and /countryname etc. So available usernames and country names will be cached and updated on changes in database. I have static class with static DataCache object which is created on first request to cache. But even home page doesn't start so error occurs before I try to create cache object.

Web.Config. Is I remove all cache and cache diagnostics related configurations from web.config, app starts.

<configuration>
  <configSections>     
    <section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere" />
  <section name="cacheDiagnostics" type="Microsoft.ApplicationServer.Caching.AzureCommon.DiagnosticsConfigurationSection, Microsoft.ApplicationServer.Caching.AzureCommon" allowLocation="true" allowDefinition="Everywhere" /></configSections>
  <system.diagnostics>
    <trace>
      <listeners>
        <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics" />
      </listeners>
    </trace>
  </system.diagnostics>
  <system.data>
    <DbProviderFactories>
      <add name="Sql Azure Reliable Provider" invariant="ReliableDbProvider.SqlAzure" description="Reliable Db Provider for SQL Azure" type="ReliableDbProvider.SqlAzure.SqlAzureProvider, ReliableDbProvider" />
      <add name="Sql Azure Reliable Provider With Timeout Retries" invariant="ReliableDbProvider.SqlAzureWithTimeoutRetries" description="Reliable Db Provider for SQL Azure with Timeout Retries" type="ReliableDbProvider.SqlAzureWithTimeoutRetries.SqlAzureProvider, ReliableDbProvider" />
    </DbProviderFactories>
  </system.data>
  <connectionStrings>
    <add name="AppDB" connectionString="value" />
    <add name="StorageConnectionString" connectionString="value" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <!--
    For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.

    The following attributes can be set on the <httpRuntime> tag.
      <system.Web>
        <httpRuntime targetFramework="4.5" />
      </system.Web>
  -->
  <system.web>
    <customErrors mode="Off" />
    <roleManager enabled="true" defaultProvider="provider">
      <providers>
        <clear />
        <remove name="AspNetSqlRoleProvider" />
        <add name="name" type="type" />
      </providers>
    </roleManager>
    <membership defaultProvider="provider">
      <providers>
        <clear />
        <remove name="AspNetSqlMembershipProvider" />
        <add name="name" type="type" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="8" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="name" />
      </providers>
    </membership>
    <machineKey validationKey="key" decryptionKey="key" validation="SHA1" decryption="AES" />
    <httpCookies httpOnlyCookies="true" requireSSL="false" />
    <authentication mode="Forms">
      <forms loginUrl="~/account/logon" protection="All" path="/" enableCrossAppRedirects="true" timeout="2880" />
    </authentication>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <pages controlRenderingCompatibilityVersion="4.0">
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
        <add namespace="System.Web.Optimization" />
      </namespaces>
    </pages>
    <httpRuntime maxRequestLength="1048576" />
    <globalization enableClientBasedCulture="true" uiCulture="auto" culture="auto" />
  <!-- Windows Azure Cache session state provider --><!--<sessionState mode="Custom" customProvider="AFCacheSessionStateProvider">
      <providers>
        <add name="AFCacheSessionStateProvider" type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheSessionState"/>
      </providers>
    </sessionState>--><!-- Windows Azure Cache output cache provider --><!--Uncomment this section to use Windows Azure Cache for output cache-->
    <caching>
      <outputCache defaultProvider="AFCacheOutputCacheProvider">
        <providers>
          <add name="AFCacheOutputCacheProvider" type="Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheOutputCache" />
        </providers>
      </outputCache>
    </caching>
  </system.web>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
    </staticContent>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="false" />
    <directoryBrowse enabled="false" />
    <httpProtocol>
      <customHeaders>
        <!-- Enable Cross Domain AJAX calls -->
        <remove name="Access-Control-Allow-Origin" />
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
    <handlers>
      <add name="UrlRoutingHandler" type="System.Web.Routing.UrlRoutingHandler,                   System.Web, Version=4.0.0.0,                   Culture=neutral,                   PublicKeyToken=b03f5f7f11d50a3a" path="path" verb="GET" />
      <add name="UrlRoutingHandlerEmailLogo" type="System.Web.Routing.UrlRoutingHandler,System.Web, Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" path="path" verb="GET" />
      <add name="UrlRoutingHandlerSitemap" type="System.Web.Routing.UrlRoutingHandler,                   System.Web, Version=4.0.0.0,                   Culture=neutral,                   PublicKeyToken=b03f5f7f11d50a3a" path="path" verb="GET" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Abstractions" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.WindowsAzure.Diagnostics" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.2.0.0" newVersion="2.2.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network host="host" userName="username" password="password" />
      </smtp>
    </mailSettings>
  </system.net>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="2147483644" />
      </webServices>
    </scripting>
  </system.web.extensions>
  <dataCacheClients>
    <dataCacheClient name="default">                
      <autoDiscover isEnabled="true" identifier="sub2o" />
      <localCache isEnabled="true" sync="TimeoutBased" objectCount="100000" ttlValue="300" />        
    </dataCacheClient>    
  </dataCacheClients>
  <cacheDiagnostics>
    <crashDump dumpLevel="Off" dumpStorageQuotaInMB="100" />
  </cacheDiagnostics>
</configuration>

ServiceConfiguration.Cloud.cscfg

<ServiceConfiguration serviceName="WindowsAzure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="3" osVersion="*" schemaVersion="2013-10.2.2">
  <Role name="sub2o">
    <Instances count="1" />
    <ConfigurationSettings>
      <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="DefaultEndpointsProtocol=https;AccountName=name;AccountKey=key" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.Enabled" value="true" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountUsername" value="username" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountEncryptedPassword" value="password" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountExpiration" value="2014-09-07T23:59:59.0000000+04:00" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteForwarder.Enabled" value="true" />
      <Setting name="Microsoft.AppInsights.AccountId" value="ID" />
      <Setting name="Microsoft.AppInsights.InstrumentationKey" value="KEY" />
      <Setting name="Microsoft.AppInsights.EnableMonitoring" value="true" />
      <!-- Uncomment the following section if you want to change the Display Name of your application on the Application Insights Portal. (Default is your WebRole Name)-->
      <!--<Setting name="Microsoft.AppInsights.DisplayName" value="Name" />-->
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel" value="1" />
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.NamedCaches" value="{&quot;caches&quot;:[{&quot;name&quot;:&quot;default&quot;,&quot;policy&quot;:{&quot;eviction&quot;:{&quot;type&quot;:0},&quot;expiration&quot;:{&quot;defaultTTL&quot;:10,&quot;isExpirable&quot;:true,&quot;type&quot;:1},&quot;serverNotification&quot;:{&quot;isEnabled&quot;:false}},&quot;secondaries&quot;:0}]}" />
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel" value="1" />
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.CacheSizePercentage" value="30" />
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.ConfigStoreConnectionString" value="DefaultEndpointsProtocol=https;AccountName=name;AccountKey=key" />
    </ConfigurationSettings>
    <Certificates>
      <Certificate name="Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption" thumbprint="value" thumbprintAlgorithm="sha1" />
    </Certificates>
  </Role>
</ServiceConfiguration>

ServiceDefinition.csdef

<?xml version="1.0"?>
<ServiceDefinition name="WindowsAzure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2013-10.2.2">
  <WebRole name="sub2o" vmsize="Small">
    <Sites>
      <Site name="Web">
        <Bindings>
          <Binding name="Endpoint1" endpointName="Endpoint1" />
        </Bindings>
      </Site>
    </Sites>
    <Endpoints>
      <InputEndpoint name="Endpoint1" protocol="http" port="80" />
    </Endpoints>
    <Imports>
      <Import moduleName="Diagnostics" />
      <Import moduleName="RemoteAccess" />
      <Import moduleName="RemoteForwarder" />
      <Import moduleName="Caching" />
    </Imports>
    <Startup priority="-2">
      <Task commandLine="AppInsightsAgent\UnifiedBootstrap.bat" executionContext="elevated" taskType="background">
      </Task>
      <Task commandLine="Microsoft.WindowsAzure.Caching\ClientPerfCountersInstaller.exe install" executionContext="elevated" taskType="simple" />
    </Startup>
    <ConfigurationSettings>
      <Setting name="Microsoft.AppInsights.AccountId" />
      <Setting name="Microsoft.AppInsights.InstrumentationKey" />
      <Setting name="Microsoft.AppInsights.EnableMonitoring" />
      <!-- Uncomment the following section if you want to change the Display Name of your application on the Application Insights Portal. (Default is your WebRole Name)-->
      <!--<Setting name="Microsoft.AppInsights.DisplayName" />-->
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel" />
    </ConfigurationSettings>
    <LocalResources>
      <LocalStorage name="DiagnosticStore" sizeInMB="20000" cleanOnRoleRecycle="false" />
    </LocalResources>
  </WebRole>
</ServiceDefinition>

Solution

  • Problem was caused by conflict between SDK 2.2 and 2.3. Just need to update SDK for Windows Azure Cloud Service project from Properties->Application. So simple.