Does a mvc6 service provides project.json data? - service

I am using asp.net 5 with mvc6, and I extended the project.json with several stuffs.
I am currently reading the project.json by parsing it myself. But I was wondering whether a service or a context exists within mvc6 already providing parsed data of project.json file.

There's no service, you have to parse it yourself

Why are you parsing manually project.json? Don't do that. If you wan't to have custom configuration settings then create new file or use one of existing ones (for example appsettings.json). Then in Startup.cs simply add that file and it will be available in the Configuration object:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
...
Configuration = builder.Build();
}

Related

Failed initial migration in Entity Framework Core on .NET 6 Isolated [duplicate]

.NET6 EFCore & Cosmos Migration issue. Need some help.
Hello folks. I am new in the world of .Net and I am facing an issue that Google has failed to help me solve. You're kind of my last regard.
So. I am trying to connect to an Azure Cosmos DB from my little HomeControlCenter Project using EFCore 6.0.3
The Error:
Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Migrations.IMigrator'. This is often because no database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext>
object in its constructor and passes it to the base constructor for DbContext.
My Program.cs:
builder.Services.AddDbContext<ControlCenterContext>(options =>
options.UseCosmos(builder.Configuration.GetConnectionString("DefaultConnection"), "ToDoList"));
My DbContext Impl:
public class ControlCenterContext : DbContext
{
public ControlCenterContext(DbContextOptions<ControlCenterContext> options) : base(options)
{
}
}
I also tried to use an override of OnConfiguring instead of the Program.cs line.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseCosmos(
"<AccountEndpoint>",
"<accountKey>",
databaseName: "ToDoList");
Nothing helped. When ever I run dotnet ef migrations add "initialSetup" I get the error mentioned above.
I read the error carefully and as you can see, I did apply all the necessary constructor params & other additions... I even tried to create a vanilla project and do the same all over again...
I couldn't find anything official from Microsoft, but the author of this blog states migrations using EF Core for CosmosDb are not supported: https://www.thereformedprogrammer.net/an-in-depth-study-of-cosmos-db-and-ef-core-3-0-database-provider/#1-no-migrations-can-cause-problems
This makes sense since CosmosDB is a document database, so it has no schema, it's just a bunch of JSON files. I ran into this issue when I wanted to use migrations to make seed data. The only solution I could think of was to create a separate project that uploaded the seed data with static values. But again, this was only seed data and not schema updates.

.net core not connecting to the changed database in appsettings.json connectionstrings in visual studio debug

