0% found this document useful (0 votes)
17 views

Codes

This document contains code for several controllers in an inventory management system for a pharmacy assistant application. The controllers manage drug generic names, items, and manufacturers. The DrugGenericNameController provides actions for listing, creating, viewing details of, deleting, and editing drug generic names. The ItemController provides actions for listing items, populating dropdowns for drug generic names and manufacturers, and creating a new item. The ManufacturerController provides basic actions for listing, creating, and saving a new manufacturer.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Codes

This document contains code for several controllers in an inventory management system for a pharmacy assistant application. The controllers manage drug generic names, items, and manufacturers. The DrugGenericNameController provides actions for listing, creating, viewing details of, deleting, and editing drug generic names. The ItemController provides actions for listing items, populating dropdowns for drug generic names and manufacturers, and creating a new item. The ManufacturerController provides basic actions for listing, creating, and saving a new manufacturer.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

15 January 2023

COMSATS UNIVERSITY ISLAMABAD


CAMPUS ATTOCK

LAB-TERMINAL
SUBMITTED TO: SIR JAMAL AHMED
SUBMITTED BY: ZUNAIRA FATIMA
REGISTRATION NO: FA20-BSE-014
COURSE TITLE: VISUAL PROGRAMMING

BS (SE)-5B
15 January 2023

CONTROLLERS
INVENTORY CONTROLLERS
DRUG NAME CONTROLLER
using PharmAssistent.Models;
using PharmAssistent.Models.InventoryModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PharmAssistent.Repository;

namespace PharmAssistent.Controllers.Inventory
{
public class DrugGenericNameController : Controller
{
CheckDuplicatecs Duplicates = new CheckDuplicatecs();
PharmContext db = new PharmContext();
// GET: DrugGenericName
public ActionResult Index()
{
return View(db.DrugGenericNames.ToList());
}
[ActionName("CreateGeneric")]
[HttpGet]
public ActionResult Create()
{
return View();
}
[ActionName("CreateGeneric")]
[HttpPost]
public ActionResult Create_Generic()
{
DrugGenericName drugGenericName = new DrugGenericName();
TryUpdateModel(drugGenericName);
{
bool count =
Duplicates.CheckDuplicatecDrugGenericName(drugGenericName);
if (count == false)
{
try
{
db.DrugGenericNames.Add(drugGenericName);
db.SaveChanges();
ViewBag.msg = "Generic Save"; // SET IT TO VIEW
}
catch
{
ViewBag.msg = "Unable to save";
//return new
HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
}

}
return RedirectToAction("Index", "DrugGenericName");
}

BS (SE)-5B
15 January 2023

}
public ActionResult Detail(int ID)
{

PharmContext context = new PharmContext();


DrugGenericName output = new DrugGenericName();
try
{
output = context.DrugGenericNames.Single(m => m.ID == ID);
ViewBag.err = null;
ViewBag.id = output.ID;

}
catch
{
ViewBag.err = "Invalid Id Selected";

return View(output);
}

return View(output);
}

public ActionResult Delete(int ID)


{

PharmContext context = new PharmContext();


DrugGenericName output = new DrugGenericName();
try
{
output = context.DrugGenericNames.Single(m => m.ID == ID);
context.DrugGenericNames.Remove(output);
context.SaveChanges();

ViewBag.msg = "Item Removed";

}
catch
{
ViewBag.msg = "ID Not Found"; // Item not Found
}

return RedirectToAction("Index");
}

[HttpGet]
public ActionResult Edit(int ID)
{
PharmContext db = new PharmContext();
DrugGenericName drugGenericName= new DrugGenericName();
try
{
drugGenericName= db.DrugGenericNames.Single(m => m.ID == ID);
}
catch
{
ViewBag.err = "ID not Found";
return RedirectToAction("Index", "DrugGenericName");

BS (SE)-5B
15 January 2023

//return new
HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
}
return View(drugGenericName);
}
[ActionName("Edit")]
[HttpPost]
public ActionResult Edit_Generic()
{
DrugGenericName DrugGenericNames = new DrugGenericName();
PharmContext db = new PharmContext();
TryUpdateModel(DrugGenericNames);
{
DrugGenericName original = new DrugGenericName();

bool count =
Duplicates.CheckDuplicatecDrugGenericName(DrugGenericNames);
if (count == false)
{
try
{
original = db.DrugGenericNames.Single(m => m.ID ==
DrugGenericNames.ID);

original.ID = DrugGenericNames.ID;
original.GenericName = DrugGenericNames.GenericName;
original.Description = DrugGenericNames.Description;

db.SaveChanges();
ViewBag.msg = "Generic Updated"; // SET IT TO VIEW
}
catch
{
ViewBag.msg = "Unable to Update";
}
}
}
return RedirectToAction("Index", "DrugGenericName");
}
}
}

