ReuseScope.Request not working in mono with self host - servicestack

I am registering a service with ReuseScope.Request and in some cases (read below) I get the exception:
Error trying to resolve Service 'Ceco.ServiceStack.TestService.TestService' or one of its autowired dependencies (see inner exception for details).
Basically this registration:
container.RegisterAutoWiredAs<FakeAgent, IAgent>().ReusedWithin(ReuseScope.Request);
which is required for the service:
public class TestService : Service {
private readonly IAgent _agent;
public TestService(IAgent agent) {
_agent = agent;
}
public object Get(TestRequest request) {
return _agent.Process(request);
}
}
is working as expected on Windows via MS.NET with both web application and self host.
On Ubuntu 14.04 via Mono 3.2.8 web application is fine. A console application with a self host (checked all three: AppSelfHostBase, AppHostHttpListenerPoolBase and AppHostHttpListenerSmartPoolBase) is throwing the aforementioned exception. If I change the ReuseScope to None it stops complaining but it is not what I want, obviously...
I am using ServiceStack 4.0.20. The above code was working as expected with 3.9.71. The code which can be used to reproduce this is in a github repo.
Question: Is this a bug and if yes - is there a workaround or I should just stick to 3.9.71?
UPDATE1:
It seems I cannot force ServiceStack to show me the inner exception. When I add in Configure:
Config.DebugMode = true;
Config.ReturnsInnerException = true;
it just returns the following stack trace (which I think is not for the inner exception but just the general failure for not being able to resolve an instance of class implementing IAgent service):
Stack Traceat Funq.Container.ResolveImpl (string,bool) <0x0010b> at Funq.Container.ResolveNamed (string) <0x00033> at Funq.Container.Resolve () <0x00027> at (wrapper dynamic-method) object.lambda_method (System.Runtime.CompilerServices.Closure,Funq.Container) <0x00024> at ServiceStack.Host.ContainerResolveCache.CreateInstance (System.Type,bool) <0x00123> at ServiceStack.Host.ContainerResolveCache.CreateInstance (System.Type) <0x0001f> at ServiceStack.Host.ServiceController/<>c__DisplayClass11.b__f (ServiceStack.Web.IRequest,object) <0x000a1> at ServiceStack.Host.ServiceController.Execute (object,ServiceStack.Web.IRequest) <0x000af> at ServiceStack.HostContext.ExecuteService (object,ServiceStack.Web.IRequest) <0x0005f> at ServiceStack.Host.Handlers.ServiceStackHandlerBase.ExecuteService (object,ServiceStack.Web.IRequest) <0x0001b> at ServiceStack.Host.RestHandler.GetResponse (ServiceStack.Web.IRequest,object) <0x00077> at ServiceStack.Host.RestHandler.ProcessRequestAsync (ServiceStack.Web.IRequest,ServiceStack.Web.IResponse,string) <0x005e8>

An option to get RequestContext to use ThreadStatic has been added in ServiceStack v4.0.21, e.g:
RequestContext.UseThreadStatic = true;

Related

Accidentally underlying NullReferenceException issue in EntityFramework in ASP.NET MVC 5

