locked
how to get login user Id and save in other table RRS feed

  • Question

  • User-2035378889 posted

    Dear All am trying to get current  login user company name and store its company name in 
    purchase table 

    this is my model class

    using PharmaApp.Core.DataModel.Base;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace PharmaApp.Core.DataModel
    {
        [Table("UserAccount")]
        public class UserAccountModel : BaseModel
        {
            [Required]
            [StringLength(30)]
            public string Name { get; set; }
            [EmailAddress]
            [Required]
            public string Email { get; set; }
            [Required]
            public string Password  { get; set; }
            [Required]
            public string Role { get; set; }
            public string Company { get; set; }

    and this is my Purchase model class

    using PharmaApp.Core.DataModel.Base;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace PharmaApp.Core.DataModel
    {
        [Table("Purchase")]
        public class PurchaseModel : BaseModel
        {
            [Required]
            [DisplayName("Purchase Code")]
            public string PurchaseCode { get; set; }
            public string Vechile { get; set; }
            [Required]
            [DisplayName("Purchase Date")]
            public DateTime PurchaseDate { get; set; }
            public string Notes { get; set; }
            public string Company { get; set; }
            [Required]
            public Double Total { get; set; }
            [Required]
            [DisplayName("Payment Method")]
            public string PaymentMethod{ get; set; }
            public string Status { get; set; }
            public double Discount { get; set; }
            public double GrandTotal { get; set; }      
            //public string CompanyName { get; set; }
            [DisplayName("Supplier")]
            [ForeignKey("SupplierModel")]
            public int SupplierId { get; set; }
            public SupplierModel SupplierModel { get; set; }
            public ICollection<PurchaseItemsModel> Items { get; set; }

            public PurchaseModel()
            {
                Items = new List<PurchaseItemsModel>();
            }
        }
    }

    The target is when a user login and put record in purchase view  system auto detect current  user company name and store in table purchase company

    what is best approach for this task

    thank

    Wednesday, January 13, 2021 10:04 AM

Answers

All replies

  • User-2054057000 posted

    what is best approach for this task

    You can use ASP.NET Core Identity for getting the User Id quite easily. Once the user is logged in then you can get his username like this:

    AppUser user = await userManager.GetUserAsync(HttpContext.User);
    string un = user.UserName;

    The variable un will contain username. Then use it in your codes.

    Refer - ASP.NET Core Identity Showing Logged in User’s name

    Wednesday, January 13, 2021 10:22 AM
  • User-2035378889 posted

    Thanks to copration wit me

    I put the code as in my purchase controller

    using PharmaApp.Core.AppData;
    using PharmaApp.Core.DataModel;
    using PharmaApp.Core.Interface;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Data;
    using System.Web.Mvc;
    using PharmaApp.Core.ViewModel;
    using PharmaApp.Web.Reports;

    namespace PharmaApp.Web.Controllers
    {
        [Authorize]
        public class AdminController : Controller
        {
            private readonly IShelfRepository _shelfRepository;
            private readonly ICategoryRepository _categoryRepository;
            private readonly ICustomerRepository _customerRepository;
            private readonly ISupplierRepository _supplierRepository;
            private readonly IStoreSettingRepository _storeRepository;
            private readonly IMedicineRepository _medicineRepository;
            private readonly IPurchaseItemRepository _purchaseItemRepository;
            private readonly IPurchaseRepository _purchaseRepository;
            private readonly IStockRepository _stockRepository;
            private readonly ISalesRepository _salesRepository;

            public AdminController(IShelfRepository shelfRepository, ICategoryRepository
                categoryRepository, ICustomerRepository customerRepository, ISupplierRepository supplierRepository,
               IMedicineRepository medicineRepository, IStoreSettingRepository storeRepository,
               IPurchaseItemRepository purchaseItemRepository, IPurchaseRepository purchaseRepository, IStockRepository stockRepository,
               ISalesRepository salesRepository)
            {
                _shelfRepository = shelfRepository;
                _categoryRepository = categoryRepository;
                _medicineRepository = medicineRepository;
                _customerRepository = customerRepository;
                _supplierRepository = supplierRepository;
                _storeRepository = storeRepository;
                _purchaseRepository = purchaseRepository;
                _purchaseItemRepository = purchaseItemRepository;
                _stockRepository = stockRepository;
                _salesRepository = salesRepository;
            }
            // GET: Admin
            public ActionResult Index()
            {
                int totalPurchases = 0;
                int totalSales = 0;
                int stocks = 0;
                if (_purchaseRepository.All().Count() > 0)
                {
                    totalPurchases = Convert.ToInt32(_purchaseRepository.All().Sum(x => x.Total));
                }
                if (_salesRepository.All().Count() > 0)
                {
                    totalSales = Convert.ToInt32(_salesRepository.All().Sum(x => x.Total));
                }
                if (_stockRepository.All().Count() > 0)
                    stocks = Convert.ToInt32(_stockRepository.All().Sum(x => x.TotalQuantity));
                var dashboard = new DashboardViewModel
                {
                    Medicines = _medicineRepository.All().Count(),
                    Stocks = stocks,
                    Shelfs = _shelfRepository.All().Count(),
                    Suppliers = _supplierRepository.All().Count(),
                    Purchases = _purchaseRepository.All().Count(),
                    TotalPurchases = totalPurchases,
                    TotalSales = totalSales,
                    sales = _salesRepository.All().Count(),
                    LowStocks = _stockRepository.All(x => x.MedicineModel).Where(x => x.TotalQuantity <= AppData.NotifyDefaultQuantity)
                };
                return View(dashboard);
            }

            #region shelf 
            [HttpGet]
            public ActionResult Shelf()
            {
                return View(_shelfRepository.All());
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Shelf(ShelfModel model)
            {
                if (ModelState.IsValid)
                {
                    _shelfRepository.Insert(model);
                    return RedirectToAction("Shelf");
                }
                return View(_shelfRepository.All());
            }

            public ActionResult DeleteShelf(int shelfId)
            {
                var shelf = _shelfRepository.Find(shelfId);
                if (shelf != null)
                {
                    _shelfRepository.Remove(shelfId);
                    return RedirectToAction("Shelf");
                }
                return View(_shelfRepository.All());
            }

            #endregion

            #region category 
            [HttpGet]
            public ActionResult Category()
            {
                return View(_categoryRepository.All());
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Category(CategoryModel model)
            {
                if (ModelState.IsValid)
                {
                    _categoryRepository.Insert(model);
                    return RedirectToAction("Category");
                }
                return View(_categoryRepository.All());
            }

            public ActionResult DeleteCategory(int categoryId)
            {
                var category = _categoryRepository.Find(categoryId);
                if (category != null)
                {
                    _categoryRepository.Remove(categoryId);
                    return RedirectToAction("Category");
                }
                return RedirectToAction("Category");

            }
            #endregion

            #region Medicine

            public ActionResult MedicineList()
            {
                var medicines = _medicineRepository.All(x => x.ShelfModel);
                return View(medicines);
            }

            [HttpGet]
            public ActionResult AddMedicine()
            {
                LoadMedicineDropdown();
                return View();
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult AddMedicine(MedicineModel model)
            {
                if (!ModelState.IsValid)
                {
                    LoadMedicineDropdown();
                    return View(model);
                }
                _medicineRepository.Insert(model);
                return RedirectToAction("MedicineList");
            }
            [HttpGet]
            public ActionResult EditMedicine(int medicineId)
            {
                var medicine = _medicineRepository.Find(medicineId);
                LoadMedicineDropdown();
                return View(medicine);
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult EditMedicine(MedicineModel model)
            {
                if (!ModelState.IsValid)
                {

                    LoadMedicineDropdown();
                    return View(model);
                }
                _medicineRepository.Update(model);
                return RedirectToAction("MedicineList");
            }
            public ActionResult DeleteMedicine(int medicineId)
            {
                if (_stockRepository.All().Where(x => x.MedicineId == medicineId).Any())
                {
                    TempData["Msg"] = "Can't Delete, this medicine has stocks ";
                    return RedirectToAction("MedicineList");
                }
                _medicineRepository.Remove(medicineId);
                return RedirectToAction("MedicineList");
            }


            #endregion

            #region customer
            [HttpGet]
            public ActionResult AddCustomer()
            {
                return View();
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult AddCustomer(CustomerModel model)
            {
                if (ModelState.IsValid)
                {
                    _customerRepository.Insert(model);
                    return RedirectToAction("CustomerList");
                }
                return View(model);
            }
            public ActionResult CustomerList()
            {
                return View(_customerRepository.All());
            }
            [HttpGet]
            public ActionResult EditCustomer(int customerId)
            {
                var customer = _customerRepository.Find(customerId);
                return View(customer);
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult EditCustomer(CustomerModel model)
            {
                if (!ModelState.IsValid)
                    return View(model);

                _customerRepository.Update(model);
                return RedirectToAction("CustomerList");
            }

            public ActionResult DeleteCustomer(int customerId)
            {
                var customer = _categoryRepository.Find(customerId);
                if (customer != null)
                {
                    _customerRepository.Remove(customerId);
                    return RedirectToAction("CustomerList");
                }
                return RedirectToAction("CustomerList");
            }
            #endregion

            #region supplier
            [HttpGet]
            public ActionResult AddSupplier()
            {
                return View();
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult AddSupplier(SupplierModel model)
            {
                if (ModelState.IsValid)
                {
                    _supplierRepository.Insert(model);
                    return RedirectToAction("SupplierList");
                }
                return View(model);
            }
            public ActionResult SupplierList()
            {
                return View(_supplierRepository.All());
            }
            [HttpGet]
            public ActionResult EditSupplier(int supplierId)
            {
                var supplier = _supplierRepository.Find(supplierId);
                return View(supplier);
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult EditSupplier(SupplierModel model)
            {
                if (!ModelState.IsValid)
                    return View(model);

                _supplierRepository.Update(model);
                return RedirectToAction("SupplierList");
            }
            public ActionResult DeleteSupplier(int supplierId)
            {
                var supplier = _supplierRepository.Find(supplierId);
                if (supplier != null)
                {
                    _supplierRepository.Remove(supplierId);
                    return RedirectToAction("SupplierList");
                }
                return RedirectToAction("SupplierList");
            }
            #endregion

            #region Store Settings 
            [HttpGet]
            public ActionResult StoreSetting()
            {
                var settings = _storeRepository.All().FirstOrDefault();
                if (settings != null)
                    return View(settings);
                return View(new StoreSettingModel());
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult StoreSetting(StoreSettingModel model, HttpPostedFileBase logoPostedFileBase)
            {
                if (!ModelState.IsValid) return View(model);
                if (logoPostedFileBase != null)
                {
                    string fileName = Path.GetFileName(logoPostedFileBase.FileName);
                    string GUID = Guid.NewGuid().ToString().Substring(0, 3).Replace("-", "").ToUpper();
                    string guidFileName = GUID + fileName;
                    var path = Path.Combine(Server.MapPath(AppData.DefaultPath), guidFileName);
                    logoPostedFileBase.SaveAs(path);
                    model.Logo = AppData.DefaultPath + guidFileName;
                }

                if (model.Id > 0)
                {
                    var settings = _storeRepository.All().FirstOrDefault();
                    settings.StoreName = model.StoreName;
                    settings.Phone = model.Phone;
                    settings.Currency = model.Currency;
                    settings.Web = model.Web;
                    settings.Email = model.Email;
                    settings.Address = model.Address;

                    if (settings.Logo != "" && logoPostedFileBase == null)
                        settings.Logo = settings.Logo;
                    else
                        settings.Logo = model.Logo;

                    _storeRepository.Update(settings);
                    TempData["Msg"] = "Store setting updated successfully";
                    return RedirectToAction("StoreSetting");
                }
                _storeRepository.Insert(model);
                TempData["Msg"] = "Store setting updated successfully";
                return RedirectToAction("StoreSetting");
            }
            #endregion

            #region purchase
            [HttpGet]
            public ActionResult Purchase()
            {
                return View();
            }
            [HttpPost]
            public ActionResult Purchase(PurchaseModel model)
            {
                if (ModelState.IsValid)
                {
                    _purchaseRepository.Insert(model);

                    foreach (var item in model.Items)
                    {
                        var stock = _stockRepository.All().SingleOrDefault(x => x.MedicineId == item.MedicineId);
                        if (stock != null)
                        {
                            // update quantity
                            _stockRepository.AddQuantity(item.Quantity, stock.Id);
                        }
                        else
                        {   // add new stock
                            _stockRepository.Insert(new StockModel { TotalQuantity = item.Quantity, NotifyForQuantityBelow = AppData.NotifyDefaultQuantity, MedicineId = item.MedicineId });
                        }
                    }
                    return Json(new { error = false, message = "Purchse saved successfully" });
                }
                return Json(new { error = true, message = "failed to save Purchse" });
            }

            public ActionResult PurchaseList()
            {
                return View(_purchaseRepository.All(x => x.SupplierModel));
            }

            [HttpGet]
            public ActionResult EditPurchase(int purchaseId)
            {
                var purchase = _purchaseRepository.Find(purchaseId);
                if (purchase != null)
                {
                    return View(model: purchaseId);
                }
                return RedirectToAction("PurchaseList");
            }

            [HttpPost]
            public ActionResult UpdatePurchase(PurchaseModel model)
            {
                if (ModelState.IsValid)
                {
                    // remove 
                    var items = _purchaseItemRepository.All().Where(x => x.PurcasheId == model.Id).ToList();
                    if (items.Any())
                    {
                        //subtract item quantity from stock
                        foreach (var item in items)
                        {
                            var stock = _stockRepository.All().SingleOrDefault(x => x.MedicineId == item.MedicineId);
                            if (stock != null)
                                _stockRepository.SubQuantity(item.Quantity, stock.Id);
                        }
                        //remove from purchase item
                        foreach (var item in items)
                        {
                            _purchaseItemRepository.Remove(item.Id);
                        }
                    }

                    var purchase = _purchaseRepository.Find(model.Id);
                    purchase.Notes = model.Notes;
                    purchase.PaymentMethod = model.PaymentMethod;
                    purchase.PurchaseCode = model.PurchaseCode;
                    purchase.SupplierId = model.SupplierId;
                    purchase.Total = model.Total;
                    purchase.PurchaseDate = model.PurchaseDate;
                    purchase.Status = model.Status;
                    purchase.Discount = model.Discount;
                    purchase.GrandTotal = model.GrandTotal;
                    purchase.Vechile = model.Vechile;
                    AppUser user = await userManager.GetUserAsync(HttpContext.User);
                    string un = user.company;
                    purchase.Company = un;
                    // purchase.CompanyName = "abc";
                    //add again
                    foreach (var item in model.Items)
                    {
                        purchase.Items.Add(new PurchaseItemsModel
                        {
                            Price = item.Price,
                            Amount = item.Amount,
                            Quantity = item.Quantity,
                            MedicineId = item.MedicineId,
                            Bagweight = item.Bagweight,
                            Weight = item.Weight,
                            Deduction = item.Deduction,
                            Bardanaweight = item.Bardanaweight,
                            Muns = item.Muns,
                        });
                    }
                    _purchaseRepository.Update(purchase);

                    // add quantity to stock and or add new 
                    foreach (var item in model.Items)
                    {
                        var stock = _stockRepository.All().SingleOrDefault(x => x.MedicineId == item.MedicineId);
                        if (stock != null)
                        {
                            // update quantity
                            _stockRepository.AddQuantity(item.Quantity, stock.Id);
                        }
                        else
                        {   // add new stock
                            _stockRepository.Insert(new StockModel { TotalQuantity = item.Quantity, NotifyForQuantityBelow = AppData.NotifyDefaultQuantity, MedicineId = item.MedicineId });
                        }
                    }

                    return Json(new { error = false, message = "Purchse updated successfully" });
                }
                return Json(new { error = true, message = "failed to Update Purchsed" });
            }

            public ActionResult DeletePurcahse(int purchaseId)
            {
                var items = _purchaseItemRepository.All().Where(x => x.PurcasheId == purchaseId).ToList();
                if (items.Any())
                {
                    // subtract item quantity from stock
                    foreach (var item in items)
                    {
                        var stock = _stockRepository.All().SingleOrDefault(x => x.MedicineId == item.MedicineId);
                        if (stock != null)
                            _stockRepository.SubQuantity(item.Quantity, stock.Id);

                    }
                }
                _purchaseRepository.Remove(purchaseId);


                return RedirectToAction("PurchaseList");
            }


            public ActionResult PurchaseInvoice(int purchaseId, int style)
            {
                if (_storeRepository.All().Count() == 0)
                {
                    TempData["Msg"] = "Setup store setting first then print sale invoice";
                    return RedirectToAction("Index");
                }
                var store = _storeRepository.All().FirstOrDefault();

                var purchase = _purchaseRepository.All(x => x.SupplierModel).SingleOrDefault(x => x.Id == purchaseId);
                purchase.Items = _purchaseItemRepository.All(x => x.MedicineModel).Where(x => x.PurcasheId == purchaseId).ToList();
                if (purchase != null)
                {
                    var purchasees = new PurchaseReportViewModel
                    {
                        company = store,
                        Purchase = purchase
                    };
                    if (style == 1)
                    {
                        PurchaseReport paymentReport = new PurchaseReport();
                        byte[] bytes = paymentReport.CreateReport(purchasees);
                        return File(bytes, "application/pdf");
                    }
                    if (style == 2)
                    {
                        PurchaseReportSmall paymentReport = new PurchaseReportSmall();
                        byte[] bytes = paymentReport.CreateReport(purchasees);
                        return File(bytes, "application/pdf");
                    }
                }

                return RedirectToAction("PurchaseList");
            }

            #endregion

            #region stock List
            public ActionResult StockList()
            {
                return View(_stockRepository.All(x => x.MedicineModel).ToList());
            }
            #endregion

            #region json methods


            public JsonResult GetPurchase(int purchaseId)
            {
                var model = _purchaseRepository.All().SingleOrDefault(x => x.Id == purchaseId);
                model.Items = _purchaseItemRepository.All(x => x.MedicineModel).Where(x => x.PurcasheId == model.Id).ToList();
                return Json(model, JsonRequestBehavior.AllowGet);
            }
            public JsonResult GetSupplier()
            {
                
                return Json(_supplierRepository.All().Where(x => x.TrialCategory == "party"), JsonRequestBehavior.AllowGet);
            }
            public JsonResult GetAccounts()
            {

                return Json(_supplierRepository.All().Where(x => x.TrialCategory != "Party"), JsonRequestBehavior.AllowGet);
            }
            public JsonResult GetCategories()
            {
                return Json(_categoryRepository.All(), JsonRequestBehavior.AllowGet);
            }
            public JsonResult GetMedicinesByCategory()
            {
                return Json(_supplierRepository.All().Where(x => x.TrialCategory == "Item"), JsonRequestBehavior.AllowGet);
            }
            public JsonResult GetMedicinesById(int id)
            {
                return Json(_medicineRepository.All().Where(x => x.Id == id), JsonRequestBehavior.AllowGet);
            }


            public JsonResult GetCustomer()
            {
                return Json(_customerRepository.All(), JsonRequestBehavior.AllowGet);
            }
            public JsonResult GetStockMedicinesByCategory(int categoryId = 0)
            {
                if (categoryId == 0)
                    return Json(_stockRepository.All(m => m.MedicineModel), JsonRequestBehavior.AllowGet);
                return Json(_stockRepository.All(m => m.MedicineModel).Where(x => x.MedicineModel.CategoryId == categoryId), JsonRequestBehavior.AllowGet);
            }
            public JsonResult GetStockMedicineById(int id)
            {
                return Json(_stockRepository.All(m => m.MedicineModel).Where(x => x.MedicineId == id), JsonRequestBehavior.AllowGet);
            }
            #endregion

            #region private methods
            private void LoadMedicineDropdown()
            {
                ViewBag.shelfs = _shelfRepository.ShelfForDropdown();
                ViewBag.categories = _categoryRepository.CategoryForDropdown();
            }
            #endregion
        }
    }

    Now  Appear the error

    the type or namespace name appuser cannot be found

    Please help me to this error

    Wednesday, January 13, 2021 5:55 PM
  • User-939850651 posted

    Hi ABDULLAH ANOTECH,

    According to the code you provided, you are missing the namespace for the relevant reference. 

    using Microsoft.AspNetCore.Identity;

    The AppUser class mentioned by other members above is a custom user class inherited from IdentityUser Class.

    You could also build your own ApplicationUser class according to your own needs.

    Something like :

    using Microsoft.AspNetCore.Identity;
    
    public class ApplicationUser : IdentityUser
    {
       //some customer define
    }
    
    public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
    	
        public AccountController(UserManager<ApplicationUser> userManager)
    	{
    		_userManager = userManager;
    	}
    	
    	[HttpGet]
    	public async Task<string> GetCurrentUserId()
    	{
    		ApplicationUser usr = await GetCurrentUserAsync();
    		return usr?.Id;
    	}
    
        private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
    }

    Hope this can help you.

    Best regards,

    Xudong Peng

    Thursday, January 14, 2021 2:58 AM
  • User-2035378889 posted

    Thanks To Reply

    this is my Model Class

    using PharmaApp.Core.DataModel.Base;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace PharmaApp.Core.DataModel
    {
        [Table("UserAccount")]
        public class UserAccountModel : BaseModel
        {
            [Required]
            [StringLength(30)]
            public string Name { get; set; }
            [EmailAddress]
            [Required]
            public string Email { get; set; }
            [Required]
            public string Password  { get; set; }
            [Required]
            public string Role { get; set; }
            public string Company { get; set; }
        }
    }

    am using code first Approach

    hope you will guide me now better

    thanks once again

    Friday, January 15, 2021 11:56 PM
  • User-939850651 posted

    Hi ABDULLAH ANOTECH,

    Registered users of your web site. The IdentityUser type may be extended or used as an example for your own custom type.

    This means that you don't have to inherit this class to define application user classes. Have you tried the solution I mentioned above?

    For more details, you could refer to this document:

    https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-custom-storage-providers?view=aspnetcore-5.0#users

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 21, 2021 10:30 AM