ITEM CONTROLLER
using PharmAssistent.Models;
using PharmAssistent.Models.InventoryModel;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PharmAssistent.Controllers.Inventory
{
public class ItemController : Controller
{
// GET: Item
public ActionResult Index()

BS (SE)-5B
15 January 2023

{
PharmContext db = new PharmContext();
// List<Item> item = new List<Item>();
var items = db.items.ToList();

//return View(item);
// var items = db.items.Include(i => i.DrugGenericName).Include(i =>
i.Manufacturer).OrderByDescending(i => i.ID);
return View(items.ToList());
}
public JsonResult PopulateDrugGenericName()
{
//holds list of suppliers
PharmContext context = new PharmContext();
List<DrugGenericName> _supplierList = new List<DrugGenericName>();

var supplierList = (from s in context.DrugGenericNames


select new { s.ID, s.GenericName }).ToList();

//save list of suppliers to the _supplierList


foreach (var item in supplierList)
{
_supplierList.Add(new DrugGenericName
{
ID = item.ID,
GenericName = item.GenericName
});
}
ViewBag.CategoryType = _supplierList;
return Json(_supplierList, JsonRequestBehavior.AllowGet);
}
public JsonResult PopulateManufacturer()
{
//holds list of suppliers
PharmContext context = new PharmContext();
List<Manufacturer> _supplierList = new List<Manufacturer>();

var supplierList = (from s in context.Manufacturers


select new { s.ID, s.ManufacturerName}).ToList();

//save list of suppliers to the _supplierList


foreach (var item in supplierList)
{
_supplierList.Add(new Manufacturer
{
ID = item.ID,
ManufacturerName = item.ManufacturerName
});
}
ViewBag.CategoryType = _supplierList;
return Json(_supplierList, JsonRequestBehavior.AllowGet);
}

BS (SE)-5B
15 January 2023

[ActionName("NewItem")]
[HttpPost]
public ActionResult Create_New_Item()
{

Item item = new Item();


TryUpdateModel(item);

if(ModelState.IsValid)
{

PharmContext db = new PharmContext();


db.items.Add(item);
db.SaveChanges();
ViewBag.msg = "Data Save SuccessFully";

}
else
{
ViewBag.err = "Invalid Entry";
}

return View();

[ActionName("NewItem")]
[HttpGet]
public ActionResult CreateItem()
{

return View();
}

}
}

MANUFACTURER CONTROLLER
using PharmAssistent.Models;
using PharmAssistent.Models.InventoryModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PharmAssistent.Repository;

namespace PharmAssistent.Controllers.Inventory
{
public class ManufacturerController : Controller
{
CheckDuplicatecs Duplicates = new CheckDuplicatecs();
PharmContext db = new PharmContext();
// GET: Manufacturer
public ActionResult Index()
{

BS (SE)-5B
15 January 2023

return View("Index", db.Manufacturers.OrderByDescending(m =>


m.ID).ToList());

}
public ActionResult Create()
{

return View();
}
[ActionName("Create")]
[HttpPost]
public ActionResult Create_Manufacturer()
{

Manufacturer manufacturer = new Manufacturer();

TryUpdateModel(manufacturer);
{
bool count = Duplicates.CheckDuplicatecManufacturer(manufacturer);

if (count == false)
{
try
{
db.Manufacturers.Add(manufacturer);
db.SaveChanges();
ViewBag.msg = "Manufacturer Saved !"; // SET IT TO VIEW
}
catch
{
ViewBag.msg = "Unable to Create";
//return new
HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
}
}
else
{
ViewBag.err = "Manufacturer Already Exist";
return View();
}

}
return RedirectToAction("Index", "manufacturer");
}
public ActionResult Detail(int ID)
{

PharmContext context = new PharmContext();


Manufacturer output = new Manufacturer();
try
{
output = context.Manufacturers.Single(m => m.ID == ID);
ViewBag.err = null;
ViewBag.id = output.ID;

}
catch
{

BS (SE)-5B
15 January 2023

ViewBag.err = "Invalid Id Selected";

return View(output);
}

return View(output);
}

public ActionResult Delete(int ID)


{

PharmContext context = new PharmContext();


Manufacturer output = new Manufacturer();
try
{
output = context.Manufacturers.Single(m => m.ID == ID);
context.Manufacturers.Remove(output);
context.SaveChanges();

ViewBag.msg = "Item Removed";

}
catch
{
ViewBag.msg = "ID Not Found"; // Item not Found
}

return RedirectToAction("Index");
}

[HttpGet]
public ActionResult Edit(int ID)
{
PharmContext db = new PharmContext();
Manufacturer manufacturer = new Manufacturer();
try
{
manufacturer = db.Manufacturers.Single(m => m.ID == ID);
}
catch
{
ViewBag.err = "ID not Found";
return RedirectToAction("Index", "Manufacturer");
//return new
HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
}
return View(manufacturer);
}
[ActionName("Edit")]
[HttpPost]
public ActionResult Edit_Manufacturer()
{
Manufacturer manufacturer = new Manufacturer();
TryUpdateModel(manufacturer);
{
Manufacturer original = new Manufacturer();
bool count = Duplicates.CheckDuplicatecManufacturer(manufacturer);

BS (SE)-5B
15 January 2023

if (count == false)
{
try
{
original = db.Manufacturers.Single(m => m.ID ==
manufacturer.ID);

original.ID = manufacturer.ID;
original.ManufacturerName = manufacturer.ManufacturerName;
original.Description = manufacturer.Description;

db.SaveChanges();
ViewBag.msg = "Manufacturer Updated"; // SET IT TO VIEW
}

catch
{
ViewBag.msg = "Unable to Update";
//return new
HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
}

}
return RedirectToAction("Index", "manufacturer");
}
}
}
}

PURCHASE ENTRY CONTROLLER


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//using PharmAssistent.Service;

using PharmAssistent.Models.PurchaseModel;
using PharmAssistent.Models;
using PharmAssistent.Models.InventoryModel;
using PharmAssistent.ViewModel;

