I am trying to setup my uni work (which is windows based) onto my mac. I have a docker container running with AzureSQLEdge, which I have connected to my Azure Data Studio and can run queries no problem. However in VS2022 trying to set up the connection to the database in Azure Data Studio.
At the moment I am just trying to get some IDs printed to the page (we are using #razor)
#using WebMatrix.Data
#{
ViewBag.Title = "About Us";
var db = Database.Open("AmazonOrders");
var select = "SELECT * FROM Customers";
var data = db.Query(select);
}
<h2 class="text-center">#ViewBag.Title</h2>
<h3>#ViewBag.Message</h3>
<p>Use this area to provide additional information</p>
#foreach (var row in data)
{
#row.customerID
}
My connection string in appsettings.json is:
"AllowedHosts": "*",
"ConnectionStrings": {
"AmazonOrders": "Server=tcp:127.0.0.1,1433;Database=AmazonOrders;User=sa;Password=SQLserver123!;"
}
However I am getting this error message when I load the page:
InvalidOperationException: Connection string "AmazonOrders" was not found.
Setting up the connection string is all the windows users have to do, they have a local version of the database in their project solution. Any help is appreciated, the resources online are more about creating db contexts which I would prefer to avoid if possible, and just connect directly to my database on docker/azure data studio.
edit
Here is the full appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"AmazonOrders": "Server=tcp:127.0.0.1,1433;Database=AmazonOrders;User=sa;Password=SQLserver123!;"
}
}
#using WebMatrix.Data
This is an old data access library intended solely for use with ASP.NET Web Pages, which is a pretty ancient (and virtually obsoleted) web development framework that targets the full .NET Framework. As such, it knows nothing about appsettings.json files which were introduced in .NET COre. The primary configuration mechanism for Web Pages is a web.config file and that's where this library looks for a connection string.
If I were you, I would remove WebMatrix.Data from your project (assuming it is actually a Razor Pages app, not Web Pages) and use Entity Framework Core instead. If it is a Web Pages app and that's the framework you want to work with, remove the appsettings.json file and add a connection string to the web.config file: https://www.connectionstrings.com/store-connection-string-in-webconfig/
Related
As the title says, I am trying to use dotnet ef database update from the command line and getting the error Format of the initialization string does not conform to specification starting at index 0.
From searching around this site and the internet, everything points to the connection string being wrong, but the connection string is working fine to compile and run the application. I am trying to add Identity to the project so I can have users with passwords, and am trying to follow the Deep Dive tutorial on pluralsight, but when it gets to this part, the code fails.
My connection string in appsettings.json is
"ConnectionStrings": {
"DefaultConnection": "Server=PTI-VWS12-002;Database=EPDM_TestVault;Trusted_Connection=true;MultipleActiveResultSets=true;"
},
The code in my Startup.cs is:
var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), sql=> sql.MigrationsAssembly(migrationAssembly)));
though i've also tried it without the migration assembly as well. I'm really not sure what could be wrong with my connection string.
EDIT: My constructor:
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) { Configuration = configuration; }
And my constructor has the default for ASP.NET CORE 2.1
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>();
EDIT 2: Solved.
I'm still not sure what I did wrong in my project, but i got the Identity tables to generate using the official Asp.NET sample project library over here https://github.com/aspnet/Docs. Using the exact migration file from the IdentityDemo, and plopping in my connection string from above, I was able to create the Identity tables in my database.
You first need to configure IConfiguration using IConfigurationBuilder in Constructor of startup or in Program.cs before Kestrel Server startup.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
_configuration = builder.Build();
I'm still not sure what I did wrong in my project, but i got the Identity tables to generate using the official Asp.NET sample project library over here https://github.com/aspnet/Docs. Using the exact migration file from the IdentityDemo, and plopping in my connection string from above, I was able to create the Identity tables in my database.
EDIT: it still doesn't run in context of my program.
I am using serilog as logging framework in .net core 2.0 project and i am trying to store the logs in sql server but serilog is not storing any data in database and it is not even returning error.
can any one help how to resolve this issue and is it possible to add file approach to store logs when database fails to store
Serilog.Debugging.SelfLog
You can use the SelfLog property to tell serilog where to log it's own errors (all of us have had to debug the logger at some point).
Sample Code
Because I hate providing an answer without sample code that others might find useful ... here is the code we use to "initialize" our logger (including serilog and seq -- a great combo for generating centralized logs that the devops team can monitor).
Serilog.Debugging.SelfLog.Enable(Console.Error);
ILoggerFactory factory = new LoggerFactory();
factory.AddConsole();
factory.AddDebug();
var env = "PROD"; //MyEnvironment: PROD, STAGE, DEV, ETC
var seqLogger = new LoggerConfiguration()
.MinimumLevel.Information()
.Enrich.FromLogContext()
.Enrich.WithProperty("Environment", env)
.WriteTo.Seq(
"logserveraddress",
Serilog.Events.LogEventLevel.Verbose,
1000,
null,
"LogServerApiKey")
);
if (env.ToLower() == "prod") { seqLogger.MinimumLevel.Warning(); }
factory.AddSerilog(seqLogger.CreateLogger());
}
return factory.CreateLogger("NameThisLogInstaceSomethingUseful");
Good day!
I am new to asp.net core web api and I am trying to connect it to my local SQL Server DB. However, I am receiving an error on my Startup.cs file :
"IServiceCollection does not contain a definition for AddDBContext".
Am I doing it right?
Here is my code in Startup.cs - ConfigureServices :
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddCors();
services.AddDbContext<MonsterContext>(options =>
{
options.UseSqlServer("MyLocalDB");
});
}
Also, here is my code in appsettings.json :
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"MyLocalDB": "Server=.\\SQLEXPRESS;Database=Inventory;User Id=sa;Password=Passw0rd;MultipleActiveResultSets=True;",
}
}
Here is the screen shot for my SQL Server Local DB :
I really don't know if I have not yet installed a Nuget package, or is there something missing in my code? I searched many times in google but unfortunately I am still receiving the error :( I will gladly appreciate any help / suggestions. Thank you very much and have a nice day guys!
You need to add (at least) Microsoft.Extensions.DependencyInjection NuGet PAckage to your project, wich is part of Microsoft.AspNetCore.Mvc 2.0 already, probably this will fix your issue.
I said at least because you should also add the EntityFramework package.
I hope it helps,
Juan
I'm trying to create a simple backend for a html/JavaScript app. I started off by creating a new visual Studio Project using the azure mobile Service template. I created a simple DataObject class called 'ProjectItem' which is looking like this:
public class ProjectItem : Microsoft.WindowsAzure.Mobile.Service.EntityData
{
public string Title { get; set; }
public string Description { get; set; }
}
After that I added a table Controller and there was no need to touch any Code in that class.
In the web api config I added this peace of Code:
List<ProjectItem> projectItems = new List<ProjectItem>
{
new ProjectItem {Id = Guid.NewGuid().ToString(), Title = "First Project", Description = "My First Project Description" },
new ProjectItem {Id = Guid.NewGuid().ToString(), Title = "Second Project", Description = "My Second Project Description" }
};
foreach (ProjectItem projectItem in projectItems)
{
context.Set<ProjectItem>().Add(projectItem);
}
I debugged the Service on my localhost and it was working just fine.
Now I wanted to host it on azure and there the Problems started for me.
Here the stepps I did using azure:
I created an empty database on the new Portal
In visual Studio I clicked publish (my solution) and created a new mobile Service selecting the empty database - I didn't touch the rest of the Settings. The mobile Service is now "up and running".
I only have worked with sqlite since now so I opened the database in visual Studio and wanted to look at the test items I created (the 2 Project Items).
But there is no ProjectItem table and no ToDoItem table either!
How can this happen?
What did I do wrong?
Why is it creating the tables running on localhost but when
Publishing on azure it isn't?
I believe that it is not that simple as to create the object model and it will create the same table in the backend (SQL Azure to be clear, or Azure Storage). You need to create it using Azure dashboard, or do the custom API and do as described here. You may do the same in the Visual Studio, i think, or from the SQL Server Management Studio connected to the SQL Azure db.
For Mobile Services, however, if you set the dynamic schema on the dashboard, it will be able to create new columns when they are in the object, but it is not recommended in the production.
So, you did not anything wrong, it looks that the creation of the table programmatically is just not a supported way (only by dashboard or any type of the explorer like SSMS or VS). Anyway (by the way), they will be not in the System Tables branch.
I have an azure mobile service that will go live at some point. So I need to create UAT and dev versions which would point to the UAT and dev databases. What I am struggling with is how to create these.
The namespace in my live, UAT and Dev databases need to be the same but if I create a new mobile service called myAppName_UAT, it's going to want to use MyAppName_UAT as the namespace and so will not find any of the tables.
Has anyone overcome this problem? Once the product goes live I'll need to be able to test the mobile apps against the Dev db without affecting live which surely must be a common scenario?
Any advice would be very gratefully received.
Edit: What I'm specifically after is how to manage the multiple environments within the Azure Portal. I can deploy all the other components of my UAT environment but I'm stuck on the mobile service.
I am not asking for a way for my applications to switch config files or to migrate data between databases. Does anyone have any experience of running azure applications with multiple components where they ran multiple mobile services?
Do you use a Version Control? For me, you just need to create branches to separate the 'UAT' and 'dev' versions.
About the databases:
You can use web.config transformations to switch the connection string between your databases.
http://msdn.microsoft.com/en-us/library/dd465326.aspx
How do I use Web.Config transform on my connection strings?
=================================================================================
Update:
Ok, now I understood what you want.
Create your two versions of mobile services:
1-Log in Windows Azure Management Portal (http://manage.windowsazure.com)
2-Create your test mobile services (if you already have then, skip this step):
2.1- New -> Compute -> Mobile Services
2.2- Url - MyMobileServicesTest
2.3- Database -> Create a new (test db).
3-Create your production mobile services (if you already have then, skip this step):
2.1- New -> Compute -> Mobile Services
2.2- Url - MyMobileServicesProduction
2.3- Database -> Create a new (production db).
Right now, you have two different versions.
Using Windows Azure SDK:
//public static MobileServiceClient MobileService = new MobileServiceClient(
// "AppUrl",
// "AppKey"
//);
Pay attention: AppUrl will be "MyMobileServicesTest.azure-mobile.net/" or "MyMobileServicesProduction.azure-mobile.net/". The app key, each environment will have it's own. You can store this settings in a config file and switch according to what you are doing.
More information:
http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-data-dotnet/
Multiple mobile services can share the same database. You only need to specify the same schema name in web.config in each mobile service:
<appSettings>
<add key="MS_MobileServiceName" value="MyAppName" />
</appSettings>
Updated:
The setting above only works in localhost, but not after publishing to live.
Need to do the following trick in order to make it work. Just hard code the schema name into function OnModelCreating. This way the database schema name will not depend on the mobile service name any more:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
string schema = "MyAppName"; // ServiceSettingsDictionary.GetSchemaName();
if (!string.IsNullOrEmpty(schema))
{
modelBuilder.HasDefaultSchema(schema);
}
modelBuilder.Conventions.Add(
new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
"ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
}