milosev.com
  • Home
    • List all categories
    • Sitemap
  • Downloads
    • WebSphere
    • Hitachi902
    • Hospital
    • Kryptonite
    • OCR
    • APK
  • About me
    • Gallery
      • Italy2022
      • Côte d'Azur 2024
    • Curriculum vitae
      • Resume
      • Lebenslauf
    • Social networks
      • Facebook
      • Twitter
      • LinkedIn
      • Xing
      • GitHub
      • Google Maps
      • Sports tracker
    • Adventures planning
  1. You are here:  
  2. Home
  3. ASP.NET
  4. Core

Asp.Net core Web Api connect Entity Framework to MySql with Code First in .NET 7

Details
Written by: Stanko Milosev
Category: Core
Published: 04 August 2023
Last Updated: 04 August 2023
Hits: 629
1. Start new empty Asp.Net Web Api core project

2. In appsetting.json add:

"ConnectionStrings": {
	"DefaultConnection": "Server=localhost;Database=database;Uid=user;Pwd=password;"
}
So it looks like:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=database;Uid=user;Pwd=password;"
  }
}
3. Install following packages:
Microsoft.EntityFrameworkCore
MySql.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design

4. Add new class "ModelExample":

using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace AspNetCore7WebApiEFMySqlExample;

public class ModelExample
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public string PhoneNumber { get; set; }
}
5. Add new class:
using Microsoft.EntityFrameworkCore;

namespace AspNetCore7WebApiEFMySqlExample;

public class ModelExampleContext : DbContext
{
    public ModelExampleContext(DbContextOptions<ModelExampleContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ModelExample>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.Name).IsRequired();
        });
    }
}
6. In Program.cs add:
builder.Services.AddDbContext<ModelExampleContext>(x => x.UseMySQL(builder.Configuration.GetConnectionString("DefaultConnection")));
6. In project (not solution) folder execute:
dotnet ef migrations add InitialCreate
dotnet ef database update
Example download from here

Serve static file from Wep Api core in Azure

Details
Written by: Stanko Milosev
Category: Core
Published: 14 March 2023
Last Updated: 14 March 2023
Hits: 734
In Program.cs I wrote:
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory())),
    RequestPath = "",
    ServeUnknownFileTypes = true,
    DefaultContentType = "text/plain"
});
    
    
    
        

Publish .NET Core 7 Web Api to Azure

Details
Written by: Stanko Milosev
Category: Core
Published: 13 March 2023
Last Updated: 14 March 2023
Hits: 747
Here I have to tried to explain how to publish to Azure, but for me that is not enough, so here is more.

First I have downloaded publish profile from azure:

Then in Visual Studio 2022 Build -> Publish -> Import profile I have loaded my profile.

Most probably would also work if simply with FTP upload web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\CreateAndUpdateKmlWebApi.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>
Notice part:
modules="AspNetCoreModuleV2"
and
arguments=".\CreateAndUpdateKmlWebApi.dll"
At the end, to access Swagger UI go to something like: https://milosevtracking.azurewebsites.net/swagger/index.html

ProgressBar using SignalR

Details
Written by: Stanko Milosev
Category: Core
Published: 14 March 2021
Last Updated: 06 April 2022
Hits: 1987
In order to write this article, I was using this web site.

First I started new ASP.NET Core Empty project with Target Framework 5.0:

Then using nuget I installed Microsoft.AspNetCore.SignalR.Common:

I have added new folder "Hubs", where I added new class ProgressHub which is inherited from Hub:

using System.Threading;
using Microsoft.AspNetCore.SignalR;

namespace SignalRProgressBar.Hubs
{
  public class ProgressHub : Hub
  {
    public string msg = "Initializing and Preparing...";
    public int count = 100;

    public void CallLongOperation()
    {
      for (int x = 0; x <= count; x++)
      {

        // delay the process to see things clearly
        Thread.Sleep(100);

        if (x == 20)
          msg = "Loading Application Settings...";

        else if (x == 40)
          msg = "Applying Application Settings...";

        else if (x == 60)
          msg = "Loading User Settings...";

        else if (x == 80)
          msg = "Applying User Settings...";

        else if (x == 100)
          msg = "Process Completed!...";

        string myMessage = string.Format(msg + " {0}% of {1}%", x, count);
        Clients.All.SendAsync("ReceiveMessage", myMessage);
      }
    }
  }
}
In Startup.cs in the method ConfigureServices I added SignalR:
public void ConfigureServices(IServiceCollection services)
{
  services.AddSignalR();
}
In EndPoints I added Hub:
app.UseEndpoints(endpoints =>
{
	endpoints.MapHub<ProgressHub>("/progressHub");
});
Then I added wwwroot folder, and support for static files as I already explained here

After that I added index.html page in wwwroot folder, and I added Signalr JavaScript using client library:

As a search I wrote signalR and I have choosen aspnet-signalr:

I have added js library to html

<script defer src="aspnet-signalr/signalr.min.js"></script>
In folder js I have added my Javascript file, which look like this:
var connection = new signalR.HubConnectionBuilder().withUrl("../progressHub").build();
connection.start().then(function () {
    connection.invoke("CallLongOperation").catch(function (err) {
        return console.error(err.toString());
    });
});

connection.on("ReceiveMessage", function (message) {
    document.getElementById('progressbar').value = document.getElementById('progressbar').value + 1; 
    document.getElementById('progressbarText').innerText = message; 
});

My html looks like this:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script defer src="aspnet-signalr/signalr.min.js"></script>
    <script defer src="js/progress.js"></script>
</head>
<body>
    <div style="width: 30%; margin: 0 auto;">

        <label id="progressbarText" style="font-family: Tahoma; font-size: 0.9em; color: darkgray; margin-top: 230px; padding-bottom: 5px; display:inline-block" for="progressbar">
            Initializing and Preparing...
        </label>
        <br />
        <progress id="progressbar" value="1" max="100"></progress>
    </div>
</body>
</html>
Notice line in controller:
Clients.All.SendAsync("ReceiveMessage", myMessage);
and line in Javascript:
connection.on("ReceiveMessage", function (message) {
    document.getElementById('progressbar').value = document.getElementById('progressbar').value + 1; 
    document.getElementById('progressbarText').innerText = message; 
});
This is how SignalR communicates with client and server using WebSocket. Method name on both sides has to be the same.

Example download from here

  1. Endpoint Routing does not support 'IApplicationBuilder.UseMvc(...)'
  2. jQuery JSON error handling
  3. jQuery "POST" method
  4. Start empty Asp.Net core project

Page 1 of 4

  • 1
  • 2
  • 3
  • 4