namespace PharmAssistent.Controllers
{

public class PurchaseEntryController : Controller


{

PharmContext context = new PharmContext();


// GET: PurchaseEntry
[HttpGet]
public ActionResult Index()
{
return View();
}

//public JsonResult PopulatePurchadeID()


// {

BS (SE)-5B
15 January 2023

// var ID = context.Database.ExecuteSqlCommand("SELECT SUM(ID) from


Purchase ");
// Supplier id = new Supplier();
// id.ID = ID;
// return Json(id, JsonRequestBehavior.AllowGet);

// }
public JsonResult PopulateSupplier()
{
//holds list of suppliers
List<Supplier> _supplierList = new List<Supplier>();

var supplierList = (from s in context.Suppliers


select new { s.ID, s.Name }).ToList();

//save list of suppliers to the _supplierList


foreach (var item in supplierList)
{
_supplierList.Add(new Supplier
{
ID = item.ID,
Name = item.Name
});
}
ViewBag.CategoryType = _supplierList;
return Json(_supplierList, JsonRequestBehavior.AllowGet);
}

public JsonResult PopulateItem()


{
//holds list of suppliers
List<Item> _itemList = new List<Item>();

var itemList = (from s in context.items


select new { s.ID, s.Name }).ToList();

//save list of suppliers to the _supplierList


foreach (var item in itemList)
{
_itemList.Add(new Item
{
ID = item.ID,
Name = item.Name
});
}
return Json(_itemList, JsonRequestBehavior.AllowGet);
}

[HttpPost]
public JsonResult SavePurchase(PurchaseEntryVM p)
{

bool status = false;

BS (SE)-5B
15 January 2023

if (p != null)
{
//new purchase object using the data from the viewmodel :
PurchaseEntryVM
Purchase purchase = new Purchase
{
ID = p.ID,
PurchaseID = p.PurchaseID,
Date = p.Date,
SupplierID = p.SupplierID,
Amount = p.Amount,
Discount = p.Discount,
Tax = p.Tax,
GrandTotal = p.GrandTotal,
IsPaid = p.IsPaid,
Description = p.Description,
LastUpdated = DateTime.Now
};
Purchase_Copy purchase_copy = new Purchase_Copy();
purchase_copy.PurchaseItem = new List<PurchaseItem>();
// populating the PurchaseItems from the PurchaseItems within
ViewModel : PurchaseEntryVM
foreach (var i in p.PurchaseItems)
{
purchase_copy.PurchaseItem.Add(i);
}
Service.PurchaseEntryService service = new
Service.PurchaseEntryService();
service.AddPurchaseAndPurchseItems(purchase);
service.InsertOrUpdateInventory(p.PurchaseItems);
/////<if everything is sucessful, set status to true.>
status = true;
}
// return the status in form of Json
return new JsonResult { Data = new { status = status } };
}
}

STOCK CONTROLLER
using PharmAssistent.Models;
using PharmAssistent.Models.InventoryModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PharmAssistent.Controllers.Inventory
{
public class StockController : Controller
{
// GET: Stock
public ActionResult Index()

BS (SE)-5B
15 January 2023

PharmContext db = new PharmContext();


List<Stock> stock = db.Stocks.OrderBy(x => x.Item.Name).ToList();

ViewBag.count = stock.Count;
// var stocks = db.Stocks.Where(s => s.Qty > 0).Include(s =>
s.Item).OrderByDescending(x => x.ID);
return View(stock);
}
public ActionResult Detail(int ID)
{

PharmContext context = new PharmContext();


Stock output = new Stock();
try
{
output = context.Stocks.Single(m => m.ID == ID);
ViewBag.err = null;
ViewBag.id = output.ItemID;

}
catch
{
ViewBag.err = "Invalid Id Selected";

return View(output);
}

return View(output);
}

public ActionResult Delete(int ID)


{

PharmContext context = new PharmContext();


Stock output = new Stock();
try
{
output = context.Stocks.Single(m => m.ID == ID);
context.Stocks.Remove(output);
context.SaveChanges();

ViewBag.msg = "Item Removed";

}
catch
{
ViewBag.msg = "ID Not Found"; // Item not Found
}

return RedirectToAction("Index");
}

[HttpGet]
public ActionResult Edit(int ID)
{
PharmContext db = new PharmContext();

BS (SE)-5B
15 January 2023

Stock Stock = new Stock();


try
{
Stock = db.Stocks.Single(m => m.ID == ID);
}
catch
{
ViewBag.err = "ID not Found";
return RedirectToAction("Index", "Stock");
//return new
HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
}
return View(Stock);
}
[ActionName("Edit")]
[HttpPost]
public ActionResult Edit_Item()
{
Stock stocks = new Stock();
PharmContext db = new PharmContext();
TryUpdateModel(stocks);
{
Stock original = new Stock();
try
{
original = db.Stocks.Single(m => m.ID == stocks.ID);

original.ID = stocks.ID;
original.Batch = stocks.Batch;
original.CostPrice = stocks.CostPrice;
original.Expiry = stocks.Expiry;
// original.Item = stocks.Item;
// original.ItemExpired = stocks.ItemExpired;
original.ItemID = stocks.ItemID;
original.ManufactureDate = stocks.ManufactureDate;
original.PurchaseID = stocks.PurchaseID;
original.Qty = stocks.Qty;
original.SellingPrice = stocks.SellingPrice;

db.SaveChanges();
ViewBag.msg = "Supplier Deleted"; // SET IT TO VIEW
}
catch
{
ViewBag.msg = "Unable to Update";
//return new
HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);

}
return RedirectToAction("Index", "Stock");
}
}
}

BS (SE)-5B
15 January 2023

PURCHASE CONTROLLER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PharmAssistent.Models;
using PharmAssistent.Models.PurchaseModel;

