I do not have much code here
But I want to create my own validation for username that will not have duplicates.
Model:
[Table("User")]
public partial class User
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Column("userName")]
[StringLength(200)]
[AllValidation(ErrorMessage = "foo")]
[Required(ErrorMessage = "Username is a required field")]
public string UserName { get; set; } = null!;
[StringLength(50, MinimumLength = 3, ErrorMessage = "The password should be between 3 characters to 50")]
[Required(ErrorMessage = "Password is a required field")]
public string Password { get; set; } = null!;
//[Column(TypeName = "date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/MM/dd}")]
public DateTime? LastLogin { get; set; }
public string? Token { get; set; }
}
ValidationAttribute:
public class AllValidationAttribute : ValidationAttribute
{
private readonly TalkBackDbContext _context;
public AllValidationAttribute(TalkBackDbContext context)
{
_context = context;
}
public override string FormatErrorMessage(string name)
{
return _context.Users.SingleOrDefault(x => x.UserName == name)!.ToString()!;
}
}
I get an error when I try to insert ErrorMessage into an attribute
this is the error:
you can do this.
remove it from constructor and override IsValid method.
public class AllValidationAttribute : ValidationAttribute
{
private string username;
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var _context = (TalkBackDbContext )validationContext
.GetService(typeof(TalkBackDbContext ));
username = value.ToString();
if(!_context.Users.Any(cus => cus.UserName == value.ToString()))
{
return ValidationResult.Success;
}
else
{
return new ValidationResult
("Unique Name expected" + value.ToString());
}
}
public override string FormatErrorMessage(string name)
{
return "Expected Uniquename" + username;
}
}
I am developing a project with Entity Framework Core. I am using Code First approach. I have the below entities.
Account
public class Account
{
public Account()
{
Id = 0;
IsActive = true;
AccountRoles = new List<AccountRole>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public DateTime? LastLogin { get; set; }
public bool IsActive { get; set; }
public bool? IsSystemAdmin { get; set; }
public string PhotoUrl { get; set; }
public DateTime? CreateDate { get; set; }
public int? OrgId { get; set; }
public IList<AccountRole> AccountRoles { get; set; }
[NotMapped]
public string UserFullName
{
get
{
return $"{FirstName} {LastName}";
}
}
}
Role
public class Role
{
public Role()
{
Id = 0;
IsActive = true;
AccountRoles = new List<AccountRole>();
}
public int Id { get; set; }
public string Title { get; set; }
public bool? IsActive { get; set; }
public int? OrgId { get; set; }
public IList<AccountRole> AccountRoles { get; set; }
}
Account Role
public class AccountRole
{
public AccountRole()
{
Id = 0;
IsActive = true;
}
public int Id { get; set; }
public int AccountId { get; set; }
public int RoleId { get; set; }
public bool IsActive { get; set; }
public Account Account { get; set; }
public Role Role { get; set; }
}
Now I have written a LINQ query to join and group by to get results of all account information with Roles in comma separate. The query is below:
var userAccount = (from account in _db.Accounts
join accountRole in _db.AccountRoles on account.Id equals accountRole.AccountId into ars
from ar in ars.DefaultIfEmpty()
join role in _db.Roles on ar.RoleId equals role.Id
where
account.UserName == username
&& account.Password == password
group new { account, role } by new
{
account.Id,
account.FirstName,
account.LastName,
account.Email,
account.Mobile,
account.UserName,
account.PhotoUrl
} into ag
select new UserAccountInfo
{
AccountId = ag.Key.Id,
FirstName = ag.Key.FirstName,
LastName = ag.Key.LastName,
Email = ag.Key.Email,
Mobile = ag.Key.Mobile,
Username = ag.Key.UserName,
PhotoUrl = ag.Key.PhotoUrl,
Roles = string.Join(",", ag.Select(x => x.role.Title))
}).FirstOrDefault();
When call the API through Postman, I found the below errors. Can anyone help me to solve the problem.
System.InvalidOperationException: Processing of the LINQ expression
'GroupByShaperExpression: KeySelector: new {
Id = a.Id,
FirstName = a.FirstName,
LastName = a.LastName,
Email = a.Email,
Mobile = a.Mobile,
UserName = a.UserName,
PhotoUrl = a.PhotoUrl }, ElementSelector:new {
account = EntityShaperExpression:
EntityType: Account
ValueBufferExpression:
ProjectionBindingExpression: account
IsNullable: False
,
role = EntityShaperExpression:
EntityType: Role
ValueBufferExpression:
ProjectionBindingExpression: role
IsNullable: True } ' by 'RelationalProjectionBindingExpressionVisitor' failed. This may
indicate either a bug or a limitation in Entity Framework. See
https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed
information. at
CashFlow.Services.AccountService.ValidateLoginAsync(String username,
String password) in D:\Workspace\My
Projects\CashFlow\CashFlow-API\SourceCode\Libraries\Services\AccountService.cs:line
77 at Web.Controllers.AccountController.Login(LoginModel model) in
D:\Workspace\My
Projects\CashFlow\CashFlow-API\SourceCode\Web\Controllers\AccountController.cs:line
51 at
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper
mapper, ObjectMethodExecutor executor, Object controller, Object[]
arguments) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker
invoker, ValueTask`1 actionResultValueTask) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed
context) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown --- at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker
invoker, Task task, IDisposable scope) at
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint
endpoint, Task requestTask, ILogger logger) at
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext
context)
I have written the query in below way and it works fine.
var userAccount = (from account in _db.Accounts
join accountRole in _db.AccountRoles on account.Id equals accountRole.AccountId into ars
from ar in ars.DefaultIfEmpty()
join role in _db.Roles on ar.RoleId equals role.Id
where account.UserName == username && account.Password == password
select new UserAccountInfo
{
AccountId = account.Id,
FirstName = account.FirstName,
LastName = account.LastName,
Email = account.Email,
Mobile = account.Mobile,
Username = account.UserName,
PhotoUrl = account.PhotoUrl,
IsActive = account.IsActive,
Roles = role.Title
}).ToList().GroupBy(x => new
{
x.AccountId,
x.FirstName,
x.LastName,
x.Email,
x.Mobile,
x.Username,
x.PhotoUrl,
x.IsActive
}).Select(y => new UserAccountInfo
{
AccountId = y.Key.AccountId,
FirstName = y.Key.FirstName,
LastName = y.Key.LastName,
Email = y.Key.Email,
Mobile = y.Key.Mobile,
Username = y.Key.Username,
PhotoUrl = y.Key.PhotoUrl,
IsActive = y.Key.IsActive,
Roles = string.Join(",", y.Select(a => a.Roles))
});
Firstly I want to tell those who are going to mark this question as copied or existing that I have seen the solution exist but neither one help me in my case.
I am using my custom model which is going to register the users and at the time of generating token the credential user entered is going to match the record in my custom model if the user exist it return the token and if not it return the exception .
This is my custom model class.
public class userregistration
{
public int ID { get; set; }
[Required]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
This is my OAuthAuthrizationServerProvider
public class MyAutorization : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult(0);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (RegistrationRepos repo = new RegistrationRepos())
{
userregistration user = await repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
In the above section I am calling FindUser method from my RegistrationRepos which is going to return the user by comparing the credential with existing record.
The RegistrationRepos Class is here
public class RegistrationRepos : IDisposable
{
private MyContext context = new MyContext();
protected DbSet<userregistration> DbSet { get; set; }
public RegistrationRepos()
{
DbSet = context.Set<userregistration>();
}
public async Task<userregistration> FindUser(string userName, string password)
{
var user = await DbSet.FirstOrDefaultAsync(x => x.UserName == userName && x.Password == password);
return user;
}
public void Dispose()
{
context.Dispose();
}
}
This is all working fine when i debug the solution the user is returning fine if the credential matches and it is returning Null if the credential does not match , But instead of generating the token it is returning {"error":"invalid_grant"}
MY Owing Startup class is here.
public class owinstartup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // enables cors origin request
var myProvider = new MyAutorization();
OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
Provider = myProvider
};
app.UseOAuthAuthorizationServer(options);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
}
}
What is the issue behind the scene?
I have an application that allows users to log in via facebook. I am trying to save each user to my database using my WebApi. However, I am encountering this exception error: System.NullReferenceException: Object reference not set to an instance of an object. Can anyone see what I am doing incorrectly to cause this. Thanks.
CustomerService class:
public async Task<int> AddCustomer(Customer cust)
{
var data = JsonConvert.SerializeObject(cust);
var content = new StringContent(data, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("X-Giftworx-App", "Posworx");
var response = await client.PostAsync("http/my api address/api/Customer/Insert", content);
var result = JsonConvert.DeserializeObject<int>(response.Content.ReadAsStringAsync().Result);
return result;
}
Customer class:
public class Customer
{
public string Token { get; set; }
public bool Authenticated { get; set; }
public string SecretKey { get; set; }
public int StoreCustomerID { get; set; }
public string Number { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public object Address { get; set; }
public string Email { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
public string MobilePhone { get; set; }
public DateTime DOB { get; set; }
public object Phone { get; set; }
public object DeviceToken { get; set; }
public object Details { get; set; }
public object Gender { get; set; }
public bool IsError { get; set; }
public object ErrorMessage { get; set; }
public bool PhoneVerified { get; set; }
}
FacebookRender
public class FacebookRender : PageRenderer
{
CustomerService customerService;
public FacebookRender()
{
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator(
clientId: "my app client's id",
scope: "",
authorizeUrl: new Uri("https://www.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html")
);
auth.Completed += async (sender, eventArgs) =>
{
if (eventArgs.IsAuthenticated)
{
await AccountStore.Create().SaveAsync(eventArgs.Account, "FacebookProviderKey");
var accessToken = eventArgs.Account.Properties["access_token"].ToString();
var expiresIn = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);
var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, eventArgs.Account);
var response = await request.GetResponseAsync();
var obj = JObject.Parse(response.GetResponseText());
var id = obj["id"].ToString().Replace("\"", "");
var name = obj["name"].ToString().Replace("\"", "");
Customer cust = new Customer();
cust.Token = accessToken;
cust.Name = name;
await customerService.AddCustomer(cust);
App.NavigateToProfile(string.Format(name));
}
else
{
App.NavigateToProfile("Invalid Login");
}
};
activity.StartActivity(auth.GetUI(activity));
}
}
I have one list populated from Database with properties code_type , description , min_value, max_value, id etc
I want to create another lists from list 1 with filter condition value of code_type with only three properties
i.e description , min_value, & max value (code_type is not required). This revised list will be used for to bind View in MVC
\Kindly help for the same
Below is my code for the same. If code ="04" Then populate list for caste & so on. Can I Use Linq for the same?
public class MyPrefernce
{
public string memberid { get; set; }
public string code { get; set; }
public string description { get; set; }
public long? min_value { get; set; }
public long? max_value { get; set; }
public long? sysid { get; set; }
public string isChecked { get; set; }
public List<Caste> lcaste;
public List<MyPrefernce> getPrefence(long sysmemberid, string memberid)
{
List<MyPrefernce> lstObj = new List<MyPrefernce>();
string strQuery = "proc_Get_Member_Preference";
Connection cobj = new Connection();
string strConnection = cobj.getConnectionString();
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand(strQuery, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#nSysMemberId", sysmemberid);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
MyPrefernce obj = new MyPrefernce();
obj.code = ds.Tables[0].Rows[i]["code"].ToString();
obj.isChecked = ds.Tables[0].Rows[i]["isChecked"].ToString();
obj.min_value = Convert.ToInt64(ds.Tables[0].Rows[i]["min_value"]);
obj.max_value = Convert.ToInt64(ds.Tables[0].Rows[i]["max_value"]);
obj.sysid = sysid;
obj.memberid = memberid;
lstObj.Add(obj);
}
}
return lstObj;
}
}
public class Caste
{
public int sysId { get; set; }
public string decription { get; set; }
public string? isChecked { get; set; }
}
You should create a new class, defining the fields you need, and use auto-mapper to map the the fields between classes.