I am working on a .net core project, I wanted to change the connectionstring of the database in appsettings.json.
I had created a duplicate database and named it originalname_fake01 and made a clone of the original database for testing.
I have also changed the database name in appsettings.developement.json. Everything seems fine but when I run the application in debug mode in visual studio. the data was being pulled from the original database rather than the changed database name in appsettings.json.
Here is my appsettings connectionstrings code:
Old connectionstring was
"connectionStrings": {
"MyConnectionString":
"Server=localhost;port=3306;database=mydb;user=root;password=rt123;"
}
changed connection string (new)
"connectionStrings": {
"FakeConnectionString":
"Server=localhost;port=3306;database=mydb_fake01;user=root;password=rt123;"
}
I am not able to understand why it is connecting to the old database rather than the new database even after changing the connectionstring.
Any help would be appreciated.
If you want the development settings to override the production settings you need to use the same names and full path. Your connection string should be named MyConnectionString, not MyConnectionString if you want the DbContext to pick it automatically.
JSON setting files have no special meaning in .NET Core, they are just files. Every provider produces key/value pairs in the form Section1:Subsection1:Attribute1, Value. Newer provider values override earlier values. Providers can be JSON or XML file readers, INI file readers, databases etc. In all cases, the settings are flattened to path/value pairs.
The file
"connectionStrings": {
"MyConnectionString": "Server=localhost;port=3306;database=mydb;user=root;password=rt123;"
}
Produces a value named connectionStrings:MyConnectionString whose value is Server=localhost;port=3306;database=mydb;user=root;password=rt123;. To override this you need to specify a setting with the same path.
The default Host builder specifies some default settings providers. From the docs, those are :
appsettings.json.
appsettings.{Environment}.json.
= Secret Manager when the app runs in the Development environment.
Environment variables.
Command-line arguments.
Settings specified lower down the list override previous ones. This means that on a development machine, the connectionStrings:MyConnectionString in appsettings.Developoment.json overrides the element with the same name in appsettings.json.
This also means that we can override the connection string with an environment variabl or a command-line argument, eg
dotnet run /connectionStrings:MyConnectionString Server=localhost;port=3306;database=mydb;user=root;password=rt123;
I have finally able to find the problem in the dbcontext.cs modelbuilder. There is a code line which has strongly typed Schema Name.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
OnModelCreatingImpl(modelBuilder);
modelBuilder.HasDefaultSchema("MyDB");
}
I changed it use the new schema as below:
modelBuilder.HasDefaultSchema("MyDB_Fake01");
I don't understand why we need to give schema name in both connectionstring and in modelbuilder. I Guess we should avoid explicit schema name targeting in ModelBuilder so that, whenever the connectionstring is changed. it will target the database correctly.
Anyways, the problem is solved as the application is connecting to the intended database.
You are almost there. In your changed connection string (new) setting, change the FakeConnectionString to MyConnectionString. If you have same keys in appsettings.json and in appsettings.development.json then latter will override the former.
"connectionStrings": {
"MyConnectionString": "Server=localhost;port=3306;database=mydb_fake01;user=root;password=rt123;"
}
P.S. This is applicable to any environment not only to development
There is also a file named "secrets.json" which overrides all other appSettings configuration. Make sure it has correct Database name.
The file named "secrets.json" worked for me as the default connection string was hardcoded there pointing to the old database. Editing the connection string (Initial Catalog=dbName) to point to the current database name fixed the problem. Thanks!
sample content of "secrets.jason":
{
"ConnectionStrings:DefaultConnection": "Data Source=TestSource;Initial Catalog=dbName;Integrated Security=True;MultipleActiveResultSets=True"
}

Spring Boot Starter Data Rest change URL of repository from the root URI

