Author: malabdali
C# Index and Range
Index
int[] numbers = Enumerable.Range(0, 100).ToArray();
int x = 12;
int y = 25;
int z = 36;
Console.WriteLine($"{numbers[^x]} is the same as {numbers[numbers.Length - x]}");
Console.WriteLine($"{numbers[x..y].Length} is the same as {y - x}");
Console.WriteLine("numbers[x..y] and numbers[y..z] are consecutive and disjoint:");
Span<int> x_y = numbers[x..y];
Span<int> y_z = numbers[y..z];
Console.WriteLine($"\tnumbers[x..y] is {x_y[0]} through {x_y[^1]}, numbers[y..z] is {y_z[0]} through {y_z[^1]}");
Console.WriteLine("numbers[x..^x] removes x elements at each end:");
Span<int> x_x = numbers[x..^x];
Console.WriteLine($"\tnumbers[x..^x] starts with {x_x[0]} and ends with {x_x[^1]}");
Console.WriteLine("numbers[..x] means numbers[0..x] and numbers[x..] means numbers[x..^0]");
Span<int> start_x = numbers[..x];
Span<int> zero_x = numbers[0..x];
Console.WriteLine($"\t{start_x[0]}..{start_x[^1]} is the same as {zero_x[0]}..{zero_x[^1]}");
Span<int> z_end = numbers[z..];
Span<int> z_zero = numbers[z..^0];
Console.WriteLine($"\t{z_end[0]}..{z_end[^1]} is the same as {z_zero[0]}..{z_zero[^1]}");
Range
var words = "my name is mohammed alabdali i am from jeddah i study master".Split(" ");
string[] allWords = words[..]; // all texts
string[] firstPhrase = words[..4]; //my name is mohammed
string[] lastPhrase = words[9..]; //i study master
Range implicitRange = 3..^5;
Range explicitRange = new(
start: new Index(value: 3, fromEnd: false),
end: new Index(value: 5, fromEnd: true));
if (implicitRange.Equals(explicitRange))
{
Console.WriteLine(
$"The implicit range '{implicitRange}' equals the explicit range '{explicitRange}'");
}
// Sample output:
// The implicit range '3..^5' equals the explicit range '3..^5'
Entity Framework With Mysql
packages you have to install
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="7.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Analyzers" Version="7.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="7.0.0" />
Create Tables Classes
assume we have two tables like this
then we will build class or record for it like
PrimaryKey("StudentId")]
public class Student
{
public string StudentId { get; set; }
public string? StudentName { get; set; }
public string? cid { get; set; }
public Course? Course { get; set; }
}
[PrimaryKey("CourseId")]
public class Course
{
public string CourseId { get; set; }
[Required]
public string? CourseName { get; set; }
//public ICollection<Student> Students { get; set; }
}
build the context
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// configure connection
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseMySql($"server=127.0.0.1;user=school;password=*******;database=FoodMenu",
MySqlServerVersion.AutoDetect("server=127.0.0.1;user=schhol;password=*******;database=FoodMenu"));
}
}
// build relations
protected sealed override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().HasOne<Course>(s => s.Course).WithMany().HasForeignKey("cid");
//modelBuilder.Entity<Course>().HasMany<Student>(s => s.Students).WithOne(s=>s.Course).HasForeignKey((e)=>e.CourseId);
}
}
then you can use it directly
using(SchoolContext context = new SchoolContext())
{
var res2= context.Students.Include(s=>s.Course).ToList();
foreach (var item in res2)
{
Console.WriteLine(JsonSerializer.Serialize(item).ToString());
}
}
or use it as a service
builder.Services.AddDbContext<SchoolContext>(c =>
{
c.UseMySql("connection string", MySqlServerVersion.AutoDetect("connection string"));
});
C# – Multithreading
The Main Thread
using System;
using System.Threading;
namespace MultithreadingApplication {
class MainThreadProgram {
static void Main(string[] args) {
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);
Console.ReadKey();
}
}
}
Sr.No. | Property & Description |
---|---|
1 | CurrentContext Gets the current context in which the thread is executing. |
2 | CurrentCulture Gets or sets the culture for the current thread. |
3 | CurrentPrinciple Gets or sets the thread’s current principal (for role-based security). |
4 | CurrentThread Gets the currently running thread. |
5 | CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run-time. |
6 | ExecutionContext Gets an ExecutionContext object that contains information about the various contexts of the current thread. |
7 | IsAlive Gets a value indicating the execution status of the current thread. |
8 | IsBackground Gets or sets a value indicating whether or not a thread is a background thread. |
9 | IsThreadPoolThread Gets a value indicating whether or not a thread belongs to the managed thread pool. |
10 | ManagedThreadId Gets a unique identifier for the current managed thread. |
11 | Name Gets or sets the name of the thread. |
12 | Priority Gets or sets a value indicating the scheduling priority of a thread. |
13 | ThreadState Gets a value containing the states of the current thread. |
Creating Threads
using System;
using System.Threading;
namespace MultithreadingApplication {
class ThreadCreationProgram {
public static void CallToChildThread() {
Console.WriteLine("Child thread starts");
}
static void Main(string[] args) {
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
childThread.Join(1000);
Console.ReadKey();
}
Thread Pool
List<string> urls = new(){
"https://www.google.com/",
"https://www.duckduckgo.com/",
"https://www.yahoo.com/",
};
foreach (var url in urls)
{
ThreadPool.QueueUserWorkItem((state) => CheckHttpStatus(url));
}
async and await
static void Main()
{
Task task = new Task(CallMethod);
task.Start();
task.Wait();
Console.ReadLine();
}
static async void CallMethod()
{
string filePath = "E:\\sampleFile.txt";
Task<int> task = ReadFile(filePath);
Console.WriteLine(" Other Work 1");
Console.WriteLine(" Other Work 2");
Console.WriteLine(" Other Work 3");
int length = await task;
Console.WriteLine(" Total length: " + length);
Console.WriteLine(" After work 1");
Console.WriteLine(" After work 2");
}
static async Task<int> ReadFile(string file)
{
int length = 0;
Console.WriteLine(" File reading is stating");
using (StreamReader reader = new StreamReader(file))
{
// Reads all characters from the current position to the end of the stream asynchronously
// and returns them as one string.
string s = await reader.ReadToEndAsync();
length = s.Length;
}
Console.WriteLine(" File reading is completed");
return length;
}
static async Task Main(string[] args)
{
await callMethod();
Console.ReadKey();
}
public static async Task callMethod()
{
Method2();
var count = await Method1();
Method3(count);
}
public static async Task<int> Method1()
{
int count = 0;
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(" Method 1");
count += 1;
}
});
return count;
}
public static void Method2()
{
for (int i = 0; i < 25; i++)
{
Console.WriteLine(" Method 2");
}
}
public static void Method3(int count)
{
Console.WriteLine("Total count is " + count);
}
ASP.NET Core – Dependency Injection and Middlewares
Services
assume we have logger service like
public interface ILog
{
void info(string str);
}
class MyConsoleLogger : ILog
{
public void info(string str)
{
Console.WriteLine(str);
}
}
then we can register it in ioc like
builder.Services.Add(new ServiceDescriptor(typeof(ILog), typeof( MyConsoleLogger)));
in the above example the service it singleton by default
- Singleton: IoC container will create and share a single instance of a service throughout the application’s lifetime.
- Transient: The IoC container will create a new instance of the specified service type every time you ask for it.
- Scoped: IoC container will create an instance of the specified service type once per request and will be shared in a single request.
public void ConfigureServices(IServiceCollection services)
{
services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger())); // singleton
services.Add(new ServiceDescriptor(typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Transient)); // Transient
services.Add(new ServiceDescriptor(typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Scoped)); // Scoped
}
access to service
var services = this.HttpContext.RequestServices;
var log = (ILog)services.GetService(typeof(ILog));
// or in controller api parameter you can access it by
[FromServices] IReCaptcha reCaptcha
asp.net core Identity and authentication
HttpContext
HttpContext encapsulates all information about an individual HTTP request and response.
and it capsulated by ControllerBase
HttpContext.User it will represent Th Identity any object implement System.Security.Principal.IIdentity and it wrapped by Principal Class Object HttpContext Can Access to Any WebApplication Service by RequestServices.GetService<>() .... Identity It is Group OF Claims each claim represent kind of user data most two famous Identity is ClaimsIdentinty And Generic Identity Principal it will Cover the Identity and provide you utilities to check if is there claim or schema or policy ... etc
protected async override sealed Task<AuthenticateResult> HandleAuthenticateAsync()
{
var authorizationHeader = Request.Headers["Authorization"].ToString();
if (authorizationHeader != null && authorizationHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
var token = authorizationHeader.Substring("Basic ".Length).Trim();
var credentialsAsEncodedString = Encoding.UTF8.GetString(Convert.FromBase64String(token));
var credentials = credentialsAsEncodedString.Split(':');
try
{
User? user = await Users.Login(credentials[0], credentials[1]);
var identity = user;
List<Claim> claims = new() { new Claim("uid", user.user_info.uid), new Claim("token", user.user_info.token) };
foreach (var authorization in user.user_info.authorization)
{
claims.Add(new Claim(authorization.ToString("G"), "true"));
}
this.Context.Items.Add("user", new ClaimsPrincipal(identity));
ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims,"Basic"));
return await Task.FromResult(
AuthenticateResult.Success(new AuthenticationTicket(principal, "Basic")));
}
catch (Exception e)
{
Response.StatusCode = 401;
Response.Headers.Add("WWW-Authenticate", "Basic realm=\"thesmartcircuit.com\"");
return await Task.FromResult(AuthenticateResult.Fail("Invalid Authorization Header"));
}
}
Response.StatusCode = 401;
Response.Headers.Add("WWW-Authenticate", "Basic realm=\"thesmartcircuit.com\"");
return await Task.FromResult(AuthenticateResult.Fail("Invalid Authorization Header"));
}
then you can add new authoentication to this services of web application .
builder.Services.AddAuthentication("Basic")
.AddScheme<BasicAuthenticationOptions, BasicAuthenticationHandler>("Basic", null);
to apply this authentication on any minimal api
app.MapGet("/", () => "Hello World!").RequireAuthorization((b) => { b.RequireClaim("admin");});
//or
[Authorize(AuthenticationSchemes = "Basic")]
Authorizations And Policies
add authorization service with Admin policy
builder.Services.AddAuthorizationBuilder().AddPolicy("Admin", (pb) =>
{
pb.RequireAuthenticatedUser().AddAuthenticationSchemes("Basic").RequireRole("admin");
});
then you can use this authorized policy with minimal api like
[Authorize(Policy = "User")]
Authentication Handler
there are already built in auth handler service like cookies and ODB if you like to customize new you can inherit AuthenticationHandler
add roles
new Claim(ClaimTypes.Role,authorization.ToString("G"));
//or instean of using ClaimTypes.Role you can identify any string as role type by add it to roletype parameter in ClaimsIdentity