namespace PharmAssistent.Controllers
{

public class PurchaseController : Controller


{
// GET: Purchase
public ActionResult Index()
{
PharmContext db = new PharmContext();
List<Purchase> purchase = new List<Purchase>();

purchase = db.PurchaseContext.SqlQuery("select * from


Purchase").ToList();

return View(purchase);
// return View();

public ActionResult Details(string PurchaseID)


{
PharmContext db = new PharmContext();
List<PurchaseItem> purchase = new List<PurchaseItem>();
purchase = db.PurchaseItemContext.Where(m => m.PurchaseID ==
PurchaseID).ToList();
return View(purchase);
// return View();

}
[HttpGet]
public ActionResult Edit(string PurchaseID)
{
PharmContext db = new PharmContext();
Purchase purchase = new Purchase();
try
{
purchase = db.PurchaseContext.Single(m => m.PurchaseID ==
PurchaseID);
}
catch
{
ViewBag.err = "ID not Found";
return RedirectToAction("Index","Purchase");
//return new
HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
}
return View(purchase);
// return View();

BS (SE)-5B
15 January 2023

}
[ActionName("Edit")]
[HttpPost]
public ActionResult Edit_Purchase()
{
Purchase purchaseView = new Purchase();
PharmContext db = new PharmContext();
TryUpdateModel(purchaseView);
{
Purchase original = new Purchase();
try
{

original = db.PurchaseContext.Single(m => m.PurchaseID ==


purchaseView.PurchaseID);

original.PurchaseID = purchaseView.PurchaseID;
original.Amount = purchaseView.Amount;
original.Date = purchaseView.Date;
original.Description = purchaseView.Description;
original.Discount = purchaseView.Discount;
original.Tax = purchaseView.Tax;
original.GrandTotal = purchaseView.GrandTotal;
original.IsPaid = purchaseView.IsPaid;
original.LastUpdated = DateTime.Now;

db.SaveChanges();
}
catch
{
ViewBag.msg = "Unable to Update";
//return new
HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);

}
return RedirectToAction("Index", "Purchase");
}
public ActionResult Delete(string PurchaseID)
{
PharmContext db = new PharmContext();
List<PurchaseItem> purchaseitem = new List<PurchaseItem>();
Purchase purchase = new Purchase();

try
{
purchase = db.PurchaseContext.Single(m => m.PurchaseID ==
PurchaseID); ;
purchaseitem = db.PurchaseItemContext.Where(m => m.PurchaseID ==
PurchaseID).ToList();

if (purchaseitem != null)
{
foreach (var i in purchaseitem)
{
db.PurchaseItemContext.Remove(i);
}

BS (SE)-5B
15 January 2023

ViewBag.msg = "Details of " + purchase.PurchaseID + "


Deleted";
db.PurchaseContext.Remove(purchase);
db.SaveChanges();

}
else
{
ViewBag.msg = "Item Not Deleted";
}

}
catch
{
ViewBag.err = "Unable to Delete ";

}
return RedirectToAction("Index");

}
}
}

SELL CONTROLLERS
SALES CONTROLLER
using PharmAssistent.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PharmAssistent.Controllers.Sell
{
public class SalesController : Controller
{
PharmContext context = new PharmContext();
// GET:Sales
[HttpGet]
public ActionResult Index()
{
return View();
}
}
}

SALE ENTRY CONTROLLER


using PharmAssistent.Models;
using PharmAssistent.Models.InventoryModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PharmAssistent.Controllers.Sell

BS (SE)-5B
15 January 2023

{
public class SalesEntryController : Controller
{
PharmContext context = new PharmContext();
// GET: SalesEntry
public ActionResult Index()
{
List<Stock> stock = new List<Stock>();
stock = context.Stocks.ToList();
return View(stock);
}
}
}

ACCOUNT CONTROLLER
using System;

using System.Globalization;

using System.Linq;

using System.Security.Claims;

using System.Threading.Tasks;

using System.Web;

using System.Web.Mvc;

using Microsoft.AspNet.Identity;

using Microsoft.AspNet.Identity.Owin;

using Microsoft.Owin.Security;

using PharmAssistent.Models;

namespace PharmAssistent.Controllers

[Authorize]

public class AccountController : Controller

private ApplicationSignInManager _signInManager;

private ApplicationUserManager _userManager;

public AccountController()

BS (SE)-5B
15 January 2023

public AccountController(ApplicationUserManager userManager, ApplicationSignInManager


signInManager )

UserManager = userManager;

SignInManager = signInManager;

public ApplicationSignInManager SignInManager

get

return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();

private set

_signInManager = value;

public ApplicationUserManager UserManager

get

return _userManager ??
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

BS (SE)-5B
15 January 2023

private set

_userManager = value;

//

// GET: /Account/Login

[AllowAnonymous]

public ActionResult Login(string returnUrl)

ViewBag.ReturnUrl = returnUrl;

return View();

//

// POST: /Account/Login

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)

if (!ModelState.IsValid)

return View(model);

// This doesn't count login failures towards account lockout

// To enable password failures to trigger account lockout, change to shouldLockout: true

BS (SE)-5B
15 January 2023

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password,


model.RememberMe, shouldLockout: false);

switch (result)

case SignInStatus.Success:

return RedirectToLocal(returnUrl);

case SignInStatus.LockedOut:

return View("Lockout");

case SignInStatus.RequiresVerification:

return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe =


model.RememberMe });

case SignInStatus.Failure:

default:

ModelState.AddModelError("", "Invalid login attempt.");

return View(model);

//

// GET: /Account/VerifyCode

[AllowAnonymous]

public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)

// Require that the user has already logged in via username/password or external login

if (!await SignInManager.HasBeenVerifiedAsync())

return View("Error");

return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl,


RememberMe = rememberMe });

BS (SE)-5B
15 January 2023

//

// POST: /Account/VerifyCode

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)

