Graphics.CopyFromScreen [Web application] + The handle is invalid - graphics

I am using the below code to take print screen of my web page.
using (Bitmap bitmap = new Bitmap(620, 850))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
}
bitmap.Save(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + 1 + ".JPEG", ImageFormat.Jpeg);
}
It works fine in the development machine,but once i deploy it in the Server
it gives below error
Error Message:
The handle is invalid
Source: System.DrawingError
Stack Trace: at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY, Int32 destinationX, Int32 destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY, Int32 destinationX, Int32 destinationY, Size blockRegionSize)
at System.Drawing.Graphics.CopyFromScreen(Point upperLeftSource, Point upperLeftDestination, Size blockRegionSize)
at Secure_SearchReport.btnSearch_Click(Object sender, EventArgs e)
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
Its very urgent.
Any suggestion please.......

I would guess the graphics functionality is only available in rich-client applications. (Windows Forms)
This would be a huge security issue if webpages could capture snapshots of users' desktop.

You may try VisualJS.NET, the video under http://www.visualjs.net/Tutorials/WhatisVisualJSNET.aspx page could be helpful. They using Cassini Dev server in addition to built-in VisualJS.NET features in order to demonstrate very simple remote desktop over web application.

Related

Invalid Character reading xml file from Azure ServiceFabric Service

