PontiacGTX
PontiacGTX
CC#
Created by PontiacGTX on 5/16/2024 in #help
Blazor sends wrong index to the event
No description
2 replies
CC#
Created by PontiacGTX on 9/22/2023 in #help
❔ trying to consume signalr through gateway
I am using the followin json in my gateway
{
"DownstreamPathTemplate": "/ws",
"UpstreamPathTemplate": "/",
"DownstreamScheme": "ws",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7200
}
]
},
{
"DownstreamPathTemplate": "/DriversHub/GetDriversDetail/{number}",
"DownstreamScheme": "ws",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7200
}
],
"UpstreamPathTemplate": "/upwg/DriversHub/GetDriversDetail/{number}",
"UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ]
}
{
"DownstreamPathTemplate": "/ws",
"UpstreamPathTemplate": "/",
"DownstreamScheme": "ws",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7200
}
]
},
{
"DownstreamPathTemplate": "/DriversHub/GetDriversDetail/{number}",
"DownstreamScheme": "ws",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7200
}
],
"UpstreamPathTemplate": "/upwg/DriversHub/GetDriversDetail/{number}",
"UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ]
}
and the front end has this code
8 replies
CC#
Created by PontiacGTX on 7/17/2023 in #help
✅ Serilog does not write logs to file
I have tried to configure it on the appsettings to write file but it doesnt
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Debug",
"Microsoft": "Information",
"System": "Information"
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}"
},
{

"Name": "File",
"Args": {

"pathFormat": "\\Employeeslog-{Date}.txt",
"rollOnFileSizeLimit": true,
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}",
"formatter": "Serilog.Formatting.Json.JsonFormatter",
"rollingInterval": "Day"
}
}
]
}
}
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Debug",
"Microsoft": "Information",
"System": "Information"
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}"
},
{

"Name": "File",
"Args": {

"pathFormat": "\\Employeeslog-{Date}.txt",
"rollOnFileSizeLimit": true,
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}",
"formatter": "Serilog.Formatting.Json.JsonFormatter",
"rollingInterval": "Day"
}
}
]
}
}
174 replies
CC#
Created by PontiacGTX on 5/30/2023 in #help
❔ itextsharp not rendering cells for a table
I am trying to display a cell in iTextSharp Version in a second page but it does not display the cells for some reason here is the code
float dpi = 100f;
float widthInches = (3900f * 1.1f) / dpi;
float heightInches = (2775f * 1.1f) / dpi;

// Increase the size of the Rectangle object by 10%
float width = widthInches * 1.1f * 72f;
float height = heightInches * 1.1f * 72f;

var pageSize = new iTextSharp.text.Rectangle(width, height);
var rect = new iTextSharp.text.Rectangle(width, height);

iTextSharp.text.Document document = new iTextSharp.text.Document(rect, 10f, 10f, 10f, 0f);
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(dest, System.IO.FileMode.Create));
document.Open();

document.NewPage();
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(model.CaraB["1"]);
image.SetAbsolutePosition(0, 0);
image.ScaleToFit(3400, 2400);
document.Add(image1);

PdfPTable table = new PdfPTable(2);
var cell = new PdfPCell(new iTextSharp.text.Phrase("Logros"));
cell.Colspan = 3;
cell.HorizontalAlignment = 1;

table.AddCell(cell);
table.AddCell("Logros");
table.AddCell("Horas");
document.Add(table);
float dpi = 100f;
float widthInches = (3900f * 1.1f) / dpi;
float heightInches = (2775f * 1.1f) / dpi;

// Increase the size of the Rectangle object by 10%
float width = widthInches * 1.1f * 72f;
float height = heightInches * 1.1f * 72f;

var pageSize = new iTextSharp.text.Rectangle(width, height);
var rect = new iTextSharp.text.Rectangle(width, height);

iTextSharp.text.Document document = new iTextSharp.text.Document(rect, 10f, 10f, 10f, 0f);
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(dest, System.IO.FileMode.Create));
document.Open();

document.NewPage();
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(model.CaraB["1"]);
image.SetAbsolutePosition(0, 0);
image.ScaleToFit(3400, 2400);
document.Add(image1);