if (!ModelState.IsValid)

return View(model);

// The following code protects for brute force attacks against the two factor codes.

// If a user enters incorrect codes for a specified amount of time then the user account

// will be locked out for a specified amount of time.

// You can configure the account lockout settings in IdentityConfig

var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code,


isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);

switch (result)

case SignInStatus.Success:

return RedirectToLocal(model.ReturnUrl);

case SignInStatus.LockedOut:

return View("Lockout");

case SignInStatus.Failure:

default:

ModelState.AddModelError("", "Invalid code.");

BS (SE)-5B
15 January 2023

return View(model);

//

// GET: /Account/Register

[AllowAnonymous]

public ActionResult Register()

return View();

//

// POST: /Account/Register

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public async Task<ActionResult> Register(RegisterViewModel model)

if (ModelState.IsValid)

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

var result = await UserManager.CreateAsync(user, model.Password);

if (result.Succeeded)

await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

// For more information on how to enable account confirmation and password reset please
visit http://go.microsoft.com/fwlink/?LinkID=320771

BS (SE)-5B
15 January 2023

// Send an email with this link

// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code


}, protocol: Request.Url.Scheme);

// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your


account by clicking <a href=\"" + callbackUrl + "\">here</a>");

return RedirectToAction("Index", "Home");

AddErrors(result);

// If we got this far, something failed, redisplay form

return View(model);

//

// GET: /Account/ConfirmEmail

[AllowAnonymous]

public async Task<ActionResult> ConfirmEmail(string userId, string code)

if (userId == null || code == null)

return View("Error");

var result = await UserManager.ConfirmEmailAsync(userId, code);

return View(result.Succeeded ? "ConfirmEmail" : "Error");

BS (SE)-5B
15 January 2023

//

// GET: /Account/ForgotPassword

[AllowAnonymous]

public ActionResult ForgotPassword()

return View();

//

// POST: /Account/ForgotPassword

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)

if (ModelState.IsValid)

var user = await UserManager.FindByNameAsync(model.Email);

if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))

// Don't reveal that the user does not exist or is not confirmed

return View("ForgotPasswordConfirmation");

// For more information on how to enable account confirmation and password reset please
visit http://go.microsoft.com/fwlink/?LinkID=320771

// Send an email with this link

// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

BS (SE)-5B
15 January 2023

// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code


}, protocol: Request.Url.Scheme);

// await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password


by clicking <a href=\"" + callbackUrl + "\">here</a>");

// return RedirectToAction("ForgotPasswordConfirmation", "Account");

// If we got this far, something failed, redisplay form

return View(model);

//

// GET: /Account/ForgotPasswordConfirmation

[AllowAnonymous]

public ActionResult ForgotPasswordConfirmation()

return View();

//

// GET: /Account/ResetPassword

[AllowAnonymous]

public ActionResult ResetPassword(string code)

return code == null ? View("Error") : View();

//

// POST: /Account/ResetPassword

BS (SE)-5B
15 January 2023

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)

if (!ModelState.IsValid)

return View(model);

var user = await UserManager.FindByNameAsync(model.Email);

if (user == null)

// Don't reveal that the user does not exist

return RedirectToAction("ResetPasswordConfirmation", "Account");

var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

if (result.Succeeded)

return RedirectToAction("ResetPasswordConfirmation", "Account");

AddErrors(result);

return View();

//

// GET: /Account/ResetPasswordConfirmation

[AllowAnonymous]

public ActionResult ResetPasswordConfirmation()

BS (SE)-5B
15 January 2023

return View();

//

// POST: /Account/ExternalLogin

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public ActionResult ExternalLogin(string provider, string returnUrl)

// Request a redirect to the external login provider

return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new {


ReturnUrl = returnUrl }));

//

// GET: /Account/SendCode

[AllowAnonymous]

public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)

var userId = await SignInManager.GetVerifiedUserIdAsync();

if (userId == null)

return View("Error");

var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);

var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value =


purpose }).ToList();

return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl,


RememberMe = rememberMe });

BS (SE)-5B
15 January 2023

//

// POST: /Account/SendCode

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public async Task<ActionResult> SendCode(SendCodeViewModel model)

if (!ModelState.IsValid)

return View();

// Generate the token and send it

if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))

return View("Error");

return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl =


model.ReturnUrl, RememberMe = model.RememberMe });

//

// GET: /Account/ExternalLoginCallback

[AllowAnonymous]

public async Task<ActionResult> ExternalLoginCallback(string returnUrl)

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

BS (SE)-5B
15 January 2023

if (loginInfo == null)

return RedirectToAction("Login");

// Sign in the user with this external login provider if the user already has a login

var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);

switch (result)

case SignInStatus.Success:

return RedirectToLocal(returnUrl);

case SignInStatus.LockedOut:

return View("Lockout");

case SignInStatus.RequiresVerification:

return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });

case SignInStatus.Failure:

default:

// If the user does not have an account, then prompt the user to create an account

ViewBag.ReturnUrl = returnUrl;

ViewBag.LoginProvider = loginInfo.Login.LoginProvider;

return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email


= loginInfo.Email });

//

// POST: /Account/ExternalLoginConfirmation

[HttpPost]

[AllowAnonymous]

BS (SE)-5B
15 January 2023

[ValidateAntiForgeryToken]

public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel


model, string returnUrl)

if (User.Identity.IsAuthenticated)

return RedirectToAction("Index", "Manage");

if (ModelState.IsValid)

// Get the information about the user from the external login provider

var info = await AuthenticationManager.GetExternalLoginInfoAsync();

if (info == null)

return View("ExternalLoginFailure");

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

