I have the following code which was working nicely until recently
private async Task<DriveItem> CreateFolderIfNotExists(GraphServiceClient graphClient, string driveId, string folderName)
{
try
{
var driveItem = new DriveItem
{
Name = folderName,
Folder = new Folder(),
AdditionalData = new Dictionary<string, object>()
{
{ "#microsoft.graph.conflictBehavior", "fail" }
}
};
return await graphClient.Drives[driveId].Root.Children
.Request()
.AddAsync(driveItem);
}
catch (ServiceException exception)
{
if (exception.StatusCode != HttpStatusCode.Conflict)
{
throw;
}
return await this.GetFolderItem(graphClient, driveId, folderName);
}
}
All of a sudden we are getting this:
System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken) at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption) at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption) at xyz.CreateFolderIfNotExists(GraphServiceClient graphClient, String driveId, String folderName) in xyz\Client\SharePointClient.cs:line 63 at xyz.Client.SharePointClient.CopyLegacyFile(String fileId, String destination, String newFileName, String documentLibraryId) xyz\Client\SharePointClient.cs:line 222 at xyz.SharePointDocumentStorage.New() in xtz\SharePointDocumentStorage.cs:line 56 at zzzWorkflowAppService.NewRevision(NewRevisionInput input) at Abp.Authorization.AuthorizationInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation) at Abp.Domain.Uow.UnitOfWorkInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation) at Abp.EntityHistory.EntityHistoryInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation) at Abp.Auditing.AuditingInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation) at Abp.Runtime.Validation.Interception.ValidationInterceptor.InternalInterceptAsynchronou...
Any idea whats happening? There was no code push to cause this.
It is not a duplicate of What is a NullReferenceException, and how do I fix it?
It looks like my version of microsoft Graph which was version 1.21.0 needed to be be upgraded. There must have been a breaking change that was hosted with MS.
Its possible it is related to something like this issue https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues/901
Related
I have an apphost
public class LocalTestAppHost : AppSelfHostBase
{
public LocalTestAppHost() : base(nameof(LocalTestAppHost), typeof(MyServices).Assembly, typeof(LocalTestAppHost).Assembly) { }
public override void Configure(Container container)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
// .AddJsonFile("appSettings.json")
.AddEnvironmentVariables()
.AddUserSecrets(typeof(IntegrationTest).Assembly);
var configuration = builder.Build();
AppSettings = new NetCoreAppSettings(configuration);
container.AddSingleton<IAppSettings>(AppSettings);
SetConfig(new HostConfig
{
AddRedirectParamsToQueryString = true,
DebugMode = true
});
Plugins.Add(new CorsFeature(allowOriginWhitelist: new[] { IntegrationTestBase.BaseUriLocalDev },
allowedMethods: "GET, PATCH, POST, PUT, DELETE, OPTIONS",
allowCredentials: true,
allowedHeaders: "Content-Type, Allow, Authorization"));
JsConfig.DateHandler = DateHandler.ISO8601;
var connectionString = AppSettings.GetString("DefaultConnection");
OrmLiteConfig.StripUpperInLike = false;
container.AddSingleton<IDbConnectionFactory>(new OrmLiteConnectionFactory(connectionString, PostgreSqlDialect.Provider));
container.AddSingleton<IAuthRepository>(c =>
new OrmLiteAuthRepository<UserAuthCustom, UserAuthDetails>(c.Resolve<IDbConnectionFactory>())
{
UseDistinctRoleTables = true
});
Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[] {
new CredentialsAuthProvider(AppSettings)
{
}, /* Sign In with Username / Password credentials */
}));
Plugins.Add(new AdminUsersFeature());
}
}
And I am trying to run simple test where I log in (using existing connection to my local db)
public class ReportTests : IntegrationTestBase
{
private string _adminUser;
private string _adminPass;
public ReportTests()
{
Licensing.RegisterLicense(Licence);
this.AppHost = new LocalTestAppHost()
.Init()
.Start(BaseUriLocalDev);
Settings = AppHost.Resolve<IAppSettings>();
Db = AppHost.Resolve<IDbConnectionFactory>().OpenDbConnection();
_adminUser = Settings.GetString("adminUser");
_adminPass = Settings.GetString("adminPass");
}
[Test]
public void TestStats()
{
var users = Db.Select<UserAuthCustom>();
var client = new JsonServiceClient(BaseUriLocalDev);
var authReq = new Authenticate()
{
UserName = _adminUser,
Password = _adminPass,
provider = CredentialsAuthProvider.Name
};
var resp = client.Post(authReq);
}
But it throws this exception:
System.Net.WebException: Received an invalid status line: '400'.
---> System.Net.Http.HttpRequestException: Received an invalid status line: '400'.
at System.Net.Http.HttpConnection.ParseStatusLine(Span`1 line, HttpResponseMessage response)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpMessageHandlerStage.Send(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.SocketsHttpHandler.Send(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClientHandler.Send(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpMessageInvoker.Send(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.Send(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
at System.Net.HttpWebRequest.SendRequest(Boolean async)
at System.Net.HttpWebRequest.GetResponse()
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at ServiceStack.ServiceClientBase.Send[TResponse](String httpMethod, String relativeOrAbsoluteUrl, Object request) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack.Client\ServiceClientBase.cs:line 1416
at ServiceStack.ServiceClientBase.Post[TResponse](IReturn`1 requestDto) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack.Client\ServiceClientBase.cs:line 1581
at LeadInput.Tests.IntegrationTests.ReportTests.TestStats() in D:\Clients\LeadInput\LeadInput.Tests\IntegrationTests\ReportTests.cs:line 43
I am struggling to figure why it is not working and why it is not receiving a valid response from the apphost.
As the apphost only runs for scope of test I am finding it hard to debug. It seems like everything is correct but I am getting invalid response.
Stepping through code it is client.GetResponse(); that throws the exception, I guess it is getting unexpected format but I cannot see a way to get raw response in debugger.
Any ideas where I am going wrong?
EDIT
It happens also on hello world endpoint so I guess the AppHost is not running. I have tried changing the port but doesn't help. I upgraded to 5.13.3 recently, not sure if that's relevant.
EDIT
With debugger active this is logged:
DEBUG: CreateRequestAsync/requestParams:
WARN: Could not Set-Cookie 'ss-id': Could not load type 'Microsoft.Extensions.Primitives.InplaceStringBuilder' from assembly 'Microsoft.Extensions.Primitives, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'., Exception: Could not load type 'Microsoft.Extensions.Primitives.InplaceStringBuilder' from assembly 'Microsoft.Extensions.Primitives, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
You can try enabling debug logging in your AppHost to see if logs any info:
LogManager.LogFactory = new ConsoleLogFactory(debugEnabled:true);
Don't forget your Integration test needs to dispose the AppHost after it's run or other integration tests will fail:
[OneTimeTearDown]
public void OneTimeTearDown() => AppHost.Dispose();
One way to view the response is run your AppHost for a long time then you can view the output by inspecting the HTTP Request externally, e.g. via Chrome's WebInspector or curl:
[Test]
public void Run_for_30secs()
{
Thread.Sleep(30000);
}
It sounds like the AppHost isn't properly running, so I'd comment/disable features until you can isolate the problem.
Note: CORS isn't relevant in an integration test, it's only relevant when called from a Web browser making cross-domain requests.
I am using Azure Media Services v3 with an Azure Function v3 app and am running into an issue when trying to create a new job from an https url.
I have the following method in the Azure Function that submits a job.
private static async Task<Job> SubmitJobAsync(IAzureMediaServicesClient client, string transformNam, string jobName, string fileUrl) {
JobInputHttp jobInput = new JobInputHttp(files: new [] { fileUrl });
JobOutput[] jobOutputs =
{
new JobOutputAsset(jobName)
}
Job job = await client.Jobs.CreateAsync(
_resourceGroupName,
_accountName,
transformName,
jobName,
new Job
{
Input = jobInput,
Outputs = jobOutputs
},
CancellationToken.None);
return job;
}
It's failing on the line that actually creates the job await client.Jobs.CreateAsync(...
and is returning an exception with a message of:
Operation returned an invalid status code 'BadRequest'
Stack Trace:
at Microsoft.Azure.Management.Media.JobsOperations.CreateWithHttpMessagesAsync(String resourceGroupName, String accountName, String transformName, String jobName, Job parameters, Dictionary`2 customHeaders, CancellationToken cancellationToken)
at Microsoft.Azure.Management.Media.JobsOperationsExtensions.CreateAsync(IJobsOperations operations, String resourceGroupName, String accountName, String transformName, String jobName, Job parameters, CancellationToken cancellationToken)
Any idea what this means or how I can further debug this?
I think the problem comes from the fact that you did not create the Output Asset before creating the job.
Try to add these lines before the job creation :
string outputAssetName = jobName;
Asset outputAsset = await client.Assets.CreateOrUpdateAsync(_resourceGroupName, _accountName, outputAssetName, new Asset());
JobOutput[] jobOutputs =
{
new JobOutputAsset(outputAssetName)
}
See also :
https://github.com/Azure-Samples/media-services-v3-dotnet-core-functions-integration/blob/master/LiveAndVodDRMOperationsV3/LiveAndVodDRMOperationsV3/VodFunctions/submit-job.cs
I'm just starting to use Glimpse with my MVC5 project and have run into an issue when I use Postal to send an email without disabling Glimpse. I've been able to narrow it down to an issue with both packages - it doesn't occur if the Glimpse cookie has not been turned on.
In Fiddler, I checked the difference between the two. When it threw the exception, the cookie was
glimpsePolicy=On
when it worked (Glimpse was off) there were two cookies
glimpseId=FBar; glimpsePolicy=
The exception I get is
System.ArgumentNullException: Value cannot be null.
Parameter name: controllerContext
at System.Web.Mvc.ChildActionValueProviderFactory.GetValueProvider(ControllerContext controllerContext)
at Castle.Proxies.Invocations.ValueProviderFactory_GetValueProvider.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Glimpse.Core.Extensibility.ExecutionTimer.Time(Action action)
at Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.ValueProviderFactoryProxy.GetValueProvider(ControllerContext controllerContext)
at System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext)
at System.Web.Mvc.ControllerBase.get_ValueProvider()
at Glimpse.Mvc.Message.ActionMessageExtension.AsActionMessage[T](T message, ControllerBase controller)
at Glimpse.Mvc.AlternateType.ViewEngine.FindViews.PostImplementation(IAlternateMethodContext context, TimerResult timerResult)
at Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IViewEngineProxy.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache)
at System.Web.Mvc.ViewEngineCollection.<>c__DisplayClass6.<FindView>b__4(IViewEngine e)
at System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths)
at System.Web.Mvc.ViewEngineCollection.Find(Func`2 cacheLocator, Func`2 locator)
at Postal.EmailViewRenderer.Render(Email email, String viewName)
at Postal.EmailService.Send(Email email)
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid1[T0](CallSite site, T0 arg0)
at System.Web.Mvc.ActionMethodDispatcher.<>c__DisplayClass1.<WrapVoidAction>b__0(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at Castle.Proxies.Invocations.AsyncControllerActionInvoker_EndInvokeActionMethod.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Glimpse.Mvc.AlternateType.AsyncActionInvoker.EndInvokeActionMethod.NewImplementation(IAlternateMethodContext context)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.AsyncControllerActionInvokerProxy.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass30.<BeginInvokeActionMethodWithFilters>b__2f(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass1e.<>c__DisplayClass28.<BeginInvokeAction>b__19()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass1e.<BeginInvokeAction>b__1b(IAsyncResult asyncResult)
I created a quick action to test it. The controller code is:
public void TestEmailExt()
{
var confirmationToken = "ConfirmationToken";
var Phone1 = "**********";
dynamic email = new Email("RegEmail");
email.To = "**#gmail.com";
email.UserName = "UserName";
email.ConfirmationToken = confirmationToken;
email.Phone = Extensions.Right(Phone1, 4);
if (email.To.Contains("#mydomain"))
email.From = INTERNAL_EMAIL_FROM;
else
email.From = EXTERNAL_EMAIL_FROM;
email.Send();
}
The reason this fails is because the Postal library creates its own HttpContext instance while rendering the email view as the decompiled CreateControllerContext method inside Postal's EmailViewRenderer class shows:
private ControllerContext CreateControllerContext()
{
HttpContextWrapper httpContextWrapper = new HttpContextWrapper(new HttpContext(new HttpRequest("", this.UrlRoot(), ""), new HttpResponse(TextWriter.Null)));
RouteData routeData = new RouteData();
routeData.Values["controller"] = (object) this.EmailViewDirectoryName;
return new ControllerContext(new RequestContext((HttpContextBase) httpContextWrapper, routeData), (ControllerBase) new EmailViewRenderer.StubController());
}
This means that the setup that Glimpse does at BeginRequest is completely removed, while the hooks are still in place to intercept MVC related calls.
We've had a similar issue where I gave a similar response to why this is not working.
UPDATE :
I mentioned above that a similar issue had been reported previously, but while I was trying to find a more appropriate solution, it seemed that this case is slightly different in that respect that the other similar issue actually executes a controller with the freshly created context resulting in a NullReferenceException in Glimpse specific code, while here we get a NullReferenceException inside MVC specific code, albeit triggered by Glimpse.
System.ArgumentNullException: Value cannot be null.
Parameter name: controllerContext
at System.Web.Mvc.ChildActionValueProviderFactory.GetValueProvider(ControllerContext controllerContext)
And the exception we get here is because the ControllerContext property on the StubController instance (created inline) is null, which would normally be set when executing the controller (which is not the case here).
So the workaround that I proposed below still applies, but can be avoided if the code of the CreateControllerContext() above is slightly modified:
private ControllerContext CreateControllerContext()
{
HttpContextWrapper httpContextWrapper = new HttpContextWrapper(new HttpContext(new HttpRequest("", this.UrlRoot(), ""), new HttpResponse(TextWriter.Null)));
RouteData routeData = new RouteData();
routeData.Values["controller"] = (object) this.EmailViewDirectoryName;
// MODIFIED
var stubController = new EmailViewRenderer.StubController();
var controllerContext = new ControllerContext(new RequestContext(httpContextWrapper, routeData), stubController);
stubController.ControllerContext = controllerContext;
return controllerContext;
}
I've created an issue for this on the Postal issue tracker
END OF UPDATE
I think the best solution, for now, is to disable Glimpse while calling into Postal and restore normal Glimpse behavior back again afterwards. We might include this one way or the other into the Glimpse Core library in one of the upcoming releases as it seems that disabling Glimpse during a specific part of the request processing logic doesn't seem to be that uncommon, but for now the following snippet might help you (beware it makes use of a Glimpse internal key which is not guaranteed to be there in an upcoming release)
public class GlimpseSuppressionScope : IDisposable
{
private const string GlimpseRequestRuntimePermissionsKey = "__GlimpseRequestRuntimePermissions";
private readonly HttpContext currentHttpContext;
private readonly RuntimePolicy? currentRuntimePolicy;
private bool disposed;
public GlimpseSuppressionScope(HttpContext currentHttpContext)
{
if (currentHttpContext == null)
{
throw new ArgumentNullException("currentHttpContext");
}
this.currentHttpContext = currentHttpContext;
this.currentRuntimePolicy = this.currentHttpContext.Items[GlimpseRequestRuntimePermissionsKey] as RuntimePolicy?;
this.currentHttpContext.Items[GlimpseRequestRuntimePermissionsKey] = RuntimePolicy.Off;
}
~GlimpseSuppressionScope()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (this.currentHttpContext != null)
{
this.currentHttpContext.Items.Remove(GlimpseRequestRuntimePermissionsKey);
if (this.currentRuntimePolicy.HasValue)
{
this.currentHttpContext.Items[GlimpseRequestRuntimePermissionsKey] = this.currentRuntimePolicy.Value;
}
}
}
this.disposed = true;
}
}
}
which you can then use in your controller action method as shown below:
public void TestEmailExt()
{
using (new GlimpseSuppressionScope(System.Web.HttpContext.Current))
{
var confirmationToken = "ConfirmationToken";
var Phone1 = "**********";
dynamic email = new Email("RegEmail");
email.To = "**#gmail.com";
email.UserName = "UserName";
email.ConfirmationToken = confirmationToken;
email.Phone = Extensions.Right(Phone1, 4);
if (email.To.Contains("#mydomain"))
email.From = INTERNAL_EMAIL_FROM;
else
email.From = EXTERNAL_EMAIL_FROM;
email.Send();
}
}
i am trying to insert an image from an Win 8 App into Azure blob .I am running into an 500 exception when i try to do this . This is the class i am using -
private MobileServiceCollection<TodoItem, TodoItem> items;
private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>();
[DataContract]
public class TodoItem
{
[DataMember(Name = "id")]
public int ID { get; set; }
[DataMember(Name = "text")]
public string Text { get; set; }
[DataMember(Name = "containerName")]
public string ContainerName { get; set; }
[DataMember(Name = "resourceName")]
public string ResourceName { get; set; }
[DataMember(Name = "sasQueryString")]
public string SasQueryString { get; set; }
[DataMember(Name = "imageUri")]
public string ImageUri { get; set; }
}
The Exception is thrown at line -await todoTable.InsertAsync(todoItem);
At this time the exception is thrown the value of SASQueryString and ImageUri is NULL.
private async void OnTakePhotoClick(object sender, RoutedEventArgs e)
{
// Capture a new photo or video from the device.
CameraCaptureUI cameraCapture = new CameraCaptureUI();
media = await cameraCapture
.CaptureFileAsync(CameraCaptureUIMode.PhotoOrVideo);
TodoItem todoitem = new TodoItem { Text="NA",ContainerName="todoitemimages"};
InsertTodoItem(todoitem);
}
private async void InsertTodoItem(TodoItem todoItem)
{
string errorString = string.Empty;
if (media != null)
{
// Set blob properties of TodoItem.
todoItem.ResourceName = media.Name;
}
// Send the item to be inserted. When blob properties are set this
// generates an SAS in the response.
await todoTable.InsertAsync(todoItem);
// If we have a returned SAS, then upload the blob.
if (!string.IsNullOrEmpty(todoItem.SasQueryString))
{
// Get the new image as a stream.
using (var fileStream = await media.OpenStreamForReadAsync())
{
// Get the URI generated that contains the SAS
// and extract the storage credentials.
StorageCredentials cred = new StorageCredentials(todoItem.SasQueryString);
var imageUri = new Uri(todoItem.ImageUri);
// Instantiate a Blob store container based on the info in the returned item.
CloudBlobContainer container = new CloudBlobContainer(
new Uri(string.Format("https://{0}/{1}",
imageUri.Host, todoItem.ContainerName)), cred);
// Upload the new image as a BLOB from the stream.
CloudBlockBlob blobFromSASCredential =
container.GetBlockBlobReference(todoItem.ResourceName);
await blobFromSASCredential.UploadFromStreamAsync(fileStream.AsInputStream());
}
}
// Add the new item to the collection.
items.Add(todoItem);
}
IS there anyway i can resolve this exception .Thanks.
These are the exception details -
Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException
was unhandled HResult=-2146233079 Message=Error: Internal Server
Error Source=Microsoft.Threading.Tasks StackTrace:
at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)
at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task
task)
at Microsoft.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.WindowsAzure.MobileServices.MobileServiceTable`1.d_0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)
at DeltaVMobile.CrudeStorageScenario.d_22.MoveNext() in
c:\Users\~
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.b__0(Object
state)
at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch() InnerException:
By default, Azure Mobile Services have "dynamic schema" enabled, which means that you don't really need to define the columns in your tables - as long as you insert data, it will "figure out" the appropriate type and create the column for you. But it needs to figure out which type to use. In your case, this is the request which will be sent to the service (pretty-printing of JSON added for clarity, in reality it's sent without unnecessary whitespaces):
POST .../tables/TodoItem
Content-Type: application/json
{
"text":null,
"containerName":"todoitemimages",
"resourceName":null,
"sasQueryString":null,
"imageUri":null
}
When this gets to the service for the first time, it knows that you're trying to insert columns such as "text", "resourceName", but since there is no value associated to it (null can be of any type), it will fail to insert that data.
If this is indeed your problem, you have basically two choices: a simple one is to do a dummy insert once during development with all members of the type with some value - and right away issue a delete for the item which was inserted. This way the columns will be created and after that the runtime doesn't have to "guess" their types. The other choice is to set the EmitDefaultValue property in the [DataMember] attribute to false, which will make the serializer not emit the fields in the request with a null value.
I have been loving the clean conventions in ServiceStack however I recently ran into a vexing problem. The user loads a "create" page to create an "ad", then posts the form data. The server in term should process the posted data and redirect the user upon success.
I run this with the debugger. The POST method completes without error, but the server always returns the error after the service is finished:
Object reference not set to an instance of an object. AT
CompiledRazorTemplates.Dynamic.dfdcdedabeabca.Execute() at ServiceStack.Razor.Templating.TemplateService.ExecuteTemplate[T](T model, String name, String defaultTemplatePath, IHttpRequest httpReq, IHttpResponse httpRes) at ServiceStack.Razor.RazorFormat.ProcessRazorPage(IHttpRequest httpReq, ViewPageRef razorPage, Object dto, IHttpResponse httpRes) at ServiceStack.Razor.RazorFormat.ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, Object dto) at ServiceStack.WebHost.Endpoints.Formats.HtmlFormat.<>c__DisplayClass1.<SerializeToStream>b__0(IViewEngine x) at System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2 predicate) at ServiceStack.WebHost.Endpoints.Formats.HtmlFormat.SerializeToStream(IRequestContext requestContext, Object response, IHttpResponse httpRes) at ServiceStack.Common.Web.HttpResponseFilter.SerializeToStream(IRequestContext requestContext, Object response, Stream responseStream) at ServiceStack.Common.Web.HttpResult.WriteTo(Stream responseStream) at ServiceStack.WebHost.Endpoints.Extensions.HttpResponseExtensions.WriteToOutputStream(IHttpResponse response, Object result, Byte[] bodyPrefix, Byte[] bodySuffix) at ServiceStack.WebHost.Endpoints.Extensions.HttpResponseExtensions.WriteToResponse(IHttpResponse response, Object result, ResponseSerializerDelegate defaultAction, IRequestContext serializerCtx, Byte[] bodyPrefix, Byte[] bodySuffix)
Ive boiled the code down to this to isolate the issue:
[Route("/ad/create", Verbs = "GET")]
public class AdCreateViewModelCriteria
{
}
[Route("/ad/create", Verbs = "POST")]
public class AdCreate
{
//some things
}
public class AdCreateService:Service
{
//the error occurs AFTER this method is complete
public object Post(AdCreate ac)
{
try
{
//do some stuff
return new HttpResult()
{
StatusCode = HttpStatusCode.Redirect,
Headers ={{HttpHeaders.Location, "/home"}}
};
}
catch (Exception e)
{
return new HttpResult(e)
{
StatusCode = HttpStatusCode.InternalServerError
};
}
}
[DefaultView("adcreate")]
public object Get(AdCreateViewModelCriteria criteria)
{
return AdCreateViewModel.Load(criteria,Db);
}
}