.Net Core Odata response missed metadata values - .net-core

Im using Odata on my old project with .NET Framework, and response from it like this:
{
"#odata.context": "http://localhost:5000/api/$metadata#TestController",
"#odata.count": 0,
"value": []
}
Here is a metadata of odata and prop "value" contains response data.
But when I tried to install Odata into my new project on .NET Core 3.1, it works, but response from it like this:
{
//some data
}
I haven't got odata metadata velues. I want that responses from all projects were similar. Can't find information how to add|turn on metadata into my .Net core response

It could work well in my asp.net core 3.1 project,here is a working demo like below:
1.Install Microsoft.AspNetCore.OData package version 7.5.2.
2.Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddOData();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.Select().Filter().OrderBy().Count().MaxTop(10);
endpoints.MapODataRoute("api", "api", GetEdmModel());
});
}
private IEdmModel GetEdmModel()
{
var odataBuilder = new ODataConventionModelBuilder();
odataBuilder.EntitySet<WeatherForecast>("WeatherForecast");
return odataBuilder.GetEdmModel();
}
3.Model:
public class WeatherForecast
{
public Guid Id { get; set; } //must have a key
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
4.Controller(comment on Route attribute and ApiController attribute):
//[ApiController]
//[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[EnableQuery]
[HttpGet]
public async Task<IEnumerable<WeatherForecast>> GetAsync()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
Result:

Related

How can I use Configuration in Net Core 6 worker app?

All information about using Configuation starts with creating builder and
var builder = WebApplication.CreateBuilder(args);
subsequnetly using
builder.Configuration.
configuration ,but in Worker services WebApplication is not available.
How can i use Configuration in Microsoft.NET.Sdk.Worker type of project?
This might help https://medium.com/c-sharp-progarmming/how-to-set-appsettings-or-config-in-a-net-worker-service-cc2d70ab4e0c
It is by accessing the HostBuilderContext
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
IConfiguration configuration = hostContext.Configuration;
services.Configure<RabbitMQConfiguration>(configuration.GetSection(nameof(RabbitMQConfiguration)));
services.AddHostedService<Worker>();
});
First of all, you should add ConfigureAppConfiguration when CreateHostBuilder
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
})
.ConfigureAppConfiguration((hostContext, configBuilder) =>
{
configBuilder
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.Build();
});
Then, add configuration in appsettings.YourEnv.json
"worker": {
"id": 12345,
"name": "SimpleWorker",
"delay": 1000
}
Add IConfiguration in Worker constructor and use it.
Full example of Worker class:
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly IConfiguration _configuration;
public Worker(ILogger<Worker> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var workerConfig = _configuration.GetSection("worker").Get<SimpleWorkerConfig>();
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker {id}:{name} running at: {time} with delay {delay}",
workerConfig.Id, workerConfig.Name, DateTimeOffset.Now, workerConfig.Delay);
await Task.Delay(workerConfig.Delay, stoppingToken);
}
}
}
public class SimpleWorkerConfig
{
public int Id { get; set; }
public string Name { get; set; }
public int Delay { get; set; }
}
Result:

Keep getting SqlException: Cannot insert explicit value for identity column in table 'Movie' when IDENTITY_INSERT is set to OFF

