Configuration doesn't pick connection string from secrets.json file in ASP NET Core MVC 6.0 lts - asp.net-core-mvc

I created ASP NET Core MVC 6 lts app with individual user accounts with Visual Studio 2022 preview 6.0. I moved connection string from appsettings.json to secrets.json. I start the app with IIS Express and apply migrations from exception page that opens. It works.
But when I try to apply additional migrations from Package Manager Console I get an error "connectionString can't be null".
Add services to the container. This is from Program.cs:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
This is appsettings.json, connection string value removed:
"ConnectionStrings": {
"DefaultConnection": ""
},
This is Secrets.json:
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=DESKTOP-HIPPIDT;Initial Catalog=KehittajaLocalDb;Integrated Security=True;MultipleActiveResultSets=True"
}
}

In .NET 6,
You do not need to specify AddUserSecrets<>.
As mentioned here ,
WebApplication.CreateBuilder initializes a new instance of the
WebApplicationBuilder class with preconfigured defaults. The
initialized WebApplicationBuilder (builder) provides default
configuration and calls AddUserSecrets when the EnvironmentName is
Development
All you need to do is get the connection string from the builder.Configuration like below:
var dbConnectionString = builder.Configuration["ConnectionStrings:DevelopmentConnection"];
Then, you can specify the connection with AddDbContext<>:
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(dbConnectionString);
});

I added this to the Program.cs, now it works as expected. I don't know how come it worked when migrations were applied from exception page "Apply Migrations" button anyway.
// Add services to the container
if(builder.Enviroment.IsDevelopment())
{
builder.Configuration.AddUserSecrets<Program>();
}
..other code

Related

CS1022 : Type or namespace definition, or end-of-file expected for program.cs file in ASP.NET Core MVC project

Creating an ASP.NET Core MVC application in VS2022.
The build throws the error shown here, for program.cs file. But I'm not seeing any red indication in the class file.
This is the code of program.cs:
using Fluent.Infrastructure.FluentModel;
using System.Net;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
//var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
And I'm getting this error message on 'RUN'
Can anyone help me resolve this issue? I've been struggling with this error for a long time.
Please follow below steps, I think you could fix the issue.
1. Move you code here like the picture below.
2. Delete .vs, bin, obj folder.
3. Expand the Denpendencies to check the warning.

Setting connecting string in Blazor Telerik Report Viewer

