How to fix Database Null Exception in ASP.NET-MVC - asp.net-mvc

services.AddDbContext<StoreContext>(options =>
options.UseSqlServer(Configuration["Data:StoreProducts:ConnectionString"]));
In the appsettings.json:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
and in the appsetting.development.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Data": {
"StoreProducts": {
"ConnectionString": "Server=DESKTOP-I3K90LQ\\SQL2016;Database=BrooksStore;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
}
I am not sure why services threw me an exception saying options.UseSqlServer has null value in it.
Can anyone help?
Thank you!

The value is null because your connection string is in "appsetting.development.json" not "appsetting.json" so you can put your connection string in appsetting.json and it will work just fine.
EDIT
Actually you have a typo in your json file name it's "appsettings.Development.json" not "appsetting.development.json"
notice the 's'
now it should work correctly from your dev json file

Related

Request sent from Swagger UI not resulting in Postman x-www-form-urlencoded response

I'm currently configuring a Swagger file to utilize OAuth to retrieve tokens from a site. For brevity, I have removed my schemes and most of my paths as those are fine.
{
"openapi": "3.0.2",
"info": {
"title": "swagger",
"version": "1.0.0",
"description": ""
},
"servers": [
{
"url": "url"
}
],
"paths": {
"/oauth_token.do": {
"post": {
"requestBody": {
"required": true,
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"components": {
"securitySchemes": {
"OAuth": {
"type": "oauth2",
"flows": {
"password": {
"tokenUrl": "/oauth_token.do",
"refreshUrl": "/oauth_token.do",
"scopes": {
"useraccount": "utilize user account"
}
}
}
}
}
}
"security": [
{
"OAuth": ["useraccount"]
}
]
}
The endpoint for this API specifies that I should use x-www-form-urlencoded in the header as the Content-Type. When executing this request in Postman, it returns 200 with the desired response.
However, with https://editor.swagger.io I input the same postman request to get the fetch failed error with my Authorize button. To test for this, I created a custom path that specifies that the content should be x-www-form-urlencoded and this also fails.
So, what am I missing in this case? Any help would be appreciated.
I believe the issue was I did not fill out some portions I added on the response for path. Instead I opted to only leave description for the 200 response.
The main error I'm getting now is CORS related which is unrelated to the original question. I'll mark this answered for now.

Serilog not creating log file on production server

I've created a C# .net5.0 console application and during testing Serilog has been working without incident, logging to Console and File (same folder; path="log.txt"). However, when I run on the application on our server, neither Console nor File logging sinks are working! I assume now that the issue is not the sinks themselves but Serilog not actually working.
I've tried enabling the self log:
Serilog.Debugging.SelfLog.Enable(msg =>
Console.WriteLine(msg)
);
but even running in the debugger in my dev environment, the Console.WriteLine(msg) line is never called!
My appsettings.json is as follows:
{
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Information",
"System": "Information"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "log.txt",
"rollingInterval": "Infinite",
"outputTemplate": "{Timestamp:HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
"shared": false
}
}
],
"Enrich": [ "FromLogContext" ]
},
"Database": {
"Server": "(local)",
"Database": "ActivbaseLive"
},
"Email": {
"SmtpHost": "localhost",
"SmtpPort": 25,
"SmtpSecurityOption": "None",
"SmtpUsername": null,
"SmtpPassword": null,
"SmtpSender": "\"Activbase Learning Platform\" <noreply#activbase.net>"
}
}
I've tried absolute paths (using double backslashes in appsettings.json).
I've tried pre-creating the log file (e.g. log.txt and log200428.txt) and setting permissions to Everyone Full Control but neither of these changes fix the problem and they don't explain why the Console sink doesn't write either.
Here is how Serilog is being configured during start-up which is where I suspect the problem is (even through it works in dev environment):
return Host.CreateDefaultBuilder()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
})
.UseSerilog((hostContext, loggerConfiguration) =>
{
loggerConfiguration.ReadFrom.Configuration(hostContext.Configuration);
})
.ConfigureAppConfiguration((hostContext, builder) =>
{
builder.AddEnvironmentVariables();
})
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
...
});
}
Any ideas why Serilog isn't working in production?
The Path you provide should be absolute.
Some thing like this:
"path": "E:/wwwroot/QA/BackgroundWorkerService/Logs/logFile_.log"
Even I had the same issue, the above fix worked fine for me...
For my api application running in IIS: I had to assign the following permissions to the log folder for the IIS_IUSRS. I didn't need an absolute path!

The service configuration is `nil` when instantiating AWSLambdaInvoker on Swift