I'm working on a program that I take an excel file to a SQL database. I'm using EPPlus -Version 4.5.2.1. I keep getting errors when I import excel file Movie. SqlException: Cannot insert explicit value for identity column in table 'Movie' when IDENTITY_INSERT is set to OFF. DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
WebApplication14.Controllers.HomeController.Import(IFormFile file) in HomeController.cs
+
await _dbContext.SaveChangesAsync();
The HomeController Code:
namespace WebApplication14.Controllers
{
public class HomeController : Controller
{
private readonly ApplicationDbContext _dbContext;
public HomeController(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<List<Movie>> Import(IFormFile file)
{
var list = new List<Movie>();
using (var stream = new MemoryStream())
{
await file.CopyToAsync(stream);
using (var package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
var rowcount = worksheet.Dimension.Rows;
var colcount = worksheet.Dimension.Columns;
for (int row = 2; row < rowcount; row++)
{
list.Add(new Movie
{
Id = int.Parse(worksheet.Cells[row, 1].Value.ToString().Trim()),
Title = worksheet.Cells[row, 2].Value.ToString().Trim(),
Genre = worksheet.Cells[row, 3].Value.ToString().Trim()
});
}
}
}
//SaveDataToDb(list);
_dbContext.Movie.AddRange(list);
await _dbContext.Database.ExecuteSqlCommandAsync(#"SET IDENTITY_INSERT [MovieList-1].[dbo].[Movie] ON");
await _dbContext.SaveChangesAsync();
await _dbContext.Database.ExecuteSqlCommandAsync(#"SET IDENTITY_INSERT [MovieList-1].[dbo].[Movie] OFF");
return list;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Model Movie
namespace WebApplication14.Models
{
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public string Genre { get; set; }
}
}
DbContext Code
namespace WebApplication14.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Movie> Movie { get; set; }
}
}
My Migration Code
public partial class MoviesToDb : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Movie",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Title = table.Column<string>(nullable: true),
Genre = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Movie", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Movie");
}
}
}
Startup Code
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
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.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
My AppSettings.Json ConnectionString
"ConnectionStrings": {
"DefaultConnection": "Server=localhost\\SQLEXPRESS;Database=MovieList-1;Trusted_Connection=True;MultipleActiveResultSets=true"
},
View/Home/Index
#{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about building Web apps with ASP.NET Core.</p>
<div class="container">
<form method="post" asp-controller="Home" asp-action="Import" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Import From Excel</button>
</form>
</div>
</div>
EF will open and close the connection after each operation by default. This causes the SqlConnection to be returned to the Connection Pool, and its state is cleared, including dropping temp tables, and resetting session-level SET setting, each time it's fetched from the pool.
If you explicitly open the DbContext's connection (or start a transaction), the IDENTITY_INSERT setting should still be in effect when you call SaveChanges():
_dbContext.Database.OpenConnection();
_dbContext.Movie.AddRange(list);
await _dbContext.Database.ExecuteSqlCommandAsync(#"SET IDENTITY_INSERT [MovieList-1].[dbo].[Movie] ON");
await _dbContext.SaveChangesAsync();
await _dbContext.Database.ExecuteSqlCommandAsync(#"SET IDENTITY_INSERT [MovieList-1].[dbo].[Movie] OFF");

Why my Entity Framework Core Database-First Model Custom Changes Gone After Re-Scaffold? Any Solution

I am working with ASP.Net Core 2.1 & I am facing a problem. I have been working on implementing a Database-First application. The initial Scaffold-DbContext command works just fine and creates all my entities correctly. After that, I make some changes to model files for Validation. My DBA made a new change on DB so I re-Scaffold the DB. Then I notice that re-scaffold overwrites all the custom code I have added to all the model files.
Is there any way I re-scaffold the DB but that only changes those files changes by DBA in ASP.Net Core DB First Approach?
Every time I am facing this problem.
I Re-scaffold with the below command:
Scaffold-DbContext "Server=192.168.46.101;Database=DBNAME;User Id=USERID;Password=PASSWORD" Microsoft.EntityFrameworkCore.SqlServer -ContextDir Data -OutputDir Models -UseDatabaseNames -force
My Custom Added Annotation to Model:
//Custom Annotation
[Key]
public int COLORCODE { get; set; }
//Custom Validation
[Required(ErrorMessage = "Color Name can not be empty")]
public string COLOR { get; set; }
public string REMARKS { get; set; }
After Re-scaffolding my code be like:
public int COLORCODE { get; set; }
public string COLOR { get; set; }
public string REMARKS { get; set; }
My Program.cs File:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
logging.AddNLog();
})
.UseStartup<Startup>();
}
My Startup.cs File:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = new PathString("/Administrator/AccessDenied");
});
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
// options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<Context>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("ConnectionName")));
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
options.Password.RequiredLength = 15;
options.Password.RequiredUniqueChars = 5;
options.Password.RequireNonAlphanumeric = false;
options.SignIn.RequireConfirmedEmail = true;
options.Tokens.EmailConfirmationTokenProvider = "CustomEmailConfirmation";
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
})
.AddEntityFrameworkStores<Context>()
.AddDefaultTokenProviders()
.AddTokenProvider<CustomEmailConfirmationTokenProvider<IdentityUser>>("CustomEmailConfirmation");
// REGISTER ExtractEMService
ExtractEMService.ExtractEMRegisterService(services);
//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseStatusCodePagesWithReExecute("/Error/{0}");
//app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Basic}/{action=BasicColors}/{id?}");
});
}
}
There is no way you can do that, but just leave the generated classes as is and use a buddy class for the data annotations:
[MetadataType(typeof(MetaData))]
public partial class Person
{
public class MetaData
{
[Required]
[Display(Name = "Enter Your Name")]
public string FirstName;
}
}
https://ryanhayes.net/data-annotations-for-entity-framework-4-entities-as-an-mvc-model/

Get items count from OData api