I know this should be easier than this, I was reading the Telerik Documentation since hours but without solution.
I have Blazor Server Side project.
I added Telerik Report Viewer.
<ReportViewer ViewerId="rv1"
ServiceUrl="/api/reportdesigner"
ReportSource="#Source"
Parameters="#ParametersOptions"
ScaleMode="#(ScaleMode.Specific)"
Scale="1.0" />
and here is the data that I am binding to from the component
private ReportSourceOptions Source => new()
{
Report = SelectedReport?.Name ?? string.Empty,
Parameters = new Dictionary<string, object>()
{
{ "ConnectionString" , "TelerikConnectionString" }
}
};
private readonly ParametersOptions ParametersOptions = new()
{
Editors = new EditorsOptions
{
MultiSelect = EditorType.ComboBox,
SingleSelect = EditorType.ComboBox,
}
};
The component show in the page, but it complains about the connection string,
which I am struggling to figure out to set
here is the error message
Unable to get report parameters. An error has occurred. Unable to establish a connection to the database. Please verify that your connection string is valid. In case you use a named connection string from the application configuration file, make sure the name is correct and the connection string settings are present in the configuration file of your application.
I added the connection string in the C:\Users\USERNAME\AppData\Roaming\Telerik Reporting\WebReportDesignerSettings.json
{
"ConnectionStrings": [
{
"name": "TelerikConnectionString",
"connectionString": "Server=.\\;Initial Catalog=AdventureWorks;Integrated Security=true",
"providerName": "System.Data.SqlClient"
}
]
}
The json file should be present in your Blazor application. You can have a look at the example Blazor projects that come with your installation, located at (Replace R3 2022 with your release version):
C:\Program Files (x86)\Progress\Telerik Reporting R3 2022\Examples\CSharp\.NET 7\BlazorIntegrationDemo
You can specify your connection string in appsettings.json file
"ConnectionStrings": {
"Telerik.Reporting.Examples.CSharp.Properties.Settings.TelerikConnectionString": {
"connectionString": "Data Source=.\\;Initial Catalog=AdventureWorks;Integrated Security=SSPI",
"providerName": "System.Data.SqlClient"
}
You may need to set its Build Action to Content and Copy if Newer.

Open Api 3.0 Swagger application with Visual Studio 19 - database connection problem

I have to make application for .NET5.0. (Core). I have installed packages Devart.Data (5.0.2658) and Devart.Data.Oracle(9.14.1234).
I use 32 bits oracle client in my computer.
I have switched my application to x86 mode.
I need to connect to a Oracle 12 server.
Here is my code:
[Route("GetMyData")]
[HttpGet]
public List<Cis_titul_pred> GetCiselnik()
{
List<DataModule.BO.Cis_titul_pred> testlist =
DataModule.DAL.Cis_titul_predDB.Instance.GetList();
return testlist;
}
public List<Cis_titul_pred> GetList()
{
List<Cis_titul_pred> cis_titul_predList = null;
using (OracleConnection oraConnect = new OracleConnection(AppConfig.ConnectionString))
{
OracleCommand oraCommand = new OracleCommand(selectList, oraConnect);
oraCommand.CommandType = CommandType.Text;
oraConnect.Open();
using (OracleDataReader oraReader = oraCommand.ExecuteReader())
{
if (oraReader.HasRows)
{
cis_titul_predList = new List<Cis_titul_pred>();
while (oraReader.Read())
{
cis_titul_predList.Add(FillCis_titul_pred(oraReader));
}
}
oraReader.Close();
}
oraConnect.Close();
}
return cis_titul_predList;
}
When I created .NET5.0 Desktop (WinForms) application , everything worked properly - I could connect to Oracle server and read data.
When I created .NET5.0 WEB application , everything worked properly - I could connect to Oracle server and read data.
When I created .NET5.0 OpenApi application , I got error message "Devart.Data.Oracle.OracleException (0x80004005): Server did not respond within the specified timeout interval
at Devart.Data.Oracle.dp.a(cj A_0, di A_1)
at Devart.Data.Oracle.OracleInternalConnection..ctor(cj connectionOptions, OracleInternalConnection proxyConnection)
at Devart.Data.Oracle.ci.a(ae A_0, Object A_1, DbConnectionBase A_2) Etc. ... Etc..."
I use the same code to connect to the Oracle server in all three applications
I tried change target framewor to NET.Core 3.0, or NET.Cre 3.1, but without success.
Any ideas?
What can I do?
What do you mean by .NET5.0 OpenApi application? It's the same architecture with .net5 web... Please check If you have a correct and same connection string in your appSettings.json file. Also consider using dependancy injection instead of creating OracleConnection instance inside controllers

display build version on web page

I am developing a web site using asp.net core.
And I publish it with Visual Studio or/and VSTS.
I want to display some information about which build it is on the web page.
(something like rev 2016.9.20.4002)
How can I do that?
You can track it with build number.
Go to your VSTS site and create build definition
Select General tab, specify build number format, for example: $(date:yyyyMMdd)$(rev:.r)
(Optional) Select Triggers tab, check Continuous integration (CI) and configure filters if you want queue build for each check-in.
Configure other settings (e.g. steps/task in Build tab)
After build complete, go to the summary of that build definition (click build definition title hyperlink to go to summary page), the result will be like this:
Steps to display build number to your website:
Install Replace Tokens extension to you VSTS
Edit your build definition to add Replace token task
Specify target files and root directory (for asp.net core app, you can specify **\appsettings.json)
Select Variable tab and add a new variable. Save your build definition
Edit appsettings.json file of your asp.net project. Sample code:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-ab933d83-8f4b-4024-9f3c-1aef5339a8f3;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"CodeVersion": {
"Num": "#{MyBuildNumber}#"
}
}
Add logical to your asp.net project to read appsettings.json to get specific value and display in the page.
Check in your code and queue build.
After a day of research, finally found/created a better option than using any random app (Replace Token) from Marketplace.
The option I am talking is already available in VSTS, Azure CLI task.
Here are the stpes:
Add setting BUILD_NUMBER with initial value of 1.0 in appsettings.json
Read appsettings.json in your app and display it. I am sure you all are smart enough to figure out how to use appsettings to display Build Number on your WebApplication.
In Azure Portal, similarly create an App Setting named BUILD_NUMBER with initial value of 1.0 in Azure Application settings section under App Services for your App.
In VSTS, In your Release definition, add a task Azure CLI.
Populate required fields such as Azure Subscription, Script Location with Inline script and last but most important Inline Script with following CLI command
az webapp config appsettings set -n iCoreTestApi -g ArchitectsSandbox -s Dev --settings BUILD_NUMBER=$(Build.BuildNumber)
Command explanation:
iCoreTestApi should be replaced by your real WebApp or Api name in Azure
ArchitectsSandbox should be replaced by your resource group in Azure
Dev is the slot name, you may or may not have it.
Rest of the command remains same.
Once you will queue new build, after successful completion of the deployment, you can see app settings section on Azure is updated with new BUILD_NUMBER.
Let me know if you still have any question.
Do you mean something like this:
In project.json:
{
"title": "Your Application name",
"version": "2016.9.20.4002",
"copyright": "Your Company 2016",
"description": "Awesome ASP.Net Core Application",
"dependencies": {
//rest of project.json
You can then create a property in your view model or model such as:
public static string Version
{
get
{
var assembly = Assembly.GetExecutingAssembly();
var fileVersion = GetCustomAttribute<AssemblyFileVersionAttribute>(assembly);
return fileVersion?.Version;
}
}
In your view:
#model Namespace.CustomViewModel
<!--Other HTML Code-->
<span id="applicationVersion">#CustomViewModel.Version</span>
Looks like ApplicationEnvironment class is what you need:
var appEnv = new Microsoft.Extensions.PlatformAbstractions.ApplicationEnvironment();
string version = appEnv.ApplicationVersion;
Also
How can I auto-increment an MVC 6 version number? may be also interesting to you, but keep in mind, that IApplicationEnvironment has been removed.
Just as an alternative option, you could read the time that the assembly was created and display it in a version format. Every time the assembly is rebuilt, this value would change to the time it was created.
(adapted from this answer for .Net Core)
public static class AppInfo
{
private static Lazy<string> buildVersion =
new Lazy<string>(() => GetBuildVersion(Assembly.GetEntryAssembly()));
public static string BuildVersion { get; } = buildVersion.Value;
private static string GetBuildVersion(Assembly assembly)
{
var filePath = assembly.Location;
const int c_PeHeaderOffset = 60;
const int c_LinkerTimestampOffset = 8;
var buffer = new byte[2048];
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
stream.Read(buffer, 0, 2048);
var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset);
var secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset);
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var linkTimeUtc = epoch.AddSeconds(secondsSince1970);
var localTime = TimeZoneInfo.ConvertTime(linkTimeUtc, TimeZoneInfo.Local);
var minutesFromMidnight = localTime.Minute + localTime.Hour * 60;
return localTime.ToString("yyyy.M.dd.") + minutesFromMidnight;
}
}
Then just reference it in Razor as:
#AppInfo.BuildVersion
It may be not exactly what requested but was quite efficient in my situation. If docker is used to build and deploy web apps, consider adding this step to your CI build script before docker build command (bash):
echo ENV BUILD_NUMBER=$(Build.BuildNumber) >> Dockerfile
In the app code just use BUILD_NUMBER environment variable.
The advantage of this method is that build number value becomes metadata of the docker image just like labels but you can also access it from the inside your app.

Can't get ASP.NET Web API 2 Help pages working when using Owin

I've installed the correct package for Web Api 2
Install-Package Microsoft.AspNet.WebApi.HelpPage -Pre
But the help area is not being mapped and is returning 404 (Web Api working fine). I'm using Microsoft.Owin.Host.SystemWeb as the host. Below is my Startup code.
public class Startup
{
public void Configuration(IAppBuilder app)
{
//Required for MVC areas new HttpConfiguration() doesn't work with MVC
var config = GlobalConfiguration.Configuration;
AreaRegistration.RegisterAllAreas();
WepApiStartup.Configure(config);
app.UseWebApi(config);
}
}
GlobalConfiguration.Configuration is web host specific HttpConfiguraiton, which should only be used with web host scenario. Use it with OWIN host will cause unexpected issues.
Please use the following code instead:
public class Startup
{
public static HttpConfiguration HttpConfiguration { get; private set; }
public void Configuration(IAppBuilder app)
{
HttpConfiguration = new HttpConfiguration();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(HttpConfiguration);
app.UseWebApi(HttpConfiguration);
}
}
Replace all GlobalConfiguration.Configuration with Startup.HttpConfiguration in the project include help page files.
Found the solution after a lot of digging/trial and error. The issue is well described here: http://aspnetwebstack.codeplex.com/discussions/453068
UseWebApi and UseHttpMessageHandler don't call Next OWIN's middleware other than for 404. This means if you use UseWebApi that's it, Next is never called therefore you can't use it with any other middleware (Nancy or Web Api Help pages for example).
Thanks to #aliostad patch:
https://github.com/aliostad/CacheCow/blob/master/samples/UsingCacheCowWithNancyAndOwin/HttpMessageHandlerAdapterModified.cs#L43
You can get it working as expected. I hope the team merge the pull request for this as UseWebApi breaks the Owin design goals IMO.
Update 13 Feb 2014
I've written an Owin extension to workaround this:
internal static void UseWebApiAndHelp(this IAppBuilder app, HttpConfiguration config)
{
WepApiStartup.Configure(config);
app.UseHandlerAsync((request, response, next) =>
{
if (request.Path == "/") //app.Map using a regex exclude list would be better here so it doesn't fire for every request
{
response.StatusCode = 301;
response.SetHeader("Location", "/Help");
return Task.FromResult(0);
}
return next();
});
// Map the help path and force next to be invoked
app.Map("/help", appbuilder => appbuilder.UseHandlerAsync((request, response, next) => next()));
app.UseWebApi(config);
}
Update 01 July 2015
You can also host the help pages using WebApi instead of MVC, which is great for self host http://blogs.msdn.com/b/yaohuang1/archive/2012/12/20/making-asp-net-web-api-help-page-work-on-self-hosted-services.aspx
Update 10 September 2015
For Web Api I tried #hongye-sun answer and it works too, follow what #gspatel says by changing HelpPageAreaRegistration.RegisterArea and the HelpController's constructor. My workaround works as well so pick whatever one works best for your situation.
However I'm still getting the issue when using UseWebApi with other middleware and it not invoking Next() (seems to only happen when using IIS not self host). I've found my workaround of mapping the path and forcing next to be invoked is a valid workaround for all Owin middleware Nancy, Simple.Web etc.
Update 13 Jan 2016
I've developed Owin middleware to generate the ASP.NET Web API Help pages we know and love that completely solves this problem. My blog post explains the background to this issue in detail

Resources