SDCores 2.0.0
dotnet add package SDCores --version 2.0.0
NuGet\Install-Package SDCores -Version 2.0.0
<PackageReference Include="SDCores" Version="2.0.0" />
paket add SDCores --version 2.0.0
#r "nuget: SDCores, 2.0.0"
// Install SDCores as a Cake Addin #addin nuget:?package=SDCores&version=2.0.0 // Install SDCores as a Cake Tool #tool nuget:?package=SDCores&version=2.0.0
SDCores
SDCores is a generic pakage that contained any necessary packages for creating a web APIs with ASP.NET Core. Some pakages will ask for licence. Please to check the dependencies list for more information and purchase for your own lience. We do not provide any licenses and disclaim all responsibility for your licenses.
Features
- Custom service configufation registers (Authentication, Swagger, Custom DependencyInjection )
- Extened Aspose.Excel functions
- Extened Aspose.Email functions
- File handling's functions
- "appsettings.json" accessor helper
- Dynamic repository with accessor unit (UnitOfWork)
Usage
1. AuthenticationConfig
Enables JWT-bearer authentication using the default scheme. JWT bearer authentication performs authentication by extracting and validating a JWT token from the Authorization request header.
public static void AddAuthenticationConfigufation(this IServiceCollection services, IConfiguration configuration)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
Using package Document : Microsoft.AspNetCore.Authentication.JwtBearer
.
2. DependencyInjectionConfiguration
Why is DependencyInjectionConfiguration ?
In the below example, the IServiceA interface defines a Call method:
public interface IServiceA
{
void Call(string name);
}
This interface is implemented by ServiceA:
public class ServiceA : IServiceA
{
void Call(string name)
{
// implementation
}
}
The example app registers the IServiceA with ServiceA by AddScoped method:
using DependencyInjectionConfigurationExample.Interfaces;
using DependencyInjectionConfigurationExample.Services;
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddScoped<IServiceA, ServiceA>();
...
var app = builder.Build();
The IServiceA service is requested and used to call the Call method:
public class TestController : ControllerBase
{
private readonly IServiceA _serviceA;
public TestController(IServiceA serviceA)
{
_serviceA = serviceA;
}
public void OnRequest()
{
_serviceA.Call("SD3team");
}
}
If you forget to register any nessessory service into DI engine or not defined before using, there are some annoying error can be happened:
System.InvalidOperationException: Unable to resolve service for type ...
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, ...
With DependencyInjectionConfiguration, above problem can be solved.
First of all, you need to create IServiceA service with DependencyInjection attribute and specify that the service will be created every time it is requested (Transient) :
[DependencyInjectionAttribute(ServiceLifetime.Transient)]
public interface IServiceA
{
void Do();
}
Finally, register the DependencyInjection by adding this line into Program.cs:
builder.Services.AddDependencyInjectionConfiguration(typeof(Program));
And now, all of your services that attributed with DependencyInjection will be automatically registered in the dotnet core DI engine. When you create a new service with DependencyInjection attribute, you do not need to add any new code line into DI engine for the new service register.
3. SwaggerGenConfig
Define one or more documents to be created by the Swagger generator. Adding one or more "securityDefinitions" and describing how your API is protected to the generated Swagger. Adds a global security requirement.
public static void AddSwaggerGenConfiguration(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please insert JWT with Bearer into field",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
}
Using package Document : Swashbuckle.AspNetCore.SwaggerGen
4. AsposeUtility
Using Aspose.Cells version 23.8.0
Start Aspose.Cells with License
.Net Document
5. ExcelUtility
An extension from Aspose.cells.
CheckExcel: Check uploaded excel file template with sample template.
DownloadExcel: Create an excel file by a given excel file template with dynamic input data.
6. ExceptionHandlingMiddleware
A custom middleware that catches exception HttpStatusCode and write error message.
7. FilesUtility
Contains several file handling functions
Upload file into folder and return file name (string) :
UploadAsync(IFormFile file, string subfolder = "upload", string rawFileName = null)
UploadAsync(string file, string subfolder = "upload", string rawFileName = null)
Delete file on path:
DeleteFile(string filePath = "upload")
Save file into folder:
SaveFile(IFormFile file, string subfolder = "upload", string rawFileName = null)
8. OperationResult
A custom class Result.
9. PaginationUtility
A widget that returns pagination data.
Create(List<T> source, int pageNumber, int pageSize = 10, bool isPaging = true)
CreateAsync(IQueryable<T> source, int pageNumber, int pageSize = 10, bool isPaging = true)
10. SettingsConfigUtility
Get a valued stored in the appsettings.
public interface IServiceA
{
void Do();
}
----------------------------------------------------------------------------------------------------
public class ServiceA : IServiceA
{
private readonly IConfiguration _cofiguration;
public ServiceA(IConfiguration cofiguration)
{
_cofiguration = cofiguration;
}
void Do()
{
var demo = _configuration.GetSection("AppSettings:Demo").Value;
var mailSettingServer _configuration.GetSection("MailSettingServer").Get<MailSettingServer>();
...
}
}
You don't need to declare IConfiguration in Service or Controller anymore, use the following:
public interface IServiceA
{
void Do();
}
----------------------------------------------------------------------------------------------------
using SDCores;
public class ServiceA :IServiceA
{
void Do()
{
var demo = SettingsConfigUtility.GetCurrentSettings("AppSettings:Factory");
var mailSettingServer = SettingsConfigUtility<MailSettingServer>.GetCurrentSettings("MailSettingServer");
...
}
}
11. Repository Base
A repository class that contains several necessary customized functions All the thing you need to do is creating a repository class as a UnitOfWork layer for your own project like the following sample:
using Microsoft.EntityFrameworkCore.Storage;
using SDCores;
namespace API._Repositories
{
[DependencyInjection(ServiceLifetime.Scoped)]
public interface IRepositoryAccessor
{
IRepository<ModelA> ModelA{get;}
...
Task<bool> Save();
Task<IDbContextTransaction> BeginTransactionAsync();
}
}
...
using Microsoft.EntityFrameworkCore.Storage;
using SDCores;
namespace API._Repositories
{
public class RepositoryAccessor : IRepositoryAccessor
{
private DBContext _dbContext;
public RepositoryAccessor(DBContext dbContext)
{
_dbContext = dbContext;
ModelA = new Repository<ModelA, DBContext>(_dbContext);
...
}
public IRepository<ModelA> ModelA { get; set; }
...
public async Task<bool> Save()
{
return await _dbContext.SaveChangesAsync() > 0;
}
public async Task<IDbContextTransaction> BeginTransactionAsync()
{
return await _dbContext.Database.BeginTransactionAsync();
}
}
}
Usage :
public interface IServiceA
{
void Do();
}
----------------------------------------------------------------------------------------------------
using SDCores;
public class ServiceA : IServiceA
{
private readonly IRepositoryAccessor _repoAccessor;
public ServiceA(IRepositoryAccessor repoAccessor) {
_repoAccessor = repoAccessor;
}
void Do()
{
var demo = _repoAccessor.ModelA.FirstOrDefaultAsync(x => ...);
...
}
}
12. MailUtility
An extended extension from Aspose.cells.
Add this setting to appsetting.json :
"MailSettingServer": {
"Server": "<Server>",
"UserName": "<UserAddress>",
"Password": "<Password>",
"FromEmail": "<FromAddress>",
"FromName": "<Name>",
"Port": "<Port>",
"SecurityOptions": "Auto",
"UseAuthentication": "false"
}
Usage :
using SDCores;
...
OperationResult result = MailUtility.SendMail("<ToAdrress>", "Subject", "Content");
13. HTTPSRedirection
Custom middleware for redirecting HTTP Requests to HTTPS.
Program.cs :
using SDCores;
...
var app = builder.Build();
//app.UseWebSockets(); Uncomment this if Websocket is available
app.UseSDHttpsRedirection();
...
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. |
-
net9.0
- Aspose.Cells (>= 23.8.0)
- Aspose.Email (>= 23.7.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 9.0.0)
- Microsoft.EntityFrameworkCore (>= 9.0.0)
- Microsoft.EntityFrameworkCore.SqlServer (>= 9.0.0)
- Swashbuckle.AspNetCore.SwaggerGen (>= 7.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.