Following the spring.io example here: http://spring.io/guides/gs/accessing-data-rest/ for exposing a repository as a rest web service works just fine, but I cannot see how to change the URL of the exposed service. The API documentation is a little vague as to what the annotation parameters mean, perhaps some prior knowledge is assumed.
What I want - A HATEOAS service accessed at http://localhost:8080/api/people for a People repository. I want to achieve this URL using annotations only, not messing with the context root or similar. I tried the following repository annotations:
#RepositoryRestResource(collectionResourceRel = "api/people", path = "people")
#RepositoryRestResource(collectionResourceRel = "people", path = "api/people")
#RepositoryRestResource(collectionResourceRel = "api/people", path = "api/people")
None of these work.
I know I have probably missed the obvious, much appreciate anyone who can point it out.
As of Spring Boot 1.2 you are able to set this property:
spring.data.rest.baseUri=api
Alternatively:
spring.data.rest.base-uri=api
(Spring Boot uses a relaxed binding system)
NOTE: I have found that if you have extended RepositoryRestMvcConfiguration with custom configuration, the property does not take effect. For more information see:
https://github.com/spring-projects/spring-boot/issues/2392
Once the next version of Spring Boot is released (after 1.2.1), the solution will be to extend RepositoryRestMvcBootConfiguration instead.
As of Spring Boot 1.4.3 the code should be :
spring.data.rest.base-path:api
(I think baseUri is deprecated since 1.2.3)
Although I couldn't change the base path of the REST services using the annotation #RepositoryRestResource combined with a CrudRepository, I managed to do it using a JpaRepository and a custom controller with the annotation #RequestMapping.
The repository could be something like:
#Repository
interface PersonRepository : JpaRepository<Person, Long>
And the controller:
#RestController
#RequestMapping("/api/people")
class PersonRestController(private val personRepository: PersonRepository) {
...
On the other hand, you can change the base path of all your REST services modifying it in the application.properties file of your project. Add the lines:
# DATA REST (RepositoryRestConfiguration)
spring.data.rest.base-path = api
Change api with the path you wish you use in your URLs. The first line is a comment and, as so, it's not mandatory, but is useful to mark the nature of the configuration value for future references.
You can find all the common application properties of Spring Boot 2.0.1 in the Appendix A of the documentation.

Need ServiceConfiguration.cscfg to populate web.config sessionstate and connection strings

I need to propagate connection string changes for entity framework, asp.net membership (which are both in the connectionstrings section of web.config) and session state (which is in sessonstate's sqlconnectionstring) in web.config when I adjust these settings in windows azure's service configuration.
During development we test our app as a standard asp.net webforms app, but once it is deployed it is running in azure. So we need to allow for the site running in both non-azure and an azure context. That's why we're just relying upon the values in web.config for now.Since these connection strings are not called directly in my code writing a utility class which grabs from azure service config if that is available or otherwise grabs from web.config is not a possibility for these values.
I realize that editing web.config would cause a disruption in service - and i only plan to do this during off hours.
I believe that the best approach is to wrap your configuration information in a service. Then, in the service, use RoleEnvironment to determine which settings to use. For example
public static class Config
{
public static string ConnStr
{
get
{
if (RoleEnvironment.IsAvailable)
return RoleEnvironment.GetConfigurationSettingValue("ConnStr");
return ConfigurationManager.AppSettings["ConnStr"];
}
}
}
If that doesn't work, and you need to change the actual web.config (for instance, using named connection strings), then you'll need to modify the config at runtime. In your role start, do something like the following:
var config = WebConfigurationManager.OpenWebConfiguration(null);
var connStrs = WebConfigurationManager.OpenWebConfiguration(null).GetSection("connectionStrings") as ConnectionStringsSection;
connStrs.ConnectionStrings["ConnStr"].ConnectionString = RoleEnvironment.GetConfigurationSettingValue("ConnStr");
config.Save();
To handle when the configuration changes after the role is running, just call the same code as above from the RoleEnvironment.Changing event.
Good luck,
Erick

WCF Web API Configuration File to IIS

I have implemented a restful service with WCF Web API and I want to publish it in IIS.
During developing process I was using the service as Console Application and all configuration was made through API.
Now I'm trying to publish the service as ASP.NET application and the only way I see is somehow to move all configuration into web config file.
Here the coded configuration:
var cfg = HttpHostConfiguration.Create()
.AddMessageHandlers(typeof(AllowCrossDomainRequestHandler));
using (var host = new HttpConfigurableServiceHost(typeof(RESTfulService), cfg , new Uri("http://localhost:8081")))
{
var endpoint = ((HttpEndpoint)host.Description.Endpoints[0]); //Assuming one endpoint
endpoint.TransferMode = TransferMode.Streamed;
endpoint.MaxReceivedMessageSize = 1024 * 1024 * 10; // Allow files up to 10MB
host.Open();
Console.WriteLine("Host opened at {0} , press any key to end", host.Description.Endpoints[0].Address);
Console.ReadKey();
}
How should my web.config look to reflect this configuration?
Or is there any other approach instead of using ASP.NET?
Any help is appreciated.
If you want to preserve your existing config, you can put all your config set up stuff into a method, and call it from global.asax Application_Start() method. All the Global.asax methods will get called in WCF the same as they do for ASP.NET.
Or, you can wire your services to a custom ServiceHostFactory and ServiceHost that has all the configuration in it (this is the approach I am using in my current app).