When I add Swagger (v2.5) on any Web Api service of my Azure ServiceFabric cluster, and the swagger documentation file contains accent marks (á, é, í...), I get this error:
Invalid character in the given encoding
I was passing the uri (path) of the xml file to swagger:
services.AddSwaggerGen(options =>
{
...
options.IncludeXmlComments(myxmlpath);
...
}
But according to this post I should pass a StreamReader to specify the encoding, so I swapped the code for this:
services.AddSwaggerGen(options =>
{
...
options.IncludeXmlComments(() => new XPathDocument(
new StreamReader(myxmlpath, Encoding.UTF8)));
...
}
In this way I managed to avoid the error, but in the swagger UI I see strange characters. For example, instead of áéíóú it shows:
����������
I don't understand why it works in my local cluster but it gives me encoding issues in my Azure cluster. I have not managed to reproduce the error in my local cluster.
Why the file parsing depends in any way on the node where the service is deployed (local or Azure)?
This is my entire stack trace before swapping the code:
Unhealthy event: SourceId='System.RA', Property='ReplicaOpenStatus', HealthState='Warning', ConsiderWarningAsError=false.
Replica had multiple failures during open on mynode01. API call: IStatelessServiceInstance.Open(); Error = System.Xml.XmlException (-2146232000)
Invalid character in the given encoding. Line 35, position 12.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.InvalidCharRecovery(Int32& bytesCount, Int32& charsCount)
at System.Xml.XmlTextReaderImpl.GetChars(Int32 maxCharsCount)
at System.Xml.XmlTextReaderImpl.ReadData()
at System.Xml.XmlTextReaderImpl.ParseText(Int32& startPos, Int32& endPos, Int32& outOrChars)
at System.Xml.XmlTextReaderImpl.ParseText()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space)
at System.Xml.XPath.XPathDocument..ctor(String uri, XmlSpace space)
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions.<>c__DisplayClass31_0.b__0()
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions.CreateSwaggerProvider(IServiceProvider serviceProvider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass4_0.b__0(RequestDelegate next)
at Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Start()
at Microsoft.ServiceFabric.Services.Communication.AspNetCore.AspNetCoreCommunicationListener.OpenAsync(CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.OpenCommunicationListenersAsync(CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.System.Fabric.IStatelessServiceInstance.OpenAsync(IStatelessServicePartition partition, CancellationToken cancellationToken)
For more information see: http://aka.ms/sfhealth
I finally found the problem. It was not a problem in the Azure environment. I had a release step in VSTS Replace Tokens with the Files Encoding option in auto. I changed it to utf-8 and it works!

Occasional 500s using Faces plugin - Delegates cannot be marshalled

We're using 3.4.3 of ImageResizer, and the elite plugins. It seems any trouble we’ve had have been related to the Faces plugin. Images will not show up, and upon looking at the network response, the stacktrace shows "Delegates cannot be marshaled from native code into a domain other than their home domain". Full trace is here
[NotSupportedException: Delegates cannot be marshaled from native code into a domain other than their home domain.]
System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t) +0
System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(IntPtr ptr, Type t) +267
OpenCvSharp.CvInvoke..cctor() +328
[TypeInitializationException: The type initializer for 'OpenCvSharp.CvInvoke' threw an exception.]
OpenCvSharp.Cv.Load(String filename, CvMemStorage memstorage, String name, String& real_name) +222
ImageResizer.Plugins.Faces.FeatureDetectionBase`1.LoadFiles() +621
ImageResizer.Plugins.Faces.FeatureDetectionBase`1.DetectFeatures(Bitmap b) +82
ImageResizer.Plugins.Faces.FacesPlugin.PostPrepareSourceBitmap(ImageState s) +341
ImageResizer.Resizing.AbstractImageProcessor.PostPrepareSourceBitmap(ImageState s) +99
ImageResizer.ImageBuilder.Process(ImageState s) +60
ImageResizer.ImageBuilder.buildToBitmap(Bitmap source, ResizeSettings settings, Boolean transparencySupported) +276
ImageResizer.ImageBuilder.buildToStream(Bitmap source, Stream dest, ResizeSettings settings) +149
ImageResizer.ImageBuilder.BuildJob(ImageJob job) +1353
ImageResizer.ImageBuilder.Build(ImageJob job) +268
ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings, Boolean disposeSource, Boolean addFileExtension) +124
ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings, Boolean disposeSource) +36
ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings) +23
ImageResizer.<>c__DisplayClass3.<HandleRequest>b__2(Stream stream) +287
ImageResizer.Plugins.DiskCache.<>c__DisplayClasse.<TryWriteFile>b__d() +593
ImageResizer.Plugins.DiskCache.LockProvider.TryExecute(String key, Int32 timeoutMs, LockCallback success) +424
ImageResizer.Plugins.DiskCache.CustomDiskCache.TryWriteFile(CacheResult result, String physicalPath, String relativePath, ResizeImageDelegate writeCallback, DateTime sourceModifiedUtc, Int32 timeoutMs, Boolean recheckFS) +517
ImageResizer.Plugins.DiskCache.CustomDiskCache.GetCachedFile(String keyBasis, String extension, ResizeImageDelegate writeCallback, DateTime sourceModifiedUtc, Int32 timeoutMs, Boolean asynchronous) +819
ImageResizer.Plugins.DiskCache.DiskCache.Process(IResponseArgs e) +209
ImageResizer.Plugins.DiskCache.DiskCache.Process(HttpContext context, IResponseArgs e) +47
ImageResizer.InterceptModule.HandleRequest(HttpContext context, String virtualPath, NameValueCollection queryString, IVirtualFile vf) +1687
ImageResizer.InterceptModule.CheckRequest_PostAuthorizeRequest(Object sender, EventArgs e) +1163
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +92
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
I found this page and ensured we weren't using overlapped recycling. I tried upgrading to 4.1.7, but it was a bit of a nightmare trying to get all the opencv versions/bitness to line up. The app would crash often and hold the rest of the sites depending on it hostage, so we rolled back to 3.4.3 which at least works, then doesn't. Our regular issues go away temporarily when we restart the IR app pool.
We have our web apps hosted on two VMS load-balanced by BigIP. Each VM has two web apps, and they share a single image resizer hosted on the same server as them which and utilizes the URL API to make resize requests, face detection + cropping, etc.
One other bit of info I was able to obtain was from DebugDiag. I grabbed a crash of the app with the following message:
In w3wp__ImageResizer__PID__5284__Date__06_14_2017__Time_08_23_10AM__122__First chance exception 0XE0434352.dmp the assembly instruction at KERNELBASE!RaiseException in C:\Windows\System32\KERNELBASE.dll from Microsoft Corporation has caused a CLR Exception on thread 28 with the following error information:
Type: ImageResizer.Plugins.Faces.AlternateResponseException
Message: Resizing was canceled as JSON data was requested instead
This exception originated from ImageResizer.Plugins.Faces.FacesPlugin.Render(ImageResizer.Resizing.ImageState).
Debug page can be found here

Out of memory exception using PdfSharp in a azure webjob

