I tried to implement the function without success
I want to check if the user's status is true so that means he is logged in
I mean if Status is false then I do not want to display it at all in a list that will be ignored
What I tried causes all the connected to be displayed even if they are false
Model:
[Table("Contact")]
public partial class Contact
{
[Key]
public Guid Id { get; set; }
public string DisplayName { get; set; } = null!;
public string ProfilePic { get; set; } = null!;
public int? Rating { get; set; }
public bool? Status { get; set; }
public bool? IsRegistration { get; set; }
}
DbContext:
public virtual DbSet<Contact> Contacts { get; set; } = null!;
Repository:
private readonly TalkBackContactsDbContext _context;
public ContactsRepository(TalkBackContactsDbContext context)
{
_context = context;
}
public IQueryable<Contact> GetAllConnectedUser(Contact contact)
{
if (contact.Status == false)
{
throw new Exception("Not exist");
}
else
{
return _context.Contacts;
}
}
api controller:
private readonly IContactsRepository _repo;
public ContactsController(IContactsRepository repo)
{
_repo = repo;
}
[HttpGet()]
public IEnumerable<Contact> GetAllConnected()
{
var contact = new Contact();
try
{
return _repo.GetAllConnectedUser(contact);
}
catch (Exception e)
{
e.ToString();
}
return _repo.GetAllConnectedUser(contact);
}
Try this.
Repository:
private readonly TalkBackContactsDbContext _context;
public ContactsRepository(TalkBackContactsDbContext context)
{
_context = context;
}
public IEnumerable<Contact> GetAllConnectedUser()
{
_context.Contacts.Where(a=>a.Status==true).AsEnumerable();
}
api controller:
private readonly IContactsRepository _repo;
public ContactsController(IContactsRepository repo)
{
_repo = repo;
}
[HttpGet()]
public IEnumerable<Contact> GetAllConnected()
{
return _repo.GetAllConnectedUser();
}
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.
How to find duplicate records in below mentioned collection structure
Unique By:
CatalogCode, ArticleNumber and Sizename
CatalogCode, ArticleNumber and SizeIndex
Code:
public class Article
{
public Article()
{
ArticleSizes = new List<Sizes>();
}
public string ArticleNumber { get; set; }
public int CatalogCode { get; set; }
public List<Sizes> ArticleSizes { get; set; }
}
public class Sizes
{
public Sizes()
{
}
public string Sizename { get; set; }
public string SizeIndex { get; set; }
}
Update:
I need to find duplicate in below mentioned list
List<Article> ArticleList=new List<Article> ()
{
new Article(ArticleNumber ='123',CatalogCode=1,
ArticleSizes =New ArticleSizes (){
new Sizes(){SizeName='L',SizeIndex='abc'},
new Sizes(){SizeName='L',SizeIndex='eee'},
new Sizes(){SizeName='L',SizeIndex='rrr'}}),
new Article(ArticleNumber ='435',CatalogCode=1,
ArticleSizes =New ArticleSizes (){
new Sizes(){SizeName='XL',SizeIndex='abc'},
new Sizes(){SizeName='L',SizeIndex='abc'},
new Sizes(){SizeName='M',SizeIndex='abc'}})
}
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();
}
I'm using knockoutjs to render a collection of items. After allowing the user to do some inline editing I need to post the collection back to the server. However, the collection isn't being populated on the server because I'm not using the name="[0].Blah" naming convention. Does anyone know how to either render name attributes like this using knockoutjs OR how to create a model binder that will allow me to extract the values from the ValueProvider?
You can see a screenshot of the ValueProvider during debugging below.
http://i.imgur.com/zSU5Z.png
Here is my managed ViewModel:
public class FundLevelInvestmentUploadResult
{
public string FileName { get; set; }
public IList<FundLevelInvestmentViewModel> Items { get; set; }
public int NumberOfErrors { get; set; }
public bool ShowErrorsOnly { get; set; }
public FundLevelInvestmentUploadResult()
{
Items = new List<FundLevelInvestmentViewModel>();
}
}
Here is the managed class for "Items":
public class FundLevelInvestmentViewModel
{
private string _fund;
private string _fundType;
private string _date;
private string _netOfWaivedFees;
private string _waivedFees;
private string _bcip;
private string _fxRate;
public uint RowIndex { get; set; }
public int? DealCode { get; set; }
public bool DealCodeIsValid { get; set; }
public string Fund
{
get { return _fund; }
set { _fund = GetString(value); }
}
public bool FundIsValid { get; set; }
public string FundType
{
get { return _fundType; }
set { _fundType = GetString(value); }
}
public bool FundTypeIsValid { get; set; }
public string DateOfInvestment
{
get { return _date; }
set { _date = GetString(value); }
}
public bool DateOfInvestmentIsValid { get; set; }
public string NetOfWaivedFees
{
get { return _netOfWaivedFees; }
set { _netOfWaivedFees = GetString(value); }
}
public bool NetOfWaivedFeesIsValid { get; set; }
public string WaivedFee
{
get { return _waivedFees; }
set { _waivedFees = GetString(value); }
}
public bool WaivedFeeIsValid { get; set; }
public string BCIP
{
get { return _bcip; }
set { _bcip = GetString(value); }
}
public bool BCIPIsValid { get; set; }
public string ExchangeRateToUSD
{
get { return _fxRate; }
set { _fxRate = GetString(value); }
}
public bool ExchangeRateToUSDIsValid { get; set; }
public string FileName { get; set; }
private IList<string> _errors;
public IList<string> Errors
{
get { return _errors ?? (_errors = new List<string>());}
set { _errors = value; }
}
public bool Show { get; set; }
public FundLevelInvestmentViewModel()
{
Errors = new List<string>();
Show = true;
}
// knockoutjs is returning "null" instead of "" for a null object when calling ko.mapping.fromJS
private string GetString(string value)
{
if (value == "null")
return string.Empty;
return value;
}
}
Here is my knockout viewModel:
var viewModel = {
FileData: ko.observableArray([]),
validateFile: function (file, event) {
$.ajax({
type: 'post',
url: newUrl,
data: ko.mapping.toJS(file)
}).done(function (data) {
var newFile = ko.mapping.fromJS(data);
var index = file.Items.indexOf(file);
viewModel.FileData.replace(file, newFile);
});
}
};
If you are using version 2.1.0.0 or later of knockout you can render the name attribute as follows from an observable array.
<input data-bind='attr: { name: "Items["+$index()+"].DealCode"}' />
In my application got:
Classes
public class User
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public bool IsApproved { get; set; }
}
public class DataContext : DbContext
{
DbSet<User> Users { get; set; }
}
public class Repository
{
DataContext db = new DataContext();
public bool ApproveUser(User usr) //This is correct place?
{
usr.IsApproved = true;
db.Attrach(usr);
return db.SaveChanges() > 0;
}
}
Question
Where putting logic approval user?
In Repository? In own class?
I ask this because today is the repository and am having trouble to test this once approval is the logic of production in the repository in the repository and not fake.
Repository is the place to write data access. User approval is more likely to be business process, so it better be separated from data access. I would do it this way (code below is more like of pseudocode, not the full production-ready stuff)
public interface IUserRepository
{
bool Save();
}
public class UserRepository : IUserRepository
{
public bool Save(User user)
{
db.Attrach(user);
return db.SaveChanges() > 0;
}
}
public interface IUserService
{
bool Approve(User user);
}
public class UserService : IUserService
{
readonly IUserRepository _userRepository;
public UserService(IUserRepository userRepository)
{
_userRepository = userRepository;
}
public bool Approve(User user)
{
user.IsApproved = true;
return _repository.Save(User user);
}
}
And now, this already is the testable code