PdfPTable table = new PdfPTable(2);
var cell = new PdfPCell(new iTextSharp.text.Phrase("Logros"));
cell.Colspan = 3;
cell.HorizontalAlignment = 1;

table.AddCell(cell);
table.AddCell("Logros");
table.AddCell("Horas");
document.Add(table);
the output is the following: https://i.stack.imgur.com/ni8WA.png
3 replies
CC#
Created by PontiacGTX on 5/17/2023 in #help
❔ problem trying to embed image sources with itextsharp converting html element to pdf
this code is showing that I am converting HTML TO pdf but only is able to embed the image source from the qr path which is an absolute path only located in a different folder but the other images arent showing up code in comments below
8 replies
CC#
Created by PontiacGTX on 2/23/2023 in #help
❔ "Invalid object name '...' "
I am trying to use a Database first(model) with Reverse engineering from EF Core Power tool) but I havent applied automatic migrations or anything) but the project tells me this table doesnt have such name but indeed it does, and I am not sure what else I could try
2 replies
CC#
Created by PontiacGTX on 2/12/2023 in #help
❔ In blazor server,in which Method should you usually implement JWT assignation
I have been wondering since I have used scaffolding por identity to receive the JWT token in J's but really the token isn't assigned on the Razor pages(scaffolding uses razor ) from the Http context into the User,since it seems to get lost as if they were using 2 different HttpContext,how would you usually do about assigning the JWT in a header with identity scaffolding?
2 replies
CC#
Created by PontiacGTX on 1/20/2023 in #help
❔ Restoring project with DB Schema only with EF and NET Framework
I am restoring a Database from a .bak file whenever I try to query something from DB, there is a lack of attributes and the context does not use fluent api.... so what can i do to restore this project from the existing DB and Code/models entities without writing all those attributes/fluent validation?
3 replies
CC#
Created by PontiacGTX on 12/5/2022 in #help
❔ Invalidating Claims from previous sessions claims when Logging In
I am using ASP.NET Core 2.0 AND IdentityServer(4?) and I need to invalidate the previous login when this user logins but I see that calling UpdateSecurityStampAsync logs me out from all previous login even tho I make it login once more...(this event is called everytime it logins but i dont know hwo ot invalidate the previous logins, do you mind helping me? thank you
o.Events.OnSigningIn = async ctx =>
{
Console.WriteLine("SignIn");
var principal = ctx.Principal;
if ((ctx.Principal?.Identity is ClaimsIdentity claimIdentity))
{
var mgr = ctx.HttpContext.RequestServices.GetRequiredService<SignInManager<ApplicationUser>>();
var user = await mgr.UserManager.FindByNameAsync(claimIdentity.Name);
var res =mgr.UserManager.UpdateSecurityStampAsync(user).Result;
if(res.Succeeded)
{
if(!mgr.IsSignedIn(ctx.Principal))
await mgr.SignInAsync(user, true);
}

}

};
o.Events.OnSigningIn = async ctx =>
{
Console.WriteLine("SignIn");
var principal = ctx.Principal;
if ((ctx.Principal?.Identity is ClaimsIdentity claimIdentity))
{
var mgr = ctx.HttpContext.RequestServices.GetRequiredService<SignInManager<ApplicationUser>>();
var user = await mgr.UserManager.FindByNameAsync(claimIdentity.Name);
var res =mgr.UserManager.UpdateSecurityStampAsync(user).Result;
if(res.Succeeded)
{
if(!mgr.IsSignedIn(ctx.Principal))
await mgr.SignInAsync(user, true);
}

}

};
2 replies
CC#
Created by PontiacGTX on 11/17/2022 in #help
❔ how to logout specific user with identityserver
I am trying to logout an specific user from previous identity user sessions, so what could I do to specifically logout one user when it logins?
4 replies
CC#
Created by PontiacGTX on 11/8/2022 in #help
❔ API doesnt return dynamic object in ASP.NET Core 2.0
I am looking to return a list from a Dynamic linq query but the problem comes when returning the list it doesnt return anything on swagger the code is like
var result = _ctx.AccionFormativa
.Include(x => x.OfertaFormativa)
.Include(x => x.Modalidad)
.Include(x => x.ProgramasFormacion)
.Include(x => x.StatusCurso)
.Include(x => x.Centro)
.ThenInclude(x => x.DireccionCentro)
.Include(x => x.Ambito)
.GroupBy(fields, "it")
.ToDynamicList()
.Select(x => (new DynamicExpando(x)).GetCurrentObject);
var result = _ctx.AccionFormativa
.Include(x => x.OfertaFormativa)
.Include(x => x.Modalidad)
.Include(x => x.ProgramasFormacion)
.Include(x => x.StatusCurso)
.Include(x => x.Centro)
.ThenInclude(x => x.DireccionCentro)
.Include(x => x.Ambito)
.GroupBy(fields, "it")
.ToDynamicList()
.Select(x => (new DynamicExpando(x)).GetCurrentObject);
5 replies
CC#
Created by PontiacGTX on 11/3/2022 in #help
How to define an Anonymous type lambda parameter in Linq Expression
0 I had found in a stackoverflow post how they created an anonymous object but I would like to create a Lambda expression which select only a field within an object to be able to Group by Id currently the coude from here Linq: Group by multiple columns using Expression-tree syntax creates a new type but I would like that it could be able to work on GroupBy linq method....
public static Type CreateNewType(List<PropertyInfo> props)
{
AssemblyName asmName = typeof(Program).Assembly.GetName();
AssemblyBuilder dynamicAssembly = AssemblyBuilder
.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("MyAsm");
TypeBuilder dynamicAnonymousType = dynamicModule
.DefineType("MyType", TypeAttributes.Public);

foreach (var p in props)
{
dynamicAnonymousType.DefineField(p.Name, p.PropertyType, FieldAttributes.Public);
}
return dynamicAnonymousType.CreateType();
}
public static Type CreateNewType(List<PropertyInfo> props)
{
AssemblyName asmName = typeof(Program).Assembly.GetName();
AssemblyBuilder dynamicAssembly = AssemblyBuilder
.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("MyAsm");
TypeBuilder dynamicAnonymousType = dynamicModule
.DefineType("MyType", TypeAttributes.Public);

foreach (var p in props)
{
dynamicAnonymousType.DefineField(p.Name, p.PropertyType, FieldAttributes.Public);
}
return dynamicAnonymousType.CreateType();
}
using this type using a single field(I only need the field rather the class... groups by an entity MyType which doesnt exist...it should group by either of the entities/fields in my class linq.net-coresystem.reflection
1 replies
CC#
Created by PontiacGTX on 11/2/2022 in #help
Incorrect dynamic lambda generation
I have setup a method to dynamically create a lambda to select a parameter and create a new object based on certain fields the code looks like when generated
Param_0 => new MyType() {Amount = Param_0.Amount, Category = Param_0.Category, PaymentMode = Param_0.PaymentMode}
Param_0 => new MyType() {Amount = Param_0.Amount, Category = Param_0.Category, PaymentMode = Param_0.PaymentMode}
but shows an error when using the compiled lambda expression.... here is the code
public Expression<Func<TSource, object>> DynamicLambda<TSource>
(ParameterExpression parameterExpression = null, params string[] properties)
{
var entityType = typeof(TSource);
var props = properties.Select(x => entityType.GetProperty(x)).ToList();
var source = parameterExpression ==null? Expression.Parameter(entityType, "x"): parameterExpression;

// create x=> new myType{ prop1 = x.prop1,...}
var newType = CreateNewType(props);
var binding = props.Select(p => Expression.Bind(newType.GetField(p.Name),
Expression.Property(source, p.Name))).ToList();
var body = Expression.MemberInit(Expression.New(newType), binding);
var selector = Expression.Lambda<Func<TSource, object>>(body, source);
return selector;
}
public static Type CreateNewType(List<PropertyInfo> props)
{
AssemblyName asmName = new AssemblyName("MyAsm");
AssemblyBuilder dynamicAssembly = AssemblyBuilder
.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("MyAsm");
TypeBuilder dynamicAnonymousType = dynamicModule
.DefineType("MyType", TypeAttributes.Public);

foreach (var p in props)
{
dynamicAnonymousType.DefineField(p.Name, p.PropertyType, FieldAttributes.Public);
}
return dynamicAnonymousType.CreateType();
}
public Expression<Func<TSource, object>> DynamicLambda<TSource>
(ParameterExpression parameterExpression = null, params string[] properties)
{
var entityType = typeof(TSource);
var props = properties.Select(x => entityType.GetProperty(x)).ToList();
var source = parameterExpression ==null? Expression.Parameter(entityType, "x"): parameterExpression;

// create x=> new myType{ prop1 = x.prop1,...}
var newType = CreateNewType(props);
var binding = props.Select(p => Expression.Bind(newType.GetField(p.Name),
Expression.Property(source, p.Name))).ToList();
var body = Expression.MemberInit(Expression.New(newType), binding);
var selector = Expression.Lambda<Func<TSource, object>>(body, source);
return selector;
}
public static Type CreateNewType(List<PropertyInfo> props)
{
AssemblyName asmName = new AssemblyName("MyAsm");
AssemblyBuilder dynamicAssembly = AssemblyBuilder
.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("MyAsm");
TypeBuilder dynamicAnonymousType = dynamicModule
.DefineType("MyType", TypeAttributes.Public);

foreach (var p in props)
{
dynamicAnonymousType.DefineField(p.Name, p.PropertyType, FieldAttributes.Public);
}
return dynamicAnonymousType.CreateType();
}
6 replies
CC#
Created by PontiacGTX on 10/31/2022 in #help
HTTP Request throws exception when invoking controller
see attached file, I cant understand why it doesnt injects the service
6 replies
CC#
Created by PontiacGTX on 10/28/2022 in #help
Cannot resolve constructor for String type. Using Unity container
I am sending a string to StringCon Class but it doesnt resolve when injecting into HomeController... here is the code
var con = ConfigurationManager.AppSettings["MyConnectionString"];
var paramStringCon = new ParameterOverrides();
container.RegisterType<StringCon>();
container.Resolve<StringCon>(new ResolverOverride[]
{
new ParameterOverride("str", con)
});

var logProd = container.Resolve(typeof(Microsoft.Extensions.Logging.ILogger<ProductoRepository>));

container.RegisterType<ProductoRepository>(nameof(ProductoRepository),
new InjectionConstructor(container.Resolve<StringCon>(new ResolverOverride[]
{
new ParameterOverride("str", con)
}), logProd));
new UnityDependencyResolver(container);
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
var con = ConfigurationManager.AppSettings["MyConnectionString"];
var paramStringCon = new ParameterOverrides();
container.RegisterType<StringCon>();
container.Resolve<StringCon>(new ResolverOverride[]
{
new ParameterOverride("str", con)
});

var logProd = container.Resolve(typeof(Microsoft.Extensions.Logging.ILogger<ProductoRepository>));

container.RegisterType<ProductoRepository>(nameof(ProductoRepository),
new InjectionConstructor(container.Resolve<StringCon>(new ResolverOverride[]
{
new ParameterOverride("str", con)
}), logProd));
new UnityDependencyResolver(container);
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
17 replies
CC#
Created by PontiacGTX on 9/8/2022 in #help
how to implement webrtc for blazor
how can I use webrtc inside blazor server? is there a way one couuld implement it using js , maybe someoe could share me the base method used in js so i can export them?
11 replies
CC#
Created by PontiacGTX on 8/22/2022 in #help
how to create a jwt for an existing user in identity
I am looking to create a new JWT and validate it... for using tiwht signalr. so i want to know how to fill these fields...
app.MapPost("/Security/Token/Create",
[AllowAnonymous]
async ([FromBody]WebAppMeet.Data.Models.UserTokenRequest user, [FromServices] SignInManager<AppUser> signInManager)
=>
{
var appUser = await signInManager.UserManager.Users.FirstOrDefaultAsync(x => x.UserName == user.UserName);

if ((await signInManager.PasswordSignInAsync(appUser, user.Password, true, false)).Succeeded)
{
var issuer = builder.Configuration["Jwt:Issuer"];
var audience = builder.Configuration["Jwt:Audience"];
var key = Encoding.ASCII.GetBytes(builder.Configuration["Jwt:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim("Id", Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Email, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
}),
Expires = DateTime.UtcNow.AddMinutes(5),
Issuer = issuer,
Audience = audience,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwtToken = tokenHandler.WriteToken(token);
var stringToken = tokenHandler.WriteToken(token);
return Results.Ok(stringToken);
}
return Results.Unauthorized();
});
app.MapPost("/Security/Token/Create",
[AllowAnonymous]
async ([FromBody]WebAppMeet.Data.Models.UserTokenRequest user, [FromServices] SignInManager<AppUser> signInManager)
=>
{
var appUser = await signInManager.UserManager.Users.FirstOrDefaultAsync(x => x.UserName == user.UserName);

if ((await signInManager.PasswordSignInAsync(appUser, user.Password, true, false)).Succeeded)
{
var issuer = builder.Configuration["Jwt:Issuer"];
var audience = builder.Configuration["Jwt:Audience"];
var key = Encoding.ASCII.GetBytes(builder.Configuration["Jwt:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim("Id", Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Email, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
}),
Expires = DateTime.UtcNow.AddMinutes(5),
Issuer = issuer,
Audience = audience,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwtToken = tokenHandler.WriteToken(token);
var stringToken = tokenHandler.WriteToken(token);
return Results.Ok(stringToken);
}
return Results.Unauthorized();
});
here is the token generation method so what do I use in Jwt:Issuer Jwt:Audience?
78 replies
CC#
Created by PontiacGTX on 8/18/2022 in #help
Signalr not sending message(s) to specific user(s)
in the hub i have setup this signature for a method
public async Task SendMessage(string sender, string receiver, string message)
{
await Clients.Users(sender, receiver).SendAsync("ReceiveMessage", receiver, message);
}
public async Task SendMessage(string sender, string receiver, string message)
{
await Clients.Users(sender, receiver).SendAsync("ReceiveMessage", receiver, message);
}
and in the client side(the page on blazor server) i have set this up for the ReceiveMessage method
public async Task OnInitializeAsync()
{

if(hub is null)
hub = new HubConnectionBuilder()
.WithUrl(_NavigationManager.ToAbsoluteUri("/ConnectionsHub"))
.Build();
hub.On<string, string>($"ReceiveMessage", // this is never triggered
async (sender, message) =>
{
var encodedMsg = $"{sender}: {message}";
ChatBox.MessageList.Add(encodedMsg);
await ChatBox.ComponentStateHasChanged();
});
hub.ServerTimeout = TimeSpan.FromMilliseconds(100000);
await hub.StartAsync();
}
public async Task OnInitializeAsync()
{

if(hub is null)
hub = new HubConnectionBuilder()
.WithUrl(_NavigationManager.ToAbsoluteUri("/ConnectionsHub"))
.Build();
hub.On<string, string>($"ReceiveMessage", // this is never triggered
async (sender, message) =>
{
var encodedMsg = $"{sender}: {message}";
ChatBox.MessageList.Add(encodedMsg);
await ChatBox.ComponentStateHasChanged();
});
hub.ServerTimeout = TimeSpan.FromMilliseconds(100000);
await hub.StartAsync();
}
and how I call this method
private async Task SendMessage(string message)
{
if(string.IsNullOrEmpty(message))
{
await PrintMessage("Error", "Cannot send an empty message");
return;
}
if (hub is not null)
{

foreach (var user in _UserList)
{
await hub.SendAsync("SendMessage", ThisUser.Email, user.User.Email,ChatBox.Message);
}

// await ChatBox.ComponentStateHasChanged();
}
}
private async Task SendMessage(string message)
{
if(string.IsNullOrEmpty(message))
{
await PrintMessage("Error", "Cannot send an empty message");
return;
}
if (hub is not null)
{

foreach (var user in _UserList)
{
await hub.SendAsync("SendMessage", ThisUser.Email, user.User.Email,ChatBox.Message);
}

// await ChatBox.ComponentStateHasChanged();
}
}
123 replies