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;
}
}
Related
Entity:
public class AccountEntity: MasterEntity
{
public AccountType AccountType { get; set; }
public DepartmentEntity Department { get; set; }
public string LeadSource { get; set; }
public ResourceEntity AccountManager { get; set; }
public AccountQualificationStatus QualificationStatus { get; set; }
}
public class DepartmentEntity : MasterEntity
{
}
public class ResourceEntity : MasterEntity
{
public string Email { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
public abstract class MasterEntity: Entity
{
public string Name { get; set; }
public string Code { get; set; }
}
Model
public class Accounts
{
private string depname;
public int Id { get; set; }
public string Name { get; set; }
public int Code { get; set; }
public string AccountType { get; set; }
public string Department { get; set; }
}
public AccountMappingProfile()
{
CreateMap<Account, AccountTest>().ReverseMap();
CreateMap<Opportunity, OpportunityEntity>().ReverseMap();
CreateMap<Accounts, AccountEntity>().ReverseMap();
CreateMap<Resource, ResourceEntity>().ReverseMap();
CreateMap<Projects, ProjectEntity>().ReverseMap();
}
public static class AccountMapper
{
private static readonly Lazy<IMapper> Lazy = new Lazy<IMapper>(() =>
{
var config = new MapperConfiguration(cfg => {
cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
cfg.AddProfile<AccountMappingProfile>();
});
var mapper = config.CreateMapper();
return mapper;
});
public static IMapper Mapper => Lazy.Value;
}
I am able to fetch resource details .while I am fetching accounts with department and resources, the value for department is giving me null after automapping.
public async Task<IEnumerable<Accounts>> GetAccounts()
{
try
{
var accounts = await _context.Account.Include(c=>c.Director).ToListAsync();
// accounts = await _context.Account.Include(c => c.Department).ToListAsync();
return AccountMapper.Mapper.Map<List<Accounts>>(accounts);
}
}
controller method:
public async Task<IEnumerable<Accounts>> GetClients()
{
var result = await _repository.GetAccounts();
return result;
}
if I am uncommenting the code to include department, its is giving the object name.
I need to get the department details as well. how can i get that.Department entity is inheriting master entity.
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 create two class in my model and create relation many to many by Entity
in sql my classes is created tables Properly
when i try to insert data in this table get show error "Object reference not set to an instance of an object." my cod is:
public class News
{
public int ID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Date { get; set; }
public virtual Picture Picture { get; set; }
public virtual NewsType NewsType { get; set; }
public ICollection<Tag> Tag { get; set; }
public News(int id, string title, string content, DateTime date)
{
this.ID = id;
this.Title = title;
this.Content = content;
this.Date = date;
}
public News()
{
}
}
public class Tag
{
public int ID { get; set; }
public string Title { get; set; }
public ICollection<News> News { get; set; }
public Tag()
{
}
}
public class DatabaseContext : DbContext
{
public DatabaseContext()
: base("News")
{
}
static DatabaseContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DatabaseContext>());
}
public DbSet<News> newsInfo { get; set; }
public DbSet<Picture> pictures { get; set; }
public DbSet<NewsType> Types { get; set; }
public DbSet<Tag> Tags { get; set; }
}
[HttpPost]
public ActionResult AddNews(NewsViewModel newsInfo)
{
using (Models.DatabaseContext dbContext = new DatabaseContext())
{
ViewData["Type"] = new SelectList(dbContext.Types.ToList(), "Id", "Title");
}
if (!ModelState.IsValid)
{
return View();
}
else
{
Models.DatabaseContext dbContext = new Models.DatabaseContext();
Models.News news = new Models.News();
news.Title = newsInfo.Title;
news.Content = newsInfo.Content;
news.Date = DateTime.Now;
string newsinput = newsInfo.Tag.cleanTag();
string[] tags = new string[] { };
if (newsinput != null)
{
tags = newsinput.Split(',');
}
foreach (string item in tags)
{
Tag findTag = dbContext.Tags.Where(x => x.Title == item).FirstOrDefault();
if (findTag != null)
{
news.Tag.Add(findTag)
////////////////////////show error in this line
}
}
news.NewsType = dbContext.Types.Find(Convert.ToInt32(Request.Form["rdb"]));
dbContext.newsInfo.Add(news);
dbContext.SaveChanges();
return View();
}
public class LearnerInfo
{
public string Id { get; set; }
public string Name { get; set; }
public LearnerInfo(string id, string name)
{
this.Id = id;
this.Name = name;
}
}
public class LearnerCourse
{
public string Id { get; set; }
public string ExpiredCount { get; set; }
public string Soonduecount { get; set; }
public string Currentmonthcount { get; set; }
public string Currentmonthplus1count { get; set; }
public string Currentmonthplus2count { get; set; }
public string Currentmonthplus3count { get; set; }
public string Currentmonthplus4count { get; set; }
public string Currentmonthplus5count { get; set; }
public string Subtotal { get; set; }
public LearnerCourse(string id, string exp, string soonDue, string current, string plus1, string plus2,
string plus3, string plus4, string plus5)
{
this.Id = id;
this.ExpiredCount = exp;
this.Soonduecount = soonDue;
this.Currentmonthcount = current;
this.Currentmonthplus1count = plus1;
this.Currentmonthplus2count = plus2;
this.Currentmonthplus3count = plus3;
this.Currentmonthplus4count = plus4;
this.Currentmonthplus5count = plus5;
}
public LearnerCourse()
{ }
}
public class InfoList : IEnumerable<CombinedInfo>
{
private List<CombinedInfo> _infoList = new List<CombinedInfo>();
public InfoList()
{
_infoList = new List<CombinedInfo>();
}
public void Add(CombinedInfo i)
{
_infoList.Add(i);
}
public IEnumerator<CombinedInfo> GetEnumerator()
{
return _infoList.GetEnumerator();
}
//IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
public class CombinedInfo
{
public string Id { get; set; }
public string ExpiredCount { get; set; }
public string Soonduecount { get; set; }
public string Currentmonthcount { get; set; }
public string Currentmonthplus1count { get; set; }
public string Currentmonthplus2count { get; set; }
public string Currentmonthplus3count { get; set; }
public string Currentmonthplus4count { get; set; }
public string Currentmonthplus5count { get; set; }
public string Name { get; set; }
}
static void Main(string[] args)
{
LearnerCourse lc1 = new LearnerCourse("777", "1", "1", "0", "1", "0", "0", "0", "0");
LearnerCourse lc2 = new LearnerCourse("589", "1", "0", "0", "0", "0", "0", "0", "0");
LearnerInfo li1 = new LearnerInfo("777", "moe");
LearnerInfo li2 = new LearnerInfo("589", "larry");
LearnerCourse[] lCourses = new LearnerCourse[2];
lCourses[0] = lc1;
lCourses[1] = lc2;
LearnerInfo[] linfos = new LearnerInfo[2];
linfos[0] = li1;
linfos[1] = li2;
//test linq join for object array
var myJoin = (from c in lCourses
join i in linfos on c.Id equals i.Id
select new {
c.ExpiredCount,
c.Soonduecount,
c.Currentmonthcount,
c.Currentmonthplus1count,
c.Currentmonthplus2count,
c.Currentmonthplus3count,
c.Currentmonthplus4count,
c.Currentmonthplus5count,
c.Subtotal,
i.Id,
i.Name
});
foreach (CombinedInfo o in l)
{
//loop through and can add to list of type CombinedInfo
}
}
Instead of going through a foreach loop, i am having issues trying to get the result set from my linq query to just return a List.
suggestions?
Two things:
a) Project to a custom class, not an anonymous type. In your case you already have CombinedInfo defined - use it.
b) Use ToList() to force execution and convert the results to a List<T>
var list = (from c in lCourses
join i in linfos on c.Id equals i.Id
select new CombinedInfo() {
ExpiredCount = c.ExpiredCount,
Soonduecount = c.Soonduecount,
Currentmonthcount = c.Currentmonthcount,
Currentmonthplus1count = c.Currentmonthplus1count,
Currentmonthplus2count = c.Currentmonthplus2count,
Currentmonthplus3count = c.Currentmonthplus3count,
Currentmonthplus4count = c.Currentmonthplus4count,
Currentmonthplus5count = c.Currentmonthplus5count,
Subtotal = c.Subtotal,
Id = i.Id,
Name = i.Name
}).ToList();
I´m started to work with AutoMapper today...
But I´m having some problem with Dropdown model...
What I have so far :
User Model
public class User : Entity
{
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual string Password { get; set; }
public virtual Role Role { get; set; }
}
Role Model
public class Role : Entity
{
public virtual string Name { get; set; }
}
UserUpdateViewModel
public class UserUpdateViewModel
{
public int Id{get;set;}
[Required(ErrorMessage = "Required.")]
public virtual string Name { get; set; }
[Required(ErrorMessage = "Required."), Email(ErrorMessage = "Email Invalid."), Remote("EmailExists", "User", ErrorMessage = "Email already in use.")]
public virtual string Email { get; set; }
[Required(ErrorMessage = "Required.")]
public virtual string Password { get; set; }
[Required(ErrorMessage = "Required")]
public virtual string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Required.")]
public int RoleId { get; set; }
public IList<Role> Roles { get; set; }
}
UserController
public ActionResult Update(int id=-1)
{
var _user = (_userRepository.Get(id));
if (_user == null)
return RedirectToAction("Index");
Mapper.CreateMap<User, UserUpdateViewModel>();
var viewModel = Mapper.Map<User, UserUpdateViewModel>(_user);
viewModel.Roles = _roleRepository.GetAll();
return View(viewModel);
}
[HttpPost, Transaction]
public ActionResult Update(UserViewModel user)
{
if (ModelState.IsValid)
{
user.Password = _userService.GetPasswordHash(user.Password);
Mapper.CreateMap<UserViewModel, User>();
var model = Mapper.Map<UserViewModel, User>(user); //model.Role = null
_userRepository.SaveOrUpdate(model); //ERROR, because model.Role = null
return Content("Ok");
}
return Content("Erro").
}
View Update
...
#Html.DropDownListFor(model => model.RoleId, new SelectList(Model.Roles, "Id", "Name"), "-- Select--", new { #class = "form radius" })
...
Some considerations:
1 - I´m returning Content() because is all Ajax enabled using HTML 5 PushState etc etc
2 - In my Update(POST one) method, my model returned by Autommapper has Role = null
Why my Role returned by Automapper is null?
Is that the right way to work with AutoMapper? Any tip?
Thanks
The map is failing because you are trying to map a single Role directly to a collection of Roles. And a collection of Roles back to a single Role. You cant directly map between these as they are different types.
If you wanted to map a Role to a List then you could use a custom value resolver.
Mapper.CreateMap<User , UserUpdateViewModel>()
.ForMember(dest => dest.Roles, opt => opt.ResolveUsing<RoleToCollectionResolver>())
Public class RoleToCollectionResolver: ValueResolver<User,IList<Role>>{
Protected override IList<Role> ResolveCore(User source){
var roleList = new List<Role>();
roleList.Add(source.Role);
Return roleList;
}
}