I'm working on ASP.NET Core 3.1 project where I use OData for the rest api. The problem is that when I try to fetch the count of the items in the collection with this query: http://someurl?$count=true, OData returns me an array of all the items, instead of the count. I read a lot of articles about OData and nothing helped, so I'm quite confused.
Here is a working demo , you could refer to
Install Package Microsoft.AspNetCore.OData -Version 7.4.0
Model
public class Student
{
public Guid Id { get; set; }
public string Name { get; set; }
public int Score { get; set; }
}
Controller , EnableQuery attribute enables an endpoint to have OData capabilities
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
[HttpGet]
[EnableQuery()]
public IEnumerable<Student> Get()
{
return new List<Student>
{
new Student
{
Id = Guid.NewGuid(),
Name = "Vishwa Goli",
Score = 100
},
new Student
{
Id = Guid.NewGuid(),
Name = "Josh McCall",
Score = 120
}
};
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(mvcOptions =>
mvcOptions.EnableEndpointRouting = false);
services.AddOData();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapControllers();
//});
app.UseMvc(routeBuilder =>
{
// enable Selection, Expansion, Count, Filter, OrderBy for all routes under “odata/”
routeBuilder.Expand().Select().Count().OrderBy().Filter();
routeBuilder.MapODataServiceRoute("odata", "odata", GetEdmModel());
});
}
private IEdmModel GetEdmModel()
{
var edmBuilder = new ODataConventionModelBuilder();
edmBuilder.EntitySet<Student>("Students");
return edmBuilder.GetEdmModel();
}
Result:
Reference:
https://devblogs.microsoft.com/odata/experimenting-with-odata-in-asp-net-core-3-1/
https://medium.com/#sddkal/using-odata-controller-in-net-core-apis-63b688585eaf

Firebase Authentication token is not valid

I am using the Xamarin forms and getting the firebase token by using this code.
using System;
using Android.Content;
using Android.Gms.Auth.Api;
using Android.Gms.Auth.Api.SignIn;
using Android.Gms.Common;
using Android.Gms.Common.Apis;
using Android.OS;
using GoogleNativeLogin.Models;
using GoogleNativeLogin.Services.Contracts;
using Plugin.CurrentActivity;
namespace GoogleNativeLogin.Droid
{
public class GoogleManager : Java.Lang.Object, IGoogleManager, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener
{
public Action<GoogleUser, string> _onLoginComplete;
public static GoogleApiClient _googleApiClient { get; set; }
public static GoogleManager Instance { get; private set; }
private const string webClientId = "********************************.apps.googleusercontent.com";
public GoogleManager()
{
Instance = this;
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
.RequestIdToken(webClientId)
.RequestEmail()
.Build();
_googleApiClient = new GoogleApiClient.Builder(CrossCurrentActivity.Current.AppContext)
.AddConnectionCallbacks(this)
.AddOnConnectionFailedListener(this)
.AddApi(Auth.GOOGLE_SIGN_IN_API, gso)
.AddScope(new Scope(Scopes.Profile))
.Build();
}
public void Login(Action<GoogleUser, string> onLoginComplete)
{
_onLoginComplete = onLoginComplete;
Intent signInIntent = Auth.GoogleSignInApi.GetSignInIntent(_googleApiClient);
CrossCurrentActivity.Current.Activity.StartActivityForResult(signInIntent, 1);
_googleApiClient.Connect();
}
public void Logout()
{
_googleApiClient.Disconnect();
}
public void OnAuthCompleted(GoogleSignInResult result)
{
if (result.IsSuccess)
{
GoogleSignInAccount accountt = result.SignInAccount;
_onLoginComplete?.Invoke(new GoogleUser()
{
Token = accountt.IdToken,
Name = accountt.DisplayName,
Email = accountt.Email,
Picture = new Uri((accountt.PhotoUrl != null ? $"{accountt.PhotoUrl}" : $"https://autisticdating.net/imgs/profile-placeholder.jpg"))
}, string.Empty);
}
else
{
_onLoginComplete?.Invoke(null, "An error occured!");
}
}
public void OnConnected(Bundle connectionHint)
{
}
public void OnConnectionSuspended(int cause)
{
_onLoginComplete?.Invoke(null, "Canceled!");
}
public void OnConnectionFailed(ConnectionResult result)
{
_onLoginComplete?.Invoke(null, result.ErrorMessage);
}
}
}
And I am testing the token locally using Postman to my local Asp.Net core Web API. The authentication code is this.
public static IServiceCollection AddFirebaseAuthentication(this IServiceCollection services, string issuer, string audience)
{
var configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{issuer}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.IncludeErrorDetails = true;
o.RefreshOnIssuerKeyNotFound = true;
o.MetadataAddress = $"{issuer}/.well-known/openid-configuration";
o.ConfigurationManager = configurationManager;
o.Audience = audience;
});
return services;
}
public static IServiceCollection AddFirebaseAuthentication(this IServiceCollection services, string firebaseProject)
{
return services.AddFirebaseAuthentication("https://securetoken.google.com/" + firebaseProject, firebaseProject);
}
I am passing the Firebase Project Id to this function.
IServiceCollection AddFirebaseAuthentication(this IServiceCollection services, string firebaseProject)
And calling the API with Authorize attribute. And I am getting this error in the
Visual studio Output.
Microsoft.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException:
IDX10501: Signature validation failed. Unable to match keys:

Resources