experts
I'm running into a trouble when access the home page in my MVC 5 web site, please see the exception details below.
MVC 5.2.2
EntityFramework 6.1.1
Visual Studio 2013
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.TryGetFieldOrPropertyValue(MemberExpression me, Object instance, Object& memberValue)
at System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.TryEvaluatePath(Expression expression, ConstantExpression& constantExpression)
at System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.EvaluateParameter(Object[] arguments)
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassc.<GetResultsAsync>b__a()
at System.Data.Entity.Core.Objects.ObjectContext.<ExecuteInTransactionAsync>d__3d`1.MoveNext()
The code is quite simple, it query data asynchronously from the data context shared in the current OwinContext, it works well as usual, but accidentally, it fail because of the error previously.
public class TalentsService : ServiceBase
{
public async Task<List<TalentSummaryViewModel>> GetSlotlightTalents()
{
var talents = await DbContext.Talents.Where(t => t.IsSpotlight && IsAuthenticated).ToListAsync();
return talents.Select(t => WrapModel(t)).ToList();
}
}
public abstract class ServiceBase
{
private ApplicationDbContext _dbContext;
public ApplicationDbContext DbContext
{
get
{
return _dbContext ?? HttpContext.Current.GetOwinContext().Get<ApplicationDbContext>();
}
private set
{
_dbContext = value;
}
}
public bool IsAuthenticated
{
get
{
return HttpContext.Current.Request.IsAuthenticated;
}
}
}
Is that multi-thread related? I can't figure out what could be the root cause, any clue would be appreciated, thanks in advance.
Thanks Chris Pratt for the response which led me to double check my code, the root cause is that:
The HttpContext.Current is null in some scenario which I'm not aware of, then the call to this property IsAuthenticated failed, so I would have to store the IsAuthenticated value in a local variable, now I could repro this issue easily when use the LoadTest tool to launch lots of request, but still not clear why does the context get lost accidentally, probably somebody else have more knowledge on this.
I had the same error after the 1st HTTP request to my Web API which was reproducible only if the IIS application was recycled. Apparently after restarting IIS the first incoming request was initiating data retrieval via IQueryable with inline ClientID parameter extracted from:
(HttpContext.Current.User as ClaimsPrincipal).Claims collection in asynchronous fashion.
So by the time the I/O operation was completed -- the HttpRequest context did not exist...
Copying Http Claim value into separate variable and using this variable when contructing IQueryable solved the problem:
var claims = (HttpContext.Current.User as ClaimsPrincipal).Claims;

Custom maintenance mode module does not work on Azure Web Role

I've created and registered custom http module to show maintenance message to user after administrator turns on maintenance mode via configuration change.
When I pass request for html it should return custom html loaded from file, but it returns message: "The service is unavailable." I can't find that string in my entire solution. Custom log message from custom maintenance module is written to log4net logs.
... INFO DdiPlusWeb.Common.MaintenanceResponder - Maintenance mode is on. Request rejected. RequestUrl=...
Seems something is miss configured in IIS on Azure. Something intercepts my 503 response. How to fix it?
Module code
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
if (AppConfig.Azure.IsMaintenance)
{
MaintenanceResponder responder = new MaintenanceResponder(context, MaintenaceHtmlFileName);
responder.Respond();
}
}
Interesting part of responder code.
private void SetMaintenanceResponse(string message = null)
{
_context.Response.Clear();
_context.Response.StatusCode = 503;
_context.Response.StatusDescription = "Maintenance";
if (string.IsNullOrEmpty(message))
{
_context.Response.Write("503, Site is under maintenance. Please try again a bit later.");
}
else
{
_context.Response.Write(message);
}
_context.Response.Flush();
_context.Response.End();
}
EDIT: I lied. Sorry. Maintenance module returns the same message for requests that expect json or html.
This answer led me to the solution.
I've added another line to SetMaintenanceResponse method.
_context.Response.TrySkipIisCustomErrors = true;
It works now. Here is more about what it exactly means.

RMI calls by multiple concurrent users to JBoss AS 4.2.3

I want to write a web frontend that wants to "propagate" the HTTP authentication received from the browser to a JBoss AS 4.2.3 that exposes numerous #Remote interfaces.
Consider the following trivial simulation of RMI call concurrency:
Properties user1 = new Properties();
user1.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.jboss.security.jndi.JndiLoginInitialContextFactory");
user1.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming");
user1.setProperty(Context.PROVIDER_URL, "127.0.0.1:1099");
user1.setProperty(Context.SECURITY_PRINCIPAL, "user1");
user1.setProperty(Context.SECURITY_CREDENTIALS, "pass1");
Properties user2 = new Properties();
user2.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.jboss.security.jndi.JndiLoginInitialContextFactory");
user2.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming");
user2.setProperty(Context.PROVIDER_URL, "127.0.0.1:1099");
user2.setProperty(Context.SECURITY_PRINCIPAL, "user2");
user2.setProperty(Context.SECURITY_CREDENTIALS, "pass2");
InitialContext ctx1 = new InitialContext(user1);
Mine bean1 = (Mine) ctx1.lookup("myear/MyBean/remote");
InitialContext ctx2 = new InitialContext(user2);
Mine bean2 = (Mine) ctx2.lookup("myear/MyBean/remote");
System.out.println(bean1.whoami());
System.out.println(bean2.whoami());
Call uses jbossall-client 4.2.3 and goes to a JBoss AS 4.2.3.
The .whoami() method simply echoes the logged-in username. As it turns our, this results in both calls saying they are made by "user2". Presumably, the underlying connection is shared and only authenticated using the last seen properties bundle.
In short, this sucks. Some preliminary testing indicates that the same problem remains in JBoss AS 7 so no luck.
Is there any other RMI client implementation I can use or any parameter I can pass in the prop bundle to make the InitialContexts not share their login info? Alternatively, can someone point me to the code that needs to be hacked to make this possible?
UPDATE:
As per request:
public class Worker extends Thread {
private final String pass, user;
private int correct = 0;
public Worker(String user, String pass) { this.user = user; this.pass = pass; }
public void run() {
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.jboss.security.jndi.JndiLoginInitialContextFactory");
props.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming");
props.setProperty(Context.PROVIDER_URL, "127.0.0.1:1099");
props.setProperty(Context.SECURITY_PRINCIPAL, this.user);
props.setProperty(Context.SECURITY_CREDENTIALS, this.pass);
try {
InitialContext ctx = new InitialContext(props);
for(int i = 0; i < 100; i++) {
Mine bean = (Mine) ctx.lookup("myear/MyBean/remote");
if(bean.whoami().equals(this.user)) this.correct++;
Thread.sleep(2); }
ctx.close();
} catch (Exception e) { throw new RuntimeException(e); }
System.out.println("Done [id="+this.getId()+", good="+this.correct+"]");
}
}
Running with two workers yields:
public static void main(String[] args) throws Exception {
new Worker("user1", "pass1").start();
new Worker("user2", "pass2").start();
}
Done [t=9, good=0]
Done [t=10, good=100]
Running with 5 threads yields:
public static void main(String[] args) throws Exception {
new Worker("user1", "pass1").start();
new Worker("user2", "pass2").start();
new Worker("user3", "pass3").start();
new Worker("user4", "pass4").start();
new Worker("user5", "pass5").start();
}
Caused by: javax.ejb.EJBAccessException: Authentication failure
at org.jboss.ejb3.security.Ejb3AuthenticationInterceptor.handleGeneralSecurityException(Ejb3AuthenticationInterceptor.java:68)
at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:70)
at org.jboss.ejb3.security.Ejb3AuthenticationInterceptor.invoke(Ejb3AuthenticationInterceptor.java:110)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:46)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:106)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
at org.jboss.ejb3.stateless.StatelessContainer.dynamicInvoke(StatelessContainer.java:304)
at org.jboss.aop.Dispatcher.invoke(Dispatcher.java:106)
at org.jboss.aspects.remoting.AOPRemotingInvocationHandler.invoke(AOPRemotingInvocationHandler.java:82)
at org.jboss.remoting.ServerInvoker.invoke(ServerInvoker.java:809)
at org.jboss.remoting.transport.socket.ServerThread.processInvocation(ServerThread.java:608)
at org.jboss.remoting.transport.socket.ServerThread.dorun(ServerThread.java:406)
at org.jboss.remoting.transport.socket.ServerThread.run(ServerThread.java:173)
at org.jboss.remoting.MicroRemoteClientInvoker.invoke(MicroRemoteClientInvoker.java:163)
at org.jboss.remoting.Client.invoke(Client.java:1634)
at org.jboss.remoting.Client.invoke(Client.java:548)
at org.jboss.aspects.remoting.InvokeRemoteInterceptor.invoke(InvokeRemoteInterceptor.java:62)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
at org.jboss.aspects.tx.ClientTxPropagationInterceptor.invoke(ClientTxPropagationInterceptor.java:67)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
at org.jboss.aspects.security.SecurityClientInterceptor.invoke(SecurityClientInterceptor.java:53)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
at org.jboss.ejb3.remoting.IsLocalInterceptor.invoke(IsLocalInterceptor.java:74)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
at org.jboss.ejb3.stateless.StatelessRemoteProxy.invoke(StatelessRemoteProxy.java:107)
at $Proxy0.whoami(Unknown Source)
at net.windwards.Worker.run(TestRMIClient.java:31)
at org.jboss.aspects.remoting.InvokeRemoteInterceptor.invoke(InvokeRemoteInterceptor.java:74)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
at org.jboss.aspects.tx.ClientTxPropagationInterceptor.invoke(ClientTxPropagationInterceptor.java:67)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
at org.jboss.aspects.security.SecurityClientInterceptor.invoke(SecurityClientInterceptor.java:53)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
at org.jboss.ejb3.remoting.IsLocalInterceptor.invoke(IsLocalInterceptor.java:74)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
at org.jboss.ejb3.stateless.StatelessRemoteProxy.invoke(StatelessRemoteProxy.java:107)
at $Proxy0.whoami(Unknown Source)
at net.windwards.Worker.run(TestRMIClient.java:31)
Making the initial connection takes about 100 ms, so I tried the following (sleeping 10 ms between calls to get good overlap):
public static void main(String[] args) throws Exception {
new Worker("user1", "pass1").start();
Thread.sleep(200);
new Worker("user2", "pass2").start();
Thread.sleep(200);
new Worker("user3", "pass3").start();
Thread.sleep(200);
new Worker("user4", "pass4").start();
Thread.sleep(200);
new Worker("user5", "pass5").start();
}
Done [t=9, good=1]
Done [t=14, good=12]
Done [t=15, good=14]
Done [t=16, good=15]
Done [t=17, good=100]
From the docs for org.jboss.security.jndi.JndiLoginInitialContextFactory :
During the getInitialContext callback from the JNDI naming, layer security context identity is populated with the username ... and the credentials ... There is no actual authentication of this information. It is merely made available to the jboss transport layer for incorporation into subsequent invocations
in this case, by the time you get to invoke your beans, user2 is the last principal set and so is the one available to be used by the jboss transport layer.
However, from the jboss4 source, it looks like you can make the security context scoped to the thread context, in which case your threaded test should work, simply add this property:
userN.setProperty("jnp.multi-threaded", "true");
Another solution would be using org.jboss.security.jndi.LoginInitialContextFactory instead of org.jboss.security.jndi.JndiLoginInitialContextFactory, unlike JndiLoginInitialContextFactory, LoginInitialContextFactory will try to authenticate when the look up is made, not when the EJB is invoked, you could give it a try, even though in the docs, they recommend JndiLoginInitialContextFactory when it comes to EJB authorization on remote clients
The basic problem here is that you haven't close the first context before you use the second one in the same thread. I doubt that this is a fair test. It would be more interesting to actually make the two concurrent, by running them both in separate threads.
When the getInitialContext() is being called from the JNDI, the Security Layer invokes a wrapper with the credential tiles; which is factually never verified with a source, it is just type of a virtual representation of the tiles to JBOSS for subsequent calls to the same entity model.
In your case, user2 is the last one to be available to JBOSS.
Alternatively, you can also use multiple instances of JBOSS on the
same machine by using ServiceBindingManager. This could help you
keep a track of all RMI calls you make, also the properties for the
Connector Object do work because itself is a JMX Bean Object.
You can also use a threaded model which can give you additional security by
adding a property
userN.setProperty("jnp.multi-threaded", "true");
And just as a suggestion, I found online Use JndiLoginInitialContextFactory for EJB Authentication on remote clients.
Hope this helps!

simple GlassFish embedded security fails: Login failed: Unable to locate a login configuration

I'm creating unit tests for our application, and I'm stuck. For testing I have a simple HelloWebServlet that I'm protecting via annotations:
#WebServlet(urlPatterns = {"/hello"})
#ServletSecurity(#HttpConstraint(rolesAllowed = {"user"}))
I'm starting the server the way that's always worked OK (see [1]) and creating users (see [2]) seems to be OK because output from CommandRunner calls to list-file-users and list-file-groups are correct, but I'm getting this error when I try to connect using the username and password:
WARNING: WEB9102: Web Login Failed: com.sun.enterprise.security.auth.login.common.LoginException: Login failed: Unable to locate a login configuration
The calling code uses the Jersey client API:
#Test
public void testPingServletLoggedIn() {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(GlassFishServerHelper.USERNAME, "xx"));
WebResource webResource = client.resource(GlassFishServerHelper.getBaseUri() + "/hello");
ClientResponse clientResponse = webResource
.accept(MediaType.TEXT_PLAIN)
.get(ClientResponse.class); // #GET
assertEquals(ClientResponse.Status.OK, clientResponse.getClientResponseStatus());
}
(Note: I tried to set javax.enterprise.system.core.security.level=FINE but that call failed with: PlainTextActionReporterFAILURENo configuration found for javax.enterprise.system.core.security . Drat!)
I've tried this against both glassfish-embedded-all-3.1.2.jar (our production version) and glassfish-embedded-all-3.2-b06.jar with the same results. What do you think would solve this? I've struggled and succeeded way too many times with GFE to give up without a fight!
==== [1] server startup (excerpt) ====
public static void startServer() {
GlassFishProperties gfProps = new GlassFishProperties();
gfProps.setPort("http-listener", PORT);
GLASSFISH = GlassFishRuntime.bootstrap().newGlassFish(gfProps);
GLASSFISH.start();
enableDefaultPrincipleToRoleMapping();
createUsersAndGroups();
ScatteredArchive archive = new ScatteredArchive(WEB_APP_NAME, ScatteredArchive.Type.WAR);
File classesDir = new File("out/production/simple-security-servlet-test");
archive.addClassPath(classesDir);
DEPLOYER = GLASSFISH.getDeployer();
APP_NAME = DEPLOYER.deploy(archive.toURI());
private static void enableDefaultPrincipleToRoleMapping() throws GlassFishException {
CommandRunner cr = GLASSFISH.getCommandRunner();
CommandResult result = cr.run("set",
"server-config.security-service.activate-default-principal-to-role-mapping=true");
}
==== [2] user creation (excerpt) ====
private static void createUsersAndGroups() throws GlassFishException {
CommandRunner commandRunner = GLASSFISH.getCommandRunner();
File passwordFile = new File("password-file.txt");
CommandResult result = commandRunner.run("create-file-user",
"--passwordfile", passwordFile.getAbsolutePath(),
"--groups", "user",
USERNAME
);
}
I was getting the same error and have managed to work around it, although my situation is slightly different. I'm starting GF 3.1.2 from the "maven-embedded-glassfish-plugin" maven plugin, but this might work for you as well.
Try setting the following system property:
java.security.auth.login.config=target/test-classes/login.conf
This should point to a copy of the login.conf file. You can find this file in the "config" folder in any Glassfish domain folder.

Sorrow, Rage and Despair setting up Azure storage

I'm trying to use Azure storage locally. I have a data source class called ExpenseDataSource:
public class ExpenseDataSource
{
private static CloudStorageAccount storageAccount;
private ExpenseTableContext context;
static ExpenseDataSource()
{
//CloudStorageAccount.SetConfigurationSettingPublisher(
// (configName, configSettingPublisher) =>
// {
// string connectionString = RoleEnvironment.GetConfigurationSettingValue(configName);
// configSettingPublisher(connectionString);
// }
//);
storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
CloudTableClient.CreateTablesFromModel(typeof(ExpenseTableContext), storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
}
public ExpenseDataSource()
{
context = new ExpenseTableContext(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));
}
public IEnumerable<ExpenseInfo> Select()
{
var results = from g in context.Expenses
where g.PartitionKey == "Expense"
select g;
return results;
}
// ...
}
(I'm new to Azure, so this class could be sub-optimal in many ways.)
When I try to create an object of type ExpenseDataSource, the following exception occurs:
System.TypeInitializationException: The type initializer for 'WebRole1.ExpenseDataSource' threw an exception. ---> System.InvalidOperationException: SetConfigurationSettingPublisher needs to be called before FromConfigurationSetting can be used
at Microsoft.WindowsAzure.CloudStorageAccount.FromConfigurationSetting(String settingName)
at WebRole1.ExpenseDataSource..cctor() in [ ... ]
--- End of inner exception stack trace ---
at WebRole1.ExpenseDataSource..ctor()
at WebRole1.ExpenseService.WebRole1.IExpenseService.GetExpenses() in [ ... ]
However, this is odd, because SetConfiguationSettingPublisher has already been called:
public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
DiagnosticMonitor.Start("DiagnosticsConnectionString");
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
RoleEnvironment.Changing += RoleEnvironmentChanging;
CloudStorageAccount.SetConfigurationSettingPublisher(
(configName, configSettingPublisher) =>
{
string connectionString = RoleEnvironment.GetConfigurationSettingValue(configName);
configSettingPublisher(connectionString);
}
);
return base.OnStart();
}
// ...
}
I am able to hit breakpoints here when I start debugging.
What am I doing wrong here?
Update: I thought that maybe I'd started the dev fabric and ASP.NET localhost out of order, so I killed them both, launched the dev fabic, then launched the ASP project. Still no luck - the same error occurs.
Update 2: I changed my OnStart() to this, but it still doesn't work:
public override bool OnStart()
{
DiagnosticMonitor.Start("DiagnosticsConnectionString");
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
RoleEnvironment.Changing += RoleEnvironmentChanging;
#region Setup CloudStorageAccount Configuration Setting Publisher
// This code sets up a handler to update CloudStorageAccount instances when their corresponding
// configuration settings change in the service configuration file.
CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
{
// Provide the configSetter with the initial value
configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
RoleEnvironment.Changed += (sender, arg) =>
{
if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>()
.Any((change) => (change.ConfigurationSettingName == configName)))
{
// The corresponding configuration setting has changed, propagate the value
if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
{
// In this case, the change to the storage account credentials in the
// service configuration is significant enough that the role needs to be
// recycled in order to use the latest settings. (for example, the
// endpoint has changed)
RoleEnvironment.RequestRecycle();
}
}
};
});
#endregion
return base.OnStart();
}
Update 3: I tried putting the "Setup CloudStorageAccount Configuration Setting Publisher" region in the ExpenseDataSource static initializer, and got the following error:
System.TypeInitializationException: The type initializer for 'WebRole1.ExpenseDataSource' threw an exception. ---> System.Runtime.InteropServices.SEHException: External component has thrown an exception.
at RoleEnvironmentGetConfigurationSettingValueW(UInt16* , UInt16* , UInt32 , UInt32* )
at Microsoft.WindowsAzure.ServiceRuntime.Internal.InteropRoleManager.GetConfigurationSetting(String name, String& ret)
at Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue(String configurationSettingName)
at WebRole1.ExpenseDataSource.<.cctor>b__0(String configName, Func`2 configSetter) in C:\Users\ODP\Documents\Visual Studio 2010\Projects\ExpenseCalc\WebRole1\ExpenseDataSource.cs:line 26
at Microsoft.WindowsAzure.CloudStorageAccount.StorageAccountConfigurationSetting..ctor(String configurationSettingName)
at Microsoft.WindowsAzure.CloudStorageAccount.FromConfigurationSetting(String settingName)
at WebRole1.ExpenseDataSource..cctor() in C:\Users\ODP\Documents\Visual Studio 2010\Projects\ExpenseCalc\WebRole1\ExpenseDataSource.cs:line 47
--- End of inner exception stack trace ---
at WebRole1.ExpenseDataSource..ctor()
at WebRole1.ExpenseService.WebRole1.IExpenseService.GetExpenses() in C:\Users\ODP\Documents\Visual Studio 2010\Projects\ExpenseCalc\WebRole1\ExpenseService.svc.cs:line 18
Update 3: Following smarx's suggestion, I changed the static initializer:
static ExpenseDataSource()
{
//storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
CloudTableClient.CreateTablesFromModel(typeof(ExpenseTableContext), storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
}
This leads to the following error:
System.TypeInitializationException: The type initializer for 'WebRole1.ExpenseDataSource' threw an exception. ---> System.Runtime.InteropServices.SEHException: External component has thrown an exception.
at RoleEnvironmentGetConfigurationSettingValueW(UInt16* , UInt16* , UInt32 , UInt32* )
at Microsoft.WindowsAzure.ServiceRuntime.Internal.InteropRoleManager.GetConfigurationSetting(String name, String& ret)
at Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue(String configurationSettingName)
at WebRole1.ExpenseDataSource..cctor() in C:\Users\ODP\Documents\Visual Studio 2010\Projects\ExpenseCalc\WebRole1\ExpenseDataSource.cs:line 20
--- End of inner exception stack trace ---
at WebRole1.ExpenseDataSource..ctor()
at WebRole1.ExpenseService.WebRole1.IExpenseService.GetExpenses() in C:\Users\ODP\Documents\Visual Studio 2010\Projects\ExpenseCalc\WebRole1\ExpenseService.svc.cs:line 18
The error is slightly different from above. Could this be related to the idea that I'm somehow not actually running ASP.NET within the dev fabric?
Ugh. I'm starting to miss Google App Engine storage's simple get() and put() interface.
1) Make sure that "DataConnectionString" is configured in your settings of WebRole.
In your Solution Explorer --> Under the "Roles" folder --> Right-click on | Properties --> Go to Settings tab and click "Add Setting". Enter Name: "DataConnectionString"; Type:"ConnectionString"; Value:"UseDevelopmentStorage=true" (if you want to debug and use local storage) or if you are planning to migrate to Azure-enter your storage account details.
2) (In the above code - Remove the comment for SetConfigurationSettingPublisher). Your code should look like this:
CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
{
configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
});
var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
I can think of two reasons:
You are using Azure SDK 1.3 and the SetConfigurationSettingPublisher must be called in your Global.asax.cs Application_Start;
You are not setting the Startup project as the *.CloudService one.
If you're still having problems, try actually selecting the Web Role under the Cloud Project and starting debugging from there, that has worked for me when I've had issues with other methods.
Had the same problem, I didn't had the Azure project as start-up project.
As Muhammad Omar mention in his comment on the question, see this related question as well.

Resources