How to get the current UserID - asp.net-core

I try to get the current User Id in my action method of my Home Controller.
public async Task<IActionResult> Index(int? evenementId, string? accepteRV)
{
string userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (evenementId != null)
{
StatutEvenement statutEvenement = accepteRV == "true" ? StatutEvenement.Accepté : StatutEvenement.Refusé;
// Mise à jour de l'évènement destiné au vendeur
_traitement.MAJEvenement(evenementId , statutEvenement);
// Récupération de l'évènement en cours
Evenement evenement = await _context.Evenements.AsNoTracking().FirstAsync(e => e.ID == evenementId);
// Enregistrement de l'évènement destiné à l'acheteur
_traitement.InsereEvenement(TypeEvenement.Info, userID, statutEvenement, DateTime.Now, null, evenement.CreePar, evenement.AgendaID, evenement.AnnonceID);
await _context.SaveChangesAsync();
// Envoyer un mail pour acceptation/refus du rendez-vous
The User.FindFirstValue works in other controllers but in this one, I have the compilation error message :
Compiler Error CS0841 : Cannot use local variable 'User' before it is declared
I think it's because it's the start controller but I don't know how to solve the problem.
Please help me,
Thanks.

Related

Problem with data showed in a recycler view when user log out and log in firebase realtime

I have a weird behavior with a recyclerview. The app is a kind of social network where users publish post and I look for all the post of all users that authentifated user has bookmarked. My app works fine the first time an user logins. But if the user log out, and later log in, the first post it's not showed. But If the user start over again the app it works properly. I'm really lost why it's happening.
This is a picture of part of my database, but I can read the correctly. I think the problem has to be with the recyclew view.But not sure
Here is the code where I search the data. I use two functions buscarUsuarioSeguidos which store an array with the list of user's id that later I use to look for user's posts with mostrarPublicacionesSeguidas.
private fun buscarUsuariosSeguidos(usuarioUid:String){
//BUSCAMOS EN LA TABLA SEGUIR CADA ENTRADA DONDE APAREZCA COMO SEGUIDOR EL USUARIO AUTENTIFICADO
val seguidoresRef= referenciaBD.child("Seguir").child(usuarioUid).child("Siguiendo")
// LIMPIAMOS LAS PUBLICACIONES SEGUIDAS
usuariosSeguidosUid?.clear()
//CARGAMOS LAS PUBLICACIONES EN EL RECYCLERVIEW DATACHANGE SE ENCARGA DE CARGAR LOS DATOS
seguidoresRef.addValueEventListener(object :ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
for (snap in snapshot.children)
//RECUPERAMOS LA CLAVE DE CADA CHILDREN QUE REALMENTE ES EL UID DEL USUARIO
snap.key?.let { (usuariosSeguidosUid as ArrayList<String>).add(it) }
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
//ESTA FUNCION BUSCA LAS PUBLICACIONES DE TODOS LOS USUARIOS QUE SIGUE EL USUARIO AUTENTIFICADO
private fun mostrarPublicacionesSeguidas() {
//CREAMOS LA QUERY DE BUSQUEDA QUE APUNTA A LA TABLA PUBLICACIONES
val publicacionRef = referenciaBD.child("Publicaciones")
//listaPublicaciones?.clear()
publicacionRef.addValueEventListener(object : ValueEventListener {
//CARGAMOS TODOS LOS DATOS DE LA TABLA POSTS EN EL RECYCLERVIEW DATACHANGE SE ENCARGA DE CARGAR LOS DATOS
override fun onDataChange(snapshot: DataSnapshot) {
//LIMPIAMOS LA LISTA DE PUBLICACIONES
listaPublicaciones?.clear()
for (snapshot in snapshot.children) {
// SE VA RECUPÈRANDO CADA PUBLICACION
val publicacion = snapshot.getValue(Publicacion::class.java)
// Y SE RECORRE EL ARRAY CON LOS UID DE LOS USUARIOS SEGUIDOS PARA VER SI SE DEBE MOSTRAR
for (usuarioUid in usuariosSeguidosUid as ArrayList<String>)
// EN CASO DE QUE SE ENCUENTRE CONICIDENCIA SE AÑADE LA PUBLICACION A SU LISTA
if (usuarioUid == publicacion!!.nombreUsuario ){
listaPublicaciones?.add(publicacion!!)
}
}
//invertimos la lista para que los ultimos posts esten os primero
listaPublicaciones!!.reverse()
//SE ACTUALIZA EL LISTADO DE PUBLICACIONES MOSTRADOR EN EL ADAPTADOR
publicacionAdaptador?.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
//VER QUE HACE
}
})
}
And this is the function to log out.
private fun desconectarUsuario(){
FirebaseAuth.getInstance().signOut()
val intent = Intent(context,IdentificarseActivity::class.java)
startActivity(intent)
}
Thank

VALIDATIONS WITH FLUENT VALIDATION

I need to do a specific validation with Fluent Validation, but I have read his documentation a few times and I did not find a solution for that. My validation class currently looks like this:
using FluentValidation;
using System;
namespace SaleTheaterTickets.Models.ViewModelValidators
{
public class GeneratedTicketViewModelValidator : AbstractValidator<GeneratedTicketViewModel>
{
public GeneratedTicketViewModelValidator()
{
RuleFor(x => x.CustomerName)
.NotEmpty().WithMessage("Digite o nome do cliente");
// .Matches("/ ^[a-zA-Z çÇÁáÉéÍíÓóÚúÃã']+$/i").WithMessage("Nome aceita apenas de A-Z");
RuleFor(x => x.BirthDate)
.NotEmpty().WithMessage("Digite a data de nascimento")
.Must(ValidDate).WithMessage("Data de nascimento tem que ser menor que hoje");
//.DependentRules(() => {
// RuleFor(x => x.NeedyChild)
// .Must(ValidQuestion).WithMessage("Resposta inválida: Você não é criança");
//});
RuleFor(x => x.FormOfPayment)
.NotEmpty().WithMessage("Selecione a forma de pagamento");
RuleFor(x => x.Seat)
.NotEmpty().WithMessage("Escolha a poltrona")
.NotNull().WithMessage("Poltrona inválida");
RuleFor(x => x.NeedyChild)
.NotEmpty().WithMessage("Responda a pergunta");
}
private static bool ValidDate(DateTime date)
{
if(date < DateTime.Now.Date)
{
return true;
}
return false;
}
//private static bool DiscountChild(DateTime date)
//{
// int age = DateTime.Now.Year - date.Year;
// if (age >= 2 && age <= 12)
// {
// return true;
// }
// return false;
//}
//private static bool ValidTotalChild(decimal Total)
//{
//}
//private static bool ValidQuestion( resposta)
//{
// int idade = DateTime.Now.Year - date.Year;
// bool _resposta = Convert.ToBoolean(resposta);
// if(_resposta == true)
// {
// if(idade >= 2 && idade <=12)
// {
// return true;
// }
// }
// return false;
//}
}
}
This system is for the sale of theater tickets, so I need the total to receive a 50% discount on the ticket value when the age of the people who are buying the ticket is between 2 and 12 years old and equal to or over 60 years old. In other words, children have a discount and the elderly too. However in my system I keep the birthday and not the age itself. I tried to use the must but the must returns bool (true or false) not allowing me to assign a value if the age is equal to both. can anybody help me?

MVC Entity Framework, Query returns null

Hi guys can you help me understand why i keep getting a null instead of get the value.
Need to receive the saidaservicoid to be able to update. I receive the value from the view but can't update elemento. Stays null.
Thanks in advance for the help.
[Database]
[elementoRepository]
public async Task UpdateElementoSaidaServicosAsync(AddSaidasServicoViewModel model)
{
var saidaServico = await _context.SaidaServicos.FindAsync(model.SaidaServicoId);
var elemento = await _context.Elementos.FindAsync(model.ElementoId);
if (elemento == null)
{
return;
}
var updateElementoSaida = _context.Elementos.Where(e => e.Id == model.ElementoId).FirstOrDefault();
if (updateElementoSaida == null)
{
updateElementoSaida = new Elemento
{
saidaServico = saidaServico,
};
_context.Elementos.Update(updateElementoSaida);
}
else
{
int SaidaServicos = model.SaidaServicoId;
updateElementoSaida.saidaServico = saidaServico;
}
await _context.SaveChangesAsync();
return;
}
Ok. the best way that i found to solve this issue was to get the last ID.
int SaidaServicos = _context.SaidaServicos.Max(item => item.Id);

Groovy - Define variable where the variable name is passed by another variable

I want define a variable in groovy with where the variable name is passed by another variable.
Something like.
def runExtFunc(varName){
def varName // => def abc
varName = load 'someFile.groovy' // abc = load 'someFile.groovy'
varName."$varName"() // -> abc.abc() (run function defined in File)
}
[...]
runExtFunc('abc') // -> abc.abc() (Function abc defined in File)
[...]
runExtFunc('xyz') // -> xyz.xyz() (Function xyz defined in File)
[...]
Sadly def varName defines the variable varName and not abc. When I call runExtFunc twice an error occoures bacause varName is already defined.
I also tried
def runExtFunc(varName){
def "${varName}" // => def abc
[...]
"${varName}" = load 'someFile.groovy'
[...]
}
which doesn't work either.
Any suggestions?
This is the wrong approach. Normally you would use List, Map or Set data structures, which allow you to save a collection and access specific elements in the collection.
List allows you to hold specific values (unique or non-unique). Set allows you to hold specific values (all unique). Map allows you to have Key, Value pairs (Key must be unique) .
Read more here
groovy list,
groovy map
Try this (if I understand you correctly):
def dummyFunc(varName) {
new GroovyShell(this.binding).evaluate("${varName}")
}
dummyFunc('abc')
abc = "Hello there"
println abc
Prints
Hello there
See here
https://godless-internets.org/2020/02/14/extracting-jenkins-credentials-for-use-in-another-place/
secret_var="SECRET_VALUE_${secret_index}"
aws ssm put-parameter --name ${param_arn} --type "SecureString" --value ${!secret_var} --region us-east-2 --overwrite
I'm entering here a code sample we've done.
Please, feel free to comment.
http://groovy-lang.org/syntax.html
https://godless-internets.org/2020/02/14/extracting-jenkins-credentials-for-use-in-another-place/
def int fileContentReplaceDynamic(String filePathVar, String envTail = "",
String [] keysToIgnore = new String[0]){
def filePath = readFile filePathVar
def lines = filePath.readLines()
//def regex = ~/\b__\w*\b/
String regex = "__(.*?)__"
ArrayList credentialsList = new ArrayList();
ArrayList<String> keysToIgnoreList = new ArrayList<String>(Arrays.asList(keysToIgnore));
for (line in lines){
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE)
Matcher matcher = pattern.matcher(line)
while (matcher.find()){
String credKeyName = matcher.group().replaceAll("__","")
if ((! credentialsList.contains(credKeyName)) &&
(! keysToIgnoreList.contains(credKeyName))) {
credentialsList.add(credKeyName)
} else {
log.info("Credencial ignorada o ya incluida: ${credKeyName}")
}
}
}
if(credentialsList.size() <= 0){
log.info("No hay variables para aplicar transformada")
return 0
}
log.info("Numero de credenciales encontradas a sustituir: " + credentialsList.size())
String credentialsListString = String.join(", ", credentialsList);
log.info("Credenciales: " + credentialsListString)
def credsRequest = null
for(def credKeyName in credentialsList){
// Retrieve the values of the variables by environment tail name.
String credKeyNameByEnv = "${credKeyName}";
if ((envTail != null) && (! envTail.trim().isEmpty())) {
credKeyNameByEnv = credKeyNameByEnv + "-" + envTail.trim().toUpperCase();
}
// Now define the name of the variable we'll use
// List<org.jenkinsci.plugins.credentialsbinding.MultiBinding>
// Tip: java.lang.ClassCastException:
// org.jenkinsci.plugins.credentialsbinding.impl.BindingStep.bindings
// expects class org.jenkinsci.plugins.credentialsbinding.MultiBinding
String varName = "var_${credKeyNameByEnv}"
if (credsRequest == null) {
// Initialize
credsRequest = [string(credentialsId: "${credKeyNameByEnv}", variable: "${varName}")]
} else {
// Add element
credsRequest << string(credentialsId: "${credKeyNameByEnv}", variable: "${varName}")
}
}
int credsProcessed = 0
def passwordsRequest = null
StringBuilder sedReplacements = new StringBuilder();
// Now ask jenkins to fill in all variables with values
withCredentials(credsRequest) {
for(def credKeyName in credentialsList){
String credKeyVar = "var_${credKeyName}"
log.info("Replacing value for credential ${credKeyName} stored in ${credKeyVar}")
String credKeyValueIn = "${!credKeyVar}"
String credKeyValue = null;
if ("empty_string_value".equals(credKeyValueIn.trim())) {
credKeyValue = "";
} else {
credKeyValue = credKeyValueIn.replaceAll(/(!|"|#|#|\$|%|&|\/|\(|\)|=|\?)/, /\\$0/)
}
if (passwordsRequest == null) {
// Initialize
passwordsRequest = [[password: "${credKeyValue}" ]]
} else {
// Add element
passwordsRequest << [password: "${credKeyValue}" ]
}
sedReplacements.append("s/__${credKeyName}__/${credKeyValue}/; ")
credsProcessed++
}
}
wrap([$class: "MaskPasswordsBuildWrapper", varPasswordPairs: passwordsRequest ]){
String sedReplacementsString = sedReplacements.toString().trim();
if (sedReplacementsString.endsWith(";")) {
sedReplacementsString = sedReplacementsString.substring(0, sedReplacementsString.length() -1);
sedReplacementsString = sedReplacementsString + "g;"
}
sh """sed -i "${sedReplacementsString}" ${filePathVar}"""
}
log.info("Finaliza la transformada. Transformados: ${credsProcessed}/${credentialsList.size()} ")
if (credsProcessed != credentialsList.size()) {
log.info("Hay credenciales que no se han podido encontrar en el vault de Jenkins.")
log.info("Si estas guardando cadenas vacias en credenciales, guarda en su lugar el valor 'empty_string_value'.");
return -1
}
return 0;
}

ASP.net Entity Framework Check if exists in database

I have VS2015, entity framework 6. I have a database with one table (Logins)
FirstName, lastName, Birthdate, email, password
I also have a textbox(s), button
tbEmail tbpass and btnLogin
How do I check if the users email in the textbox matches one in the database?
So far I have:
protected void btnLogin_Click(object sender, EventArgs e)
{
Logins Log = new Logins();
using (LoginDataEntities lg = new LoginDataEntities())
{
string #email = tbUsernameL.Text;
string #password = tbPassL.Text;
var logged = from L in lg.Logins
where L.Username == #email
&& L.Pass == #password
select L.Username;
if (logged != null)
{
lblSuccess.Visible = true;
}
else
{
lblFail.Visible = true;
}
}
}
However, its not working and always enables the success label. How do I fix this?
Try it once with the following snippet:
using (LoginDataEntities lg = new LoginDataEntities())
{
string #email = tbUsernameL.Text;
string #password = tbPassL.Text;
var logged = lg.Logins
.SingleOrDefault(l=> l.Username == #email && l.Pass == #password);
if (logged != null) // update
{
lblSuccess.Visible = true;
}
else
{
lblFail.Visible = true;
}
}
Alternatively, can you also look at the following example again:
http://www.c-sharpcorner.com/uploadfile/b19d5a/custom-user-login-and-registration-page-in-Asp-Net-mvc3-with-razor-and-entity-framework/
Or you refactorisiers the VS template with Individual User Accounts