I'm using Azure Storage Queues to send a message to a WebJob. This WebJob then creates a PDF and stores it in a blob container. This works fine on my dev-machine. The message is received, object instantiated and PDF is created and stored in the blob storage. When I deploy the WebJob to Azure I get an Out of Memory exception at the moment it receives a message.
What are the memory limit and how do I keep below those limits?
public static void HandleNewRegistration(
[QueueInput("pdf")] Models.Registration registration,
[BlobOutput("pdf/{Name}.txt")] TextWriter writer,
[BlobOutput("pdf/{Name}.pdf")] Stream pdfWriter)
{
try
{
// Store received registration in database (using EF)
AppContext db = new AppContext();
db.Registrations.Add(registration);
db.SaveChanges();
// Create PDF document (nothing fancy, just a section with a paragraph)
var pdf = CreatePdf(registration);
var renderer = new MigraDoc.Rendering.PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
renderer.Document = pdf;
renderer.RenderDocument();
renderer.Save(pdfWriter,true);
}
catch (Exception e)
{
writer.WriteLine(e.Message);
writer.WriteLine(e.StackTrace);
}
writer.WriteLine(registration.Name);
}
Using this I end up with only a text file in my blob storage with the stack trace:
Out of memory.
at System.Drawing.Graphics.FromHwndInternal(IntPtr hwnd)
at System.Drawing.Graphics.FromHwnd(IntPtr hwnd)
at PdfSharp.Drawing.XGraphics..ctor(Graphics gfx, XSize size, XGraphicsUnit pageUnit, XPageDirection pageDirection)
at MigraDoc.Rendering.DocumentRenderer.PrepareDocument()
at MigraDoc.Rendering.PdfDocumentRenderer.PrepareDocumentRenderer(Boolean prepareCompletely)
at MigraDoc.Rendering.PdfDocumentRenderer.PrepareRenderPages()
at MigraDoc.Rendering.PdfDocumentRenderer.RenderDocument()
at WebJob.Program.HandleNewRegistration(Registration registration, TextWriter writer, Stream pdfWriter) in d:\Source\Workspaces\[...]\WebJob\Program.cs:line 43
Obviously you are using the GDI+ build of MigraDoc - and there is no GDI+ on the Azure Server and Graphics.FromHwnd() fails.
Use the WPF build of MigraDoc and things should run fine on the Azure Server.

Azure ACS with HTTPS and multiple instances Error

I just followed the following instructions here.
And found a couple blog entries here and here to be rather helpful.
But I am still getting weird issues with my ASP.NET MVC3 app running on Azure on an HTTPS end point. I have the HTTPS certificate loaded and it has deployed consistently on a single role instance for quite some time without any issue. However, just recently I started deploying multiple instances and ran into the 'Key not valid for use in specified state' and the 'Value cannot be null. Parameter name: certificate' erors.
But I have a new one now:
'Unable to read beyond the end of the stream.'
Looks pretty vanilla. It doesn't become obvious that its an issue with the move from DPAPI to the RSA cookie transform until you look at the stack trace.
[EndOfStreamException: Unable to read beyond the end of the stream.]
System.IO.MemoryStream.InternalReadInt32() +12750266
Microsoft.IdentityModel.Web.RsaEncryptionCookieTransform.Decode(Byte[] encoded) +369
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +189
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +862
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +109
Microsoft.IdentityModel.Web.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +356
Microsoft.IdentityModel.Web.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +123
Microsoft.IdentityModel.Web.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +61
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270
I have added the following code to global.asax:
void OnServiceConfigurationCreated(object sender, ServiceConfigurationCreatedEventArgs e)
{
//
// Use the <serviceCertificate> to protect the cookies that are sent to the client.
//
List<CookieTransform> sessionTransforms = new List<CookieTransform>(
new CookieTransform[] {
new DeflateCookieTransform(),
new RsaEncryptionCookieTransform(e.ServiceConfiguration.ServiceCertificate) });
SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
e.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler);
}
As well as this code:
void WSFederationAuthenticationModule_RedirectingToIdentityProvider(object sender, RedirectingToIdentityProviderEventArgs e)
{
// In the Windows Azure environment, build a wreply parameter for the SignIn request
// that reflects the real address of the application.
HttpRequest request = HttpContext.Current.Request;
Uri requestUrl = request.Url;
StringBuilder wreply = new StringBuilder();
wreply.Append(requestUrl.Scheme); // e.g. "http" or "https"
wreply.Append("://");
wreply.Append(request.Headers["Host"] ?? requestUrl.Authority);
wreply.Append(request.ApplicationPath);
if (!request.ApplicationPath.EndsWith("/")) wreply.Append("/"); e.SignInRequestMessage.Reply = wreply.ToString();
}
I recently worked on similar problem and the potential reason was combination of older SDK and ACS. If you try using SDK 1.6 and ACSv2 setting, i hope this problem will not occur and if you still see the problem, I would be glad to work with you to root cause it.

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