How to configure a C# program with a connection string in Visual Studio Code?
This is for .Net Core 2.2 using .Net Core SDK version 2.2.203 in Visual Studio Code 1.34.0
I have tried to add App.Config file to the project, but I'm not able to resolve this issue. Do let me know any solution to configure connection string.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Collections.Specialized;
using Dapper;
namespace Sample_Dapper
{
class Program
{
static void Main(string[] args)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
var SqlString = "SELECT TOP 100 [CustomerID],[CustomerFirstName],
[CustomerLastName],[IsActive] FROM [Customer]";
var ourCustomers = (List<Customer>)db.Query<Customer>(SqlString);
}
}
}
Install Microsoft.Extensions.Configuration.Json
Then add appsettings.json file to project and right click on file -properties and select copy to output as copy if newer
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
Console.WriteLine(configuration.GetConnectionString("Test"));
Console.WriteLine(configuration.GetSection("SampleObj:AnyPropName").Value);
sample appsetting.json file
{
"SampleObj": {
"AnyPropName" : "testProp"
} ,
"ConnectionStrings": {
"Test": "CONNECTION-STRING"
}
}
Your code has ConfigurationManager.ConnectionStrings to get the connection string. This code will not work in .NET Core 2.2 and later, because ConfigurationManager.ConnectionStrings is used to get connection strings in web.config for ASP.NET project and app.config for console and Winforms/WPF projects if your app is using .NET Framework.
In .NET Core 2.0 and later, most configuration is stored as JSON file, and by default the equivalent of web.config/app.config is appsettings.json file, and you can also have your own configuration file as well, because it is highly extensible.
The official .NET Core 2.0 (or later) documentation on how to manage configuration files is available at: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2
Related
I'm following the docs for Configuration in .Net, and having trouble getting it working with User Secrets in Visual Studio 2022 (.Net 6.0).
Thus far I've:
Installed Microsoft.Extensions.Configuration.UserSecrets, and Microsoft.Extensions.Hosting.
Confirmed that <UserSecretsId> was added to the .csproj file
Code
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
// Retrieve App Secrets
using IHost host = Host.CreateDefaultBuilder(args).Build();
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();
string secret = config.GetValue<string>("DUMMY_VALUE");
...
await host.RunAsync();
secrets.json (Opened by right-clicking the project and choosing 'Manage User Secrets')
{
"DUMMY_VALUE": "dummy-test-value"
}
In the above, secret is null. Based on this line from the docs, I thought the code above would create a default config capable of reading the secrets.json file.
It seems like the way this works has been updated since similar questions were asked and answered, like this one. I've also been referencing the docs on Secrets in ASP applications, but still having trouble spotting what I'm missing.
With help from this answer and the docs for AddUserSecrets, I have a working solution: construct a custom config object with the desired capability.
code
using Microsoft.Extensions.Configuration;
// Retrieve App Secrets
IConfiguration config = new ConfigurationBuilder()
.AddUserSecrets<SomeClass>()
.Build();
string secret = config.GetValue<string>("DUMMY_VALUE");
...
Here, SomeClass can be any class in the assembly. The in-IDE description for AddUserSecrets<T> says:
AddUserSecrets will search the assembly that contains class T for some instance of Microsoft.Configuration.UserSecrets.UserSecretsIdAttribute which specifies the user secrets ID.
After following the steps listed in the question, this code succeeds in reading the secrets.json file. This solution is hinted at in the docs on Secrets in ASP.NET Core applications.
As mentioned by Bellrampion, the steps described in the Configuration in .Net docs will only read the secrets.json file in the Development configuration - which I do not see as an option in Visual Studio 2022. Based on this, if you want to use User Secret management in a .Net Console application in VS 2022, you may need to construct the custom config object like above.
In Vistual Studio 2022:
Select a project that will use the secrets;
Open context menu, select Manage User Secrets:
Library “Microsoft.Extensions.Configuration” will be auto added;
A secrets.json file will be auto created: fill it with access token, etc.
{
"github": {
"accessToken": "xx"
}
}
use the following lines to fetch a secret in a class, e.g. Program.cs
using Microsoft.Extensions.Configuration;
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
IConfiguration configuration = configurationBuilder.AddUserSecrets<Program>().Build();
string githubToken = configuration.GetSection("github")["accessToken"];
I keep all the data related classes, interfaces, configurations, etc in a separate library project so it can easily be reused for any other project I need (API, WebAssembly, Mobile, Server Pages, etc..)
I have converted all the projects from the solution to .NET6. They all work and build, as the did before, except for the data library which is giving me the following error: Program using top-level statements must be an executable.
How do I write the new .NET 6 Program.cs file for a .NET 6 library?
The new Program.cs file that is not working:
using FlasherData.Context;
using FlasherData.Repositories;
using FlasherData.Repositories.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<FlasherContext>(options => options.UseSqlite(builder.Configuration.GetConnectionString("FlasherDb")));
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
var app = builder.Build();
app.Run();
The old .NET 5 Startup.cs file that worked:
using FlasherData.Context;
using FlasherData.Repositories;
using FlasherData.Repositories.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace FlasherData
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// SQLite connection and database context
services.AddDbContext<FlasherContext>(options => options.UseSqlite(Configuration.GetConnectionString("FlasherDb")));
// Dependency Injection
services.AddScoped<IUnitOfWork, UnitOfWork>();
}
}
}
The .NET 5 library did not have a Program.cs file as it was not needed in a .NET 5 library project.
This is a link to the entire solution: Flasher
The first example you show isn't library code, but the entry point of an application. Top-level-statements are internally transformed into the Main method of the assembly, it's really just a syntactical alternative. But a library must not have a Main method, and that's why you get the mentioned error.
Therefore, for a library, either just remove the startup code or (to get the equivalent behavior than before) change it back to what it was before. There's no need to use top-level-statements anywhere. When updating an application from .NET 5.0 to .NET 6.0, typically you don't have to change anything (except in the project files), because the existing code base is fully backwards compatible.
I have asp.net core library project.
I want to add connection string to it. I don't have startup class in this. Where I need to place connection string and how to fetch it?
In dotnet core you can manage configuration using json files, which is one in many ways to configure your application.
According to the dotnet core configuration documentation you can simply do (copied from link reference)
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
// Add NuGet <package id="Microsoft.Extensions.Configuration" and
// <package id="Microsoft.Extensions.Configuration.Json"
// .NET Framework 4.x use the following path:
//.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), #"..\.."))
public class Program
{
static public IConfigurationRoot Configuration { get; set; }
public static void Main(string[] args = null)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
Console.WriteLine($"option1 = {Configuration["option1"]}");
Console.WriteLine($"option2 = {Configuration["option2"]}");
Console.WriteLine(
$"option1 = {Configuration["subsection:suboption1"]}");
}
}
Then in your appsettings.json file you can add:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
}
And access it in code using Configuration.GetConnectionString("BloggingDatabase")
I can recommend also reading the dotnet core documentation regarding connection strings
EDIT: As the commentors mention on your post, don't add connection strings and config files to your library code - do this from your console application or the web application!
Additional forms of configuration for dotnet core includes user secrets, environment variables and perhaps XML files or other forms of storage, as pointed out in the comments
I am trying to serve static files in a ASP.NET 4.6 web application, MVC 5.2.3 using the Entity Framework. I'm following this tutorial.
I'm getting a compiler error:
The type or namespace name 'PhysicalFileProvider' could not be found
(are you missing a using directive or an assembly reference?)
It seems that the using Microsoft.Extensions.FileProviders is not actually being used (it is grayed out in Visual Studio.
I have tried importing various assemblies without any luck. I'm not a .NET developer and any help would be greatly appreciated.
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Primitives;
using Microsoft.Owin;
using Microsoft.Owin.StaticFiles;
using Microsoft.Extensions.Configuration;
using Owin;
[assembly: OwinStartup(typeof(Monica.Startup))]
namespace Monica
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseStaticFiles(); // For the wwwroot folder
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), #"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles")
});
}
}
}
You should install the nugget package:
Microsoft.Extensions.FileProviders.Physical
Right click the project -> Manage Nugget Packages -> Browse -> Microsoft.Extensions.FileProviders.Physical -> Install.
The using statement should be available to you afterwards.
I'm new in .Net and I'm now trying to write a plugin for windows live writer because I prefer to publish blogs using it rather than using the web editors. And I want to develop some small plugins for my daily use. But after I created a class libarary project and built it following the steps as some developers described, the WLW does not load the plugin so I don't know how to debug.
My Code:
using System;
using System.Collections.Generic;
using System.Text;
using WindowsLive.Writer.Api;
using System.Windows.Forms;
namespace Insert_Colorful_Table
{
[WriterPluginAttribute
("f7581112-dddd-47c9-9db0-46987a2aaae1",
"Insert Colorful Table",
Description = "Helps you create a beautiful table.",
ImagePath = "icon.gif",
PublisherUrl = "http://ggicci.blog.163.com")]
[InsertableContentSource("Insert Colorful Table")]
public class Plugin : ContentSource
{
public override DialogResult CreateContent
(IWin32Window dialogOwner, ref string content)
{
content = #"<table><tr><td>Ggicci</td></tr></table>";
return DialogResult.OK;
}
}
}
I did configure the 'Build Events' of the project and set the 'Build Action' of the image to 'Embedded Resource'. And no errors occured when building my project.
okay, I've worked out what went wrong. Windows Live Writer supports plugins that are built with either the Microsoft .NET Framework version 1.1 or 2.0. Writer requires users to have .NET 2.0 present to install the application. But I used .NET 4.0. So when I changed target framework to 2.0, then it worked well.