var result = await UserManager.CreateAsync(user);

if (result.Succeeded)

result = await UserManager.AddLoginAsync(user.Id, info.Login);

if (result.Succeeded)

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

return RedirectToLocal(returnUrl);

AddErrors(result);

BS (SE)-5B
15 January 2023

ViewBag.ReturnUrl = returnUrl;

return View(model);

//

// POST: /Account/LogOff

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult LogOff()

AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

return RedirectToAction("Index", "Home");

//

// GET: /Account/ExternalLoginFailure

[AllowAnonymous]

public ActionResult ExternalLoginFailure()

return View();

protected override void Dispose(bool disposing)

if (disposing)

if (_userManager != null)

BS (SE)-5B
15 January 2023

_userManager.Dispose();

_userManager = null;

if (_signInManager != null)

_signInManager.Dispose();

_signInManager = null;

base.Dispose(disposing);

#region Helpers

// Used for XSRF protection when adding external logins

private const string XsrfKey = "XsrfId";

private IAuthenticationManager AuthenticationManager

get

return HttpContext.GetOwinContext().Authentication;

private void AddErrors(IdentityResult result)

BS (SE)-5B
15 January 2023

foreach (var error in result.Errors)

ModelState.AddModelError("", error);

private ActionResult RedirectToLocal(string returnUrl)

if (Url.IsLocalUrl(returnUrl))

return Redirect(returnUrl);

return RedirectToAction("Index", "Home");

internal class ChallengeResult : HttpUnauthorizedResult

public ChallengeResult(string provider, string redirectUri)

: this(provider, redirectUri, null)

public ChallengeResult(string provider, string redirectUri, string userId)

LoginProvider = provider;

RedirectUri = redirectUri;

UserId = userId;

BS (SE)-5B
15 January 2023

public string LoginProvider { get; set; }

public string RedirectUri { get; set; }

public string UserId { get; set; }

public override void ExecuteResult(ControllerContext context)

var properties = new AuthenticationProperties { RedirectUri = RedirectUri };

if (UserId != null)

properties.Dictionary[XsrfKey] = UserId;

context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);

#endregion

EMPLOYEE CONTROLER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PharmAssistent.Models;

namespace MVCDEMO.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Index(int departmentId)
{
EmployeeContext employeContext = new EmployeeContext();
List<Employee> employees = employeContext.Employees.Where(emp =>
emp.DepartmentId == departmentId).ToList();

return View(employees);

BS (SE)-5B
15 January 2023

public ActionResult Details(int id)


{
EmployeeContext employeContext = new EmployeeContext();
Employee employee = employeContext.Employees.Single(emp => emp.EmpId ==
id);

return View(employee);

}
[HttpGet]
[ActionName("Create")]
public ActionResult Create_Get()
{
return View();
}

[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post()
{
Employee employee = new Employee();
TryUpdateModel(employee);
//if (ModelState.iIsValid)
//{
EmployeeBusinessLayer employeeBusinessLayer = new
EmployeeBusinessLayer();
employeeBusinessLayer.AddEmployee(employee); //
@Html.ActionLink("Back to List", "Index", new { departmentId = Model.DepartmentId })

return RedirectToAction("ShowAll", "Employee");


//}

//return View();

public ActionResult ShowAll()


{
EmployeeBusinessLayer employeeBussinessLayer = new
EmployeeBusinessLayer();
List<Employee> employees = employeeBussinessLayer.Employees.ToList();
EmployeeContext db = new EmployeeContext();
var data = db.Employees.SqlQuery("spGetEmployeeData").ToList();
return View(data);
/* return View(employees)*/;
}
public ActionResult Search(String Search)
{
Employee employee = new Employee();
EmployeeContext db = new EmployeeContext();
EmployeeBusinessLayer employeeBussinessLayer = new
EmployeeBusinessLayer();
var emp = from m in db.Employees select m;
if (!String.IsNullOrEmpty(Search))
{
emp = emp.Where(m => m.Name.Contains(Search));
}

BS (SE)-5B
15 January 2023

return View(emp);

public ActionResult Delete(int id)


{
EmployeeBusinessLayer employeeBusinessLayer = new
EmployeeBusinessLayer();
employeeBusinessLayer.DeleteEmployee(id);
ViewBag.msg = "Employee Deleted SuccessFully";
return RedirectToAction("ShowAll", "Employee");
}
[HttpGet]
[ActionName("Edit")]
public ActionResult Edit_Get(int id)
{
EmployeeBusinessLayer employeeBusinessLayer = new
EmployeeBusinessLayer();
Employee employee = employeeBusinessLayer.Employees.Single(emp =>
emp.EmpId == id);

return View(employee);
}

[HttpPost]
[ActionName("Edit")]
public ActionResult Edit_Post(Employee employee)
{

EmployeeBusinessLayer employeeBusinessLayer = new


EmployeeBusinessLayer();
employeeBusinessLayer.SaveEmployee(employee);
return RedirectToAction("ShowAll", "Employee");

}
}
HOME CONTROLLER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PharmAssistent.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();

BS (SE)-5B
15 January 2023

public ActionResult About()


{
ViewBag.Message = "Your application description page.";

return View();
}

public ActionResult Contact()


{
ViewBag.Message = "Your contact page.";

return View();
}
}
}

MANAGE CONTROLLER
using System;

using System.Linq;

using System.Threading.Tasks;

using System.Web;

using System.Web.Mvc;

using Microsoft.AspNet.Identity;

using Microsoft.AspNet.Identity.Owin;

using Microsoft.Owin.Security;

using PharmAssistent.Models;

namespace PharmAssistent.Controllers

[Authorize]

public class ManageController : Controller

private ApplicationSignInManager _signInManager;

private ApplicationUserManager _userManager;

public ManageController()

BS (SE)-5B
15 January 2023

public ManageController(ApplicationUserManager userManager, ApplicationSignInManager


signInManager)

UserManager = userManager;

SignInManager = signInManager;

public ApplicationSignInManager SignInManager

get

return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();

private set

_signInManager = value;

public ApplicationUserManager UserManager

get

return _userManager ??
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

BS (SE)-5B
15 January 2023

private set

_userManager = value;

//

// GET: /Manage/Index

public async Task<ActionResult> Index(ManageMessageId? message)

ViewBag.StatusMessage =

message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."

: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."

: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication


provider has been set."

: message == ManageMessageId.Error ? "An error has occurred."

: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."

: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."

: "";

var userId = User.Identity.GetUserId();

var model = new IndexViewModel

HasPassword = HasPassword(),

PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),

TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),

Logins = await UserManager.GetLoginsAsync(userId),

BrowserRemembered = await
AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)

BS (SE)-5B
15 January 2023

};

return View(model);

//

// POST: /Manage/RemoveLogin

[HttpPost]

[ValidateAntiForgeryToken]

public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey)

ManageMessageId? message;

var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new


UserLoginInfo(loginProvider, providerKey));

if (result.Succeeded)

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

if (user != null)

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

message = ManageMessageId.RemoveLoginSuccess;

else

message = ManageMessageId.Error;

return RedirectToAction("ManageLogins", new { Message = message });

BS (SE)-5B
15 January 2023

//

// GET: /Manage/AddPhoneNumber

public ActionResult AddPhoneNumber()

return View();

//

// POST: /Manage/AddPhoneNumber

[HttpPost]

[ValidateAntiForgeryToken]

public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)

if (!ModelState.IsValid)

return View(model);

// Generate the token and send it

var code = await


UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number);

if (UserManager.SmsService != null)

var message = new IdentityMessage

Destination = model.Number,

Body = "Your security code is: " + code

};

await UserManager.SmsService.SendAsync(message);

BS (SE)-5B
15 January 2023

return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number });

//

// POST: /Manage/EnableTwoFactorAuthentication

[HttpPost]

[ValidateAntiForgeryToken]

public async Task<ActionResult> EnableTwoFactorAuthentication()

await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

if (user != null)

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

return RedirectToAction("Index", "Manage");

//

// POST: /Manage/DisableTwoFactorAuthentication

[HttpPost]

[ValidateAntiForgeryToken]

public async Task<ActionResult> DisableTwoFactorAuthentication()

await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false);

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

if (user != null)

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

BS (SE)-5B
15 January 2023

return RedirectToAction("Index", "Manage");

//

// GET: /Manage/VerifyPhoneNumber

public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber)

var code = await


UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber);

// Send an SMS through the SMS provider to verify the phone number

return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel {


PhoneNumber = phoneNumber });

//

// POST: /Manage/VerifyPhoneNumber

[HttpPost]

[ValidateAntiForgeryToken]

public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)

if (!ModelState.IsValid)

return View(model);

var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(),


model.PhoneNumber, model.Code);

if (result.Succeeded)

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

BS (SE)-5B
15 January 2023

if (user != null)

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess });

// If we got this far, something failed, redisplay form

ModelState.AddModelError("", "Failed to verify phone");

return View(model);

//

// POST: /Manage/RemovePhoneNumber

[HttpPost]

[ValidateAntiForgeryToken]

public async Task<ActionResult> RemovePhoneNumber()

var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null);

if (!result.Succeeded)

return RedirectToAction("Index", new { Message = ManageMessageId.Error });

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

if (user != null)

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess });

BS (SE)-5B
15 January 2023

//

// GET: /Manage/ChangePassword

public ActionResult ChangePassword()

return View();

//

// POST: /Manage/ChangePassword

[HttpPost]

[ValidateAntiForgeryToken]

public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)

if (!ModelState.IsValid)

return View(model);

var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(),


model.OldPassword, model.NewPassword);

if (result.Succeeded)

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

if (user != null)

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess


});

BS (SE)-5B
15 January 2023

AddErrors(result);

return View(model);

//

// GET: /Manage/SetPassword

public ActionResult SetPassword()

return View();

//

// POST: /Manage/SetPassword

[HttpPost]

[ValidateAntiForgeryToken]

public async Task<ActionResult> SetPassword(SetPasswordViewModel model)

if (ModelState.IsValid)

var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(),


model.NewPassword);

if (result.Succeeded)

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

if (user != null)

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

BS (SE)-5B
15 January 2023

return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });

AddErrors(result);

// If we got this far, something failed, redisplay form

return View(model);

//

// GET: /Manage/ManageLogins

public async Task<ActionResult> ManageLogins(ManageMessageId? message)

ViewBag.StatusMessage =

message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."

: message == ManageMessageId.Error ? "An error has occurred."

: "";

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

if (user == null)

return View("Error");

var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId());

var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth =>


userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();

ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;

return View(new ManageLoginsViewModel

CurrentLogins = userLogins,

BS (SE)-5B
15 January 2023

OtherLogins = otherLogins

});

//

// POST: /Manage/LinkLogin

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult LinkLogin(string provider)

// Request a redirect to the external login provider to link a login for the current user

return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback",


"Manage"), User.Identity.GetUserId());

//

// GET: /Manage/LinkLoginCallback

public async Task<ActionResult> LinkLoginCallback()

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey,


User.Identity.GetUserId());

if (loginInfo == null)

return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });

var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);

return result.Succeeded ? RedirectToAction("ManageLogins") :


RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });

BS (SE)-5B
15 January 2023

protected override void Dispose(bool disposing)

if (disposing && _userManager != null)

_userManager.Dispose();

_userManager = null;

base.Dispose(disposing);

#region Helpers

// Used for XSRF protection when adding external logins

private const string XsrfKey = "XsrfId";

private IAuthenticationManager AuthenticationManager

get

return HttpContext.GetOwinContext().Authentication;

private void AddErrors(IdentityResult result)

foreach (var error in result.Errors)

ModelState.AddModelError("", error);

BS (SE)-5B
15 January 2023

private bool HasPassword()

var user = UserManager.FindById(User.Identity.GetUserId());

if (user != null)

return user.PasswordHash != null;

return false;

private bool HasPhoneNumber()

var user = UserManager.FindById(User.Identity.GetUserId());

if (user != null)

return user.PhoneNumber != null;

return false;

public enum ManageMessageId

AddPhoneSuccess,

ChangePasswordSuccess,

SetTwoFactorSuccess,

SetPasswordSuccess,

RemoveLoginSuccess,

BS (SE)-5B
15 January 2023

RemovePhoneSuccess,

Error

#endregion

MODELS
INVENTRY MODEL
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;
using PharmAssistent.Models.PurchaseModel;
using PharmAssistent.Models.InventoryModel;

namespace PharmAssistent.Models.InventoryModel
{
[Table("DrugGenericName")]
public class DrugGenericName
{
public int ID { get; set; }

[Required]
[StringLength(50, ErrorMessage="Maximum limit exceeded")]
public string GenericName { get; set; }
public string Description { get; set; }

public virtual ICollection<Item> Items { get; set; }

}
}
ITEM MODEL
using PharmAssistent.Models.PurchaseModel;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;

namespace PharmAssistent.Models.InventoryModel
{

BS (SE)-5B
15 January 2023

[Table("Item")]
public class Item
{
[Key]
[Display(Name = "Item No")]
public int ID { get; set; }

[Required]
[Display(Name="Item")]
public string Name { get; set; }

[Required]
[Display(Name="Generic Name")]
public int? DrugGenericNameID { get; set; }

[Required]
[Display(Name = "Manufacturer")]
public int? ManufacturerID { get; set; }

[Required]
[Display(Name = "Categeory")]
public string Categeory { get; set; }

public int AlertQty { get; set; }


public string Description { get; set; }

[Display(Name = "Last Update")]


[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode =
true)]
public DateTime LastUpdated { get; set; }

//reference entity
public virtual DrugGenericName DrugGenericName { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
//public virtual ICollection<Stock> Stocks { get; set; }
// COMENT public virtual ICollection<PurchaseItem> PurchaseItems { get; set;
}

}
public enum Categeory
{
Drug,
Supplies,
other
}

public enum Measurement


{
ml, mg, gm, kg, others

public enum UnitType


{
pkg, file, pcs, other
}

BS (SE)-5B
15 January 2023

MANUFACTURE MODEL
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;
using PharmAssistent.Models.PurchaseModel;

namespace PharmAssistent.Models.InventoryModel
{
[Table("Manufacturer")]
public class Manufacturer
{
public int ID { get; set; }
[Required]
[StringLength(50, ErrorMessage="Too lengthy")]
public String ManufacturerName { get; set; }
public string Description { get; set; }

// public virtual ICollection<Item> Items { get; set; }


public virtual ICollection<Item> Items { get; set; }

}
}
STOCK MODEL
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using PharmAssistent.Models.PurchaseModel;
using System.ComponentModel.DataAnnotations.Schema;

namespace PharmAssistent.Models.InventoryModel
{
[Table("Stock")]
public class Stock
{
public Stock()
{

Stop_Notification = true;
//ItemExpired = false;
}
[Key]
public int ID { get; set; }
[Required]
public int ItemID { get; set; }

[StringLength(20, ErrorMessage = "Too long. Plese check again!")]


public string Batch { get; set; }

BS (SE)-5B
15 January 2023

[Range(0, 9999999)]
public int Qty { get; set; }

//[Required]
//[Range(0, 100000)]
//public int Qty { get; set; }

[Required]
[Range(0, 1000000, ErrorMessage = "Out of range!")]
public decimal CostPrice { get; set; }

[Required]
[Range(0, 1000000, ErrorMessage = "Out of range!")]
public decimal SellingPrice { get; set; }

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode =
true)]
public DateTime? ManufactureDate { get; set; }

[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode =
true)]
public DateTime? Expiry { get; set; }

[NotMapped]
public bool ItemExpired { get; set; }
[NotMapped]
public bool Stop_Notification { get; set; }

public string PurchaseID { get; set; }

//references
public virtual Item Item { get; set; }
}
}

VIEWS
PURCHASE ENTRY VIEW MODEL
using PharmAssistent.Models;

using PharmAssistent.Models.PurchaseModel;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PharmAssistent.ViewModel
{

BS (SE)-5B
15 January 2023

// [Table("Purchase")]
public class PurchaseEntryVM
{
// PharmContext db = new PharmContext();
[Key]
public int ID { get; set; }
public string PurchaseID { get; set; }
public DateTime Date { get; set; }
public int SupplierID { get; set; }
public decimal Amount { get; set; }
public decimal? Discount { get; set; }
public decimal? Tax { get; set; }
public decimal GrandTotal { get; set; }
public bool IsPaid { get; set; }
public string Description { get; set; }
public DateTime LastUpdated { get; set; }

public List<PurchaseItem> PurchaseItems { get; set; }

}
}

BS (SE)-5B

You might also like