I'm trying to implement a lambda function with an iOS app. I follow all the steps on this tutorial form AWS: https://docs.aws.amazon.com/aws-mobile/latest/developerguide/how-to-ios-lambda.html.
But when I add the following line:
let lambdaInvoker = AWSLambdaInvoker.default()
it throws this error:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'The service configuration is `nil`. You need to configure `Info.plist` or set `defaultServiceConfiguration` before using this method.'
I added the awsconfiguration.json file to the project with this content:
{
"Version": "1.0",
"CredentialsProvider": {
"CognitoIdentity": {
"Default": {
"PoolId": "us-east-1:05aab771-99b5-4a9b-8448-de92fe86ba56",
"Region": "us-east-1"
}
}
},
"IdentityManager" : {
"Default" : {
}
}
}
The app runs well importing AWSLambda and the mobileClient, and I'm able to validate credentials with Cognito (I get the "welcome to AWS" message)
Any ideas??
You will have to update your awsconfiguraiton.json file to have information about LambdaInvoker so that it can load the configuration for default service configuration. Your updated file should look like:
{
"Version": "1.0",
"CredentialsProvider": {
"CognitoIdentity": {
"Default": {
"PoolId": "us-east-1:05aab771-99b5-4a9b-8448-de92fe86ba56",
"Region": "us-east-1"
}
}
},
"IdentityManager" : {
"Default" : {
}
},
"LambdaInvoker" : {
"Default" : {
"Region": "us-east-1"
}
}
}

graphql-ruby: Int isn't a defined input type (on $first)

I’ve got a question I can’t seemingly resolve on my own.
Together with basic Query, Mutation and so on types I’ve made the following type definition:
module Types
UserType = GraphQL::ObjectType.define do
name 'User'
description 'A user'
implements GraphQL::Relay::Node.interface
global_id_field :id
field :email, !types.String, 'Email address'
connection :docs, DocType.connection_type, 'Available docs'
end
end
And I then try to query it with:
query FileListQuery(
$after: String
$first: Int
) {
viewer {
currentUser {
docs(first: $first, after: $after) {
edges {
node {
id
name
__typename
}
cursor
}
pageInfo {
endCursor
hasNextPage
hasPreviousPage
startCursor
}
}
id
}
id
}
}
And I pass the following as query variables:
{
"first": 1,
"after": null
}
The problem is it bails out with the following:
{
"errors": [
{
"message": "Int isn't a defined input type (on $first)",
"locations": [
{
"line": 3,
"column": 3
}
],
"fields": [
"query FileListQuery"
]
}
]
}
I honestly have no clue why it complains about the Int type…
If I get rid of the problematic $first query variable in the request, it works fine.
This:
query FileListQuery(
$after: String
) {
viewer {
currentUser {
docs(first: 10, after: $after) {
edges {
node {
id
name
__typename
}
cursor
}
pageInfo {
endCursor
hasNextPage
hasPreviousPage
startCursor
}
}
id
}
id
}
}
Produces this:
{
"data": {
"viewer": {
"currentUser": {
"docs": {
"edges": [
{
"node": {
"id": "1",
"name": "First Doc",
"__typename": "Doc"
},
"cursor": "MQ=="
}
],
"pageInfo": {
"endCursor": "MQ==",
"hasNextPage": false,
"hasPreviousPage": false,
"startCursor": "MQ=="
}
},
"id": "1"
},
"id": "VIEWER"
}
}
}
Any hints, ideas on how to fix this? I use the graphql gem v1.6.3.
Currently, there seems to be a bug in graphql-ruby that prevents types not explicitly used in a schema from being propagated. Check out this issue on GitHub: https://github.com/rmosolgo/graphql-ruby/issues/788#issuecomment-308996229
To fix the error one has to include an Int field somewhere in the schema. Turns out I haven't had one. Yikes.
This fixed it for me:
# Make sure Int is included in the schema:
field :testInt, types.Int

Serilog Exceptionless Sink in .NET Core 1.1

How can the Serilog Exceptionless Sink be used with .NET Core 1.1?
The Serilog.Sinks.Exceptionless README isn't clear and doesn't work for .NET Core 1.1 where I have put the configuration in the appsettings.json file.
{
"Serilog": {
"Using": ["Serilog.Sinks.Literate"],
"MinimumLevel": ["Debug"],
"WriteTo": [{
"Name": "LiterateConsole"
}],
"Enrich": ["FromLogContext"],
"Properties": {
"Application": "MyAppServer"
}
}
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger();
}
}
I obviously need to set up the API key somewhere, too.
Can anyone provide a clear description of how this can be configured, please?
In JSON you can add additional sinks to the "WriteTo" list and add arguments like apiKey in the "Args" block:
{
"Serilog": {
"Using": ["Serilog.Sinks.Literate"],
"MinimumLevel": ["Debug"],
"WriteTo": [{
"Name": "LiterateConsole"
}, {
"Name": "Exceptionless",
"Args": { apiKey: "12345" }
}],
"Enrich": ["FromLogContext"],
"Properties": {
"Application": "MyAppServer"
}
}
}
I think it's
Log.Logger = new LoggerConfiguration()
.WriteTo.Exceptionless(
apiKey: "yourApiKey",
additionalOperation: b => b.AddTags("ASP.NET Core Example Logger"))
.CreateLogger();

Resources