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

Manual de Codigo

This document contains code for controllers in a .NET Core application. It defines controllers for managing categories of products and clients. The controllers implement CRUD operations and use a database context to retrieve and save data.

Uploaded by

Ana Samayoa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Manual de Codigo

This document contains code for controllers in a .NET Core application. It defines controllers for managing categories of products and clients. The controllers implement CRUD operations and use a database context to retrieve and save data.

Uploaded by

Ana Samayoa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

CONTROLLERS

#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using StorePlace.Models;

namespace StorePlace.Controllers
{
[Authorize(Roles = "Administrador,Bodeguero")]
public class CategoriaProductoesController : Controller
{
private readonly storeplacedbContext _context;

public CategoriaProductoesController(storeplacedbContext context)


{
_context = context;
}

// GET: CategoriaProductoes
public async Task<IActionResult> Index()
{
ViewBag.Message = TempData["Message"];
ViewBag.Class = TempData["class"];
ViewBag.Icon = TempData["icon"];
return View(await _context.CategoriaProductos.ToListAsync());
}

// GET: CategoriaProductoes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}

var categoriaProducto = await _context.CategoriaProductos


.FirstOrDefaultAsync(m => m.Idcategoria == id);
if (categoriaProducto == null)
{
return NotFound();
}

return View(categoriaProducto);
}

// GET: CategoriaProductoes/Create
public IActionResult Create()
{
ViewBag.Message = TempData["Message"];
return View();
}

// POST: CategoriaProductoes/Create
// To protect from overposting attacks, enable the specific
properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?
LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult>
Create([Bind("Idcategoria,Descripcion")] CategoriaProducto
categoriaProducto)
{
if (ModelState.IsValid)
{
_context.Add(categoriaProducto);
await _context.SaveChangesAsync();
TempData["Message"] = "El registro se guardo correctamente";
TempData["class"] = "alert alert-success alert-dismissible
fade show";
TempData["icon"] = "bi bi-check-circle me-1";
return RedirectToAction(nameof(Index));
}
else
{
TempData["Message"] = "Llene todos los campos
correctamente";
}
return View(categoriaProducto);
}

// GET: CategoriaProductoes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}

var categoriaProducto = await


_context.CategoriaProductos.FindAsync(id);
if (categoriaProducto == null)
{
return NotFound();
}
return View(categoriaProducto);
}

// POST: CategoriaProductoes/Edit/5
// To protect from overposting attacks, enable the specific
properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?
LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id,
[Bind("Idcategoria,Descripcion")] CategoriaProducto categoriaProducto)
{
if (id != categoriaProducto.Idcategoria)
{
return NotFound();
}

if (ModelState.IsValid)
{
try
{
_context.Update(categoriaProducto);
TempData["Message"] = "El registro se actualizo
correctamente";
TempData["class"] = "alert alert-success alert-
dismissible fade show";
TempData["icon"] = "bi bi-check-circle me-1";

await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!
CategoriaProductoExists(categoriaProducto.Idcategoria))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}

return View(categoriaProducto);
}

// GET: CategoriaProductoes/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}

var categoriaProducto = await _context.CategoriaProductos


.FirstOrDefaultAsync(m => m.Idcategoria == id);
if (categoriaProducto == null)
{
return NotFound();
}

return View(categoriaProducto);
}

// POST: CategoriaProductoes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var categoriaProducto = await
_context.CategoriaProductos.FindAsync(id);
_context.CategoriaProductos.Remove(categoriaProducto);
TempData["Message"] = $"La categoria
'{categoriaProducto.Descripcion}' se elimino correctamente";
TempData["class"] = "alert alert-info alert-dismissible fade
show";
TempData["icon"] = "bi bi-info-circle me-1";
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}

private bool CategoriaProductoExists(int id)


{
return _context.CategoriaProductos.Any(e => e.Idcategoria ==
id);
}
}
}

#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using StorePlace.Models;

namespace StorePlace.Controllers
{
[Authorize(Roles = "Administrador,Cajero")]
public class ClientesController : Controller
{
private readonly storeplacedbContext _context;

public ClientesController(storeplacedbContext context)


{
_context = context;
}

// GET: Clientes
public async Task<IActionResult> Index()
{
ViewBag.Message = TempData["Message"];
ViewBag.Class = TempData["class"];
ViewBag.Icon = TempData["icon"];
var storeplacedbContext = _context.Clientes.Include(c =>
c.IdctgclienteNavigation);
return View(await storeplacedbContext.ToListAsync());
}

// GET: Clientes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}

var cliente = await _context.Clientes


.Include(c => c.IdctgclienteNavigation)
.FirstOrDefaultAsync(m => m.Idcliente == id);
if (cliente == null)
{
return NotFound();
}

return View(cliente);
}

// GET: Clientes/Create
public IActionResult Create()
{
ViewData["Idctgcliente"] = new
SelectList(_context.CategoriaClientes, "Idcategoria", "Idcategoria");
return View();
}

// POST: Clientes/Create
// To protect from overposting attacks, enable the specific
properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?
LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult>
Create([Bind("Idcliente,Nit,Idctgcliente,Nombre,Apellido,Direccion,Telefono"
)] Cliente cliente)
{
if (ModelState.IsValid)
{
_context.Add(cliente);
TempData["Message"] = "El registro se guardo correctamente";
TempData["class"] = "alert alert-success alert-dismissible
fade show";
TempData["icon"] = "bi bi-check-circle me-1";
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["Idctgcliente"] = new
SelectList(_context.CategoriaClientes, "Idcategoria", "Idcategoria",
cliente.Idctgcliente);
return View(cliente);
}

// GET: Clientes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}

var cliente = await _context.Clientes.FindAsync(id);


if (cliente == null)
{
return NotFound();
}
ViewData["Idctgcliente"] = new
SelectList(_context.CategoriaClientes, "Idcategoria", "Idcategoria",
cliente.Idctgcliente);
return View(cliente);
}

// POST: Clientes/Edit/5
// To protect from overposting attacks, enable the specific
properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?
LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id,
[Bind("Idcliente,Nit,Idctgcliente,Nombre,Apellido,Direccion,Telefono")]
Cliente cliente)
{
if (id != cliente.Idcliente)
{
return NotFound();
}

if (ModelState.IsValid)
{
try
{
_context.Update(cliente);
TempData["Message"] = "El registro se actualizo
correctamente";
TempData["class"] = "alert alert-success alert-
dismissible fade show";
TempData["icon"] = "bi bi-check-circle me-1";
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ClienteExists(cliente.Idcliente))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["Idctgcliente"] = new
SelectList(_context.CategoriaClientes, "Idcategoria", "Idcategoria",
cliente.Idctgcliente);
return View(cliente);
}

// GET: Clientes/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var cliente = await _context.Clientes
.Include(c => c.IdctgclienteNavigation)
.FirstOrDefaultAsync(m => m.Idcliente == id);
if (cliente == null)
{
return NotFound();
}

return View(cliente);
}

// POST: Clientes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var cliente = await _context.Clientes.FindAsync(id);
_context.Clientes.Remove(cliente);
TempData["Message"] = $"El Cliente '{cliente.Nombre}
{cliente.Apellido}' se elimino correctamente";
TempData["class"] = "alert alert-info alert-dismissible fade
show";
TempData["icon"] = "bi bi-info-circle me-1";
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}

private bool ClienteExists(int id)


{
return _context.Clientes.Any(e => e.Idcliente == id);
}
}
}

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StorePlace.Models;
using System.Diagnostics;

namespace StorePlace.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly storeplacedbContext _context;

public HomeController(ILogger<HomeController> logger,


storeplacedbContext context)
{
_logger = logger;
_context = context;
}

public IActionResult Index()


{
var Productos = _context.Productos.ToList().Count;
var Proveedores = _context.Proveedors.ToList().Count;
var today = DateTime.Today.ToString("dd/MM/yyyy");
var mes = DateTime.Now.ToString("MM/yyyy");
var año = DateTime.Now.ToString("yyyy");
var VentasHoy = _context.Venta.FromSqlRaw("SELECT * FROM venta
WHERE date_format(FECHA, '%d/%m/%Y') = {0}",
today.ToString()).ToList().Count;
var VentasMes = _context.Venta.FromSqlRaw("SELECT * FROM venta
WHERE date_format(FECHA, '%m/%Y') = {0}", mes.ToString()).ToList().Count;
var VentasAño = _context.Venta.FromSqlRaw("SELECT * FROM venta
WHERE date_format(FECHA, '%Y') = {0}", año.ToString()).ToList().Count;
Tuple<int, int, int, int, int> model = new Tuple<int, int, int,
int, int>(Productos, Proveedores, VentasHoy, VentasMes, VentasAño);
return View(model);
}

public IActionResult Privacy()


{
return View();
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None,


NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId =
Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
using Microsoft.AspNetCore.Mvc;
using StorePlace.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;

namespace StorePlace.Controllers
{
public class LoginController : Controller
{
private readonly storeplacedbContext _context;

public LoginController(storeplacedbContext context)


{
_context = context;
}

public IActionResult Index()


{
return View();
}

[HttpPost]
public async Task<IActionResult> Index(Usuario user)
{
Usuario _user = UserIsvalid(user);
if (_user != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier,
_user.Idusuario.ToString()),
new Claim(ClaimTypes.Name, _user.Nombre + " " +
_user.Apellido),
new Claim(ClaimTypes.Email, _user.Correo),
};

claims.Add(new Claim(ClaimTypes.Role,
_user.IdrolNavigation.Descripcion));

var claimsIdentity = new ClaimsIdentity(claims,


CookieAuthenticationDefaults.AuthenticationScheme);
await
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity));

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


}
else
{
return View();
}
}

public async Task<IActionResult> LoginOut()


{

await
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

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


}

private Usuario UserIsvalid(Usuario user)


{
Usuario usuario;
user.Contraseña = Encrypt.Encriptar(user.Contraseña);
usuario = _context.Usuarios.Where(e => e.Correo == user.Correo
&& e.Contraseña == user.Contraseña).Include(p =>
p.IdrolNavigation).FirstOrDefault();
return usuario;
}
}
}

#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using MySql.Data.MySqlClient;
using StorePlace.ClsJsonR;
using StorePlace.Models;

namespace StorePlace.Controllers
{
[Authorize(Roles = "Bodeguero,Administrador")]
//[Authorize(Roles = "Administrador")]
public class ProductosController : Controller
{
private readonly storeplacedbContext _context;
private readonly string _cn;

public ProductosController(storeplacedbContext context,


IConfiguration config)
{
_context = context;
_cn = config.GetConnectionString("default");
}

// GET: Productos
public async Task<IActionResult> Index()
{
ViewBag.Message = TempData["Message"];
ViewBag.Class = TempData["class"];
ViewBag.Icon = TempData["icon"];
var storeplacedbContext = _context.Productos.Include(p =>
p.IdcategoriaNavigation);
return View(await storeplacedbContext.ToListAsync());
}

public JsonResult GetProducts()


{
List<JProducto> Products = new List<JProducto>();
using (var cn = new MySqlConnection(_cn))
{
cn.Open();
MySqlCommand cmd = new MySqlCommand("GETPRODUCTS", cn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Products.Add(new JProducto
{
Barcode = reader["Barcode"].ToString(),
Nombre = reader["Nombre"].ToString(),
Categoria = reader["Descripcion"].ToString(),
Precio = Convert.ToDecimal(reader["Precio"]),
Costo = Convert.ToDecimal(reader["Costo"]),
Stock = Convert.ToInt32(reader["Stock"]),
Porcganacia =
Convert.ToDecimal(reader["Porcganacia"]),
});
}
}
}
return Json(new { Data = Products });
}

// GET: Productos/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return NotFound();
}

var producto = await _context.Productos


.Include(p => p.IdcategoriaNavigation)
.FirstOrDefaultAsync(m => m.Barcode == id);
if (producto == null)
{
return NotFound();
}

return View(producto);
}

// GET: Productos/Create
public IActionResult Create()
{
ViewBag.MessageErr = TempData["Message_err"];
ViewData["Idcategoria"] = new
SelectList(_context.CategoriaProductos, "Idcategoria", "Descripcion");
return View();
}

// POST: Productos/Create
// To protect from overposting attacks, enable the specific
properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?
LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult>
Create([Bind("Barcode,Idcategoria,Nombre,Costo,Porcganacia,Stock,Precio")]
Producto producto)
{
if (ModelState.IsValid)
{
_context.Add(producto);
TempData["Message"] = "El registro se guardo correctamente";
TempData["class"] = "alert alert-success alert-dismissible
fade show";
TempData["icon"] = "bi bi-check-circle me-1";
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
else if (!ModelState.IsValid) {
TempData["Message_err"] = "Llene todos los campos
correctamente";

TempData["Message_err"] = "Llene todos los campos


correctamente";
ViewData["Idcategoria"] = new
SelectList(_context.CategoriaProductos, "Idcategoria", "Descripcion",
producto.Idcategoria);
return View(producto);
}

// GET: Productos/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return NotFound();
}

var producto = await _context.Productos.FindAsync(id);


if (producto == null)
{
return NotFound();
}
ViewData["Idcategoria"] = new
SelectList(_context.CategoriaProductos, "Idcategoria", "Descripcion",
producto.Idcategoria);
return View(producto);
}

// POST: Productos/Edit/5
// To protect from overposting attacks, enable the specific
properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?
LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id,
[Bind("Barcode,Idcategoria,Nombre,Costo,Porcganacia,Stock,Precio")] Producto
producto)
{
if (id != producto.Barcode)
{
return NotFound();
}

if (ModelState.IsValid)
{
try
{
_context.Update(producto);
TempData["Message"] = "El registro se actualizo
correctamente";
TempData["class"] = "alert alert-success alert-
dismissible fade show";
TempData["icon"] = "bi bi-check-circle me-1";
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductoExists(producto.Barcode))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["Idcategoria"] = new
SelectList(_context.CategoriaProductos, "Idcategoria", "Descripcion",
producto.Idcategoria);
return View(producto);
}

// GET: Productos/Delete/5
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return NotFound();
}

var producto = await _context.Productos


.Include(p => p.IdcategoriaNavigation)
.FirstOrDefaultAsync(m => m.Barcode == id);
if (producto == null)
{
return NotFound();
}

return View(producto);
}

// POST: Productos/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
var producto = await _context.Productos.FindAsync(id);
_context.Productos.Remove(producto);
TempData["Message"] = $"El Producto '{producto.Nombre}' se
elimino correctamente";
TempData["class"] = "alert alert-info alert-dismissible fade
show";
TempData["icon"] = "bi bi-info-circle me-1";
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool ProductoExists(string id)
{
return _context.Productos.Any(e => e.Barcode == id);
}
}
}

#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using StorePlace.Models;

namespace StorePlace.Controllers
{
[Authorize(Roles = "Administrador,Bodeguero")]
public class ProveedoresController : Controller
{
private readonly storeplacedbContext _context;

public ProveedoresController(storeplacedbContext context)


{
_context = context;
}

// GET: Proveedores
public async Task<IActionResult> Index()
{
ViewBag.Message = TempData["Message"];
ViewBag.Class = TempData["class"];
ViewBag.Icon = TempData["icon"];
return View(await _context.Proveedors.ToListAsync());
}

// GET: Proveedores/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}

var proveedor = await _context.Proveedors


.FirstOrDefaultAsync(m => m.Idproveedor == id);
if (proveedor == null)
{
return NotFound();
}

return View(proveedor);
}

// GET: Proveedores/Create
public IActionResult Create()
{
return View();
}

// POST: Proveedores/Create
// To protect from overposting attacks, enable the specific
properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?
LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult>
Create([Bind("Idproveedor,Nombre,Direccion,Telefono")] Proveedor proveedor)
{
if (ModelState.IsValid)
{
_context.Add(proveedor);
TempData["Message"] = "El registro se guardo correctamente";
TempData["class"] = "alert alert-success alert-dismissible
fade show";
TempData["icon"] = "bi bi-check-circle me-1";
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(proveedor);
}

// GET: Proveedores/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}

var proveedor = await _context.Proveedors.FindAsync(id);


if (proveedor == null)
{
return NotFound();
}
return View(proveedor);
}

// POST: Proveedores/Edit/5
// To protect from overposting attacks, enable the specific
properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?
LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id,
[Bind("Idproveedor,Nombre,Direccion,Telefono")] Proveedor proveedor)
{
if (id != proveedor.Idproveedor)
{
return NotFound();
}

if (ModelState.IsValid)
{
try
{
_context.Update(proveedor);
TempData["Message"] = "El registro se actualizo
correctamente";
TempData["class"] = "alert alert-success alert-
dismissible fade show";
TempData["icon"] = "bi bi-check-circle me-1";
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProveedorExists(proveedor.Idproveedor))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(proveedor);
}

// GET: Proveedores/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}

var proveedor = await _context.Proveedors


.FirstOrDefaultAsync(m => m.Idproveedor == id);
if (proveedor == null)
{
return NotFound();
}

return View(proveedor);
}

// POST: Proveedores/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var proveedor = await _context.Proveedors.FindAsync(id);
TempData["Message"] = $"El Proveedor '{proveedor.Nombre}' se
elimino correctamente";
TempData["class"] = "alert alert-info alert-dismissible fade
show";
TempData["icon"] = "bi bi-info-circle me-1";
_context.Proveedors.Remove(proveedor);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}

private bool ProveedorExists(int id)


{
return _context.Proveedors.Any(e => e.Idproveedor == id);
}
}
}

#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using StorePlace.Models;
using StorePlace.Models.ViewsModels;
using Microsoft.AspNetCore.Authorization;

namespace StorePlace.Controllers
{
[Authorize(Roles = "Administrador")]
public class UsuariosController : Controller
{
private readonly storeplacedbContext _context;

public UsuariosController(storeplacedbContext context)


{
_context = context;
}

// GET: Usuarios
public async Task<IActionResult> Index()
{
ViewBag.Message = TempData["Message"];
ViewBag.Class = TempData["class"];
ViewBag.Icon = TempData["icon"];
var storeplacedbContext = _context.Usuarios.Include(u =>
u.IdrolNavigation);
return View(await storeplacedbContext.ToListAsync());
}

// GET: Usuarios/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}

var usuario = await _context.Usuarios


.Include(u => u.IdrolNavigation)
.FirstOrDefaultAsync(m => m.Idusuario == id);
if (usuario == null)
{
return NotFound();
}

return View(usuario);
}

// GET: Usuarios/Create
public IActionResult Create()
{
//ViewBag.MessageErr = TempData["Message_err"];
ViewData["Idrol"] = new SelectList(_context.Rols, "Idrol",
"Descripcion");
return View();
}

// POST: Usuarios/Create
// To protect from overposting attacks, enable the specific
properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?
LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult>
Create([Bind("Idusuario,Nombre,Apellido,Correo,Idrol,Contraseña")] Usuario
usuario)
{
if (UsuarioExists(usuario.Correo))
{
TempData["Message_err"] = "Este usuario ya existe";
ViewData["Idrol"] = new SelectList(_context.Rols, "Idrol",
"Descripcion", usuario.Idrol);
return View(usuario);
}
else
{
usuario.Contraseña = Encrypt.Encriptar(usuario.Contraseña);
_context.Add(usuario);
TempData["Message"] = "El registro se guardo correctamente";
TempData["class"] = "alert alert-success alert-dismissible
fade show";
TempData["icon"] = "bi bi-check-circle me-1";
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}

// GET: Usuarios/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}

var usuario = await _context.Usuarios.FindAsync(id);


if (usuario == null)
{
return NotFound();
}
ViewData["Idrol"] = new SelectList(_context.Rols, "Idrol",
"Descripcion", usuario.Idrol);
return View(usuario);
}

// POST: Usuarios/Edit/5
// To protect from overposting attacks, enable the specific
properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?
LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id,
[Bind("Idusuario,Nombre,Apellido,Correo,Idrol,Contraseña")] Usuario usuario)
{
if (id != usuario.Idusuario)
{
return NotFound();
}
_context.Update(usuario);
TempData["Message"] = "El registro se actualizo correctamente";
TempData["class"] = "alert alert-success alert-dismissible fade
show";
TempData["icon"] = "bi bi-check-circle me-1";
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
ViewData["Idrol"] = new SelectList(_context.Rols, "Idrol",
"Descripcion", usuario.Idrol);
return View(usuario);
}

// GET: Usuarios/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}

var usuario = await _context.Usuarios


.Include(u => u.IdrolNavigation)
.FirstOrDefaultAsync(m => m.Idusuario == id);
if (usuario == null)
{
return NotFound();
}

return View(usuario);
}

// POST: Usuarios/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var usuario = await _context.Usuarios.FindAsync(id);
_context.Usuarios.Remove(usuario);
TempData["Message"] = $"El Producto '{usuario.Nombre}
{usuario.Apellido}' se elimino correctamente";
TempData["class"] = "alert alert-info alert-dismissible fade
show";
TempData["icon"] = "bi bi-info-circle me-1";
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}

private bool UsuarioExists(string correo)


{
return _context.Usuarios.Any(e => e.Correo == correo);
}

}
}

#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using StorePlace.Models;
using StorePlace.Models.ViewsModels;

namespace StorePlace.Controllers
{
[Authorize(Roles = "Administrador,Cajero")]
public class VentasController : Controller
{
private readonly storeplacedbContext _context;

public VentasController(storeplacedbContext context)


{
_context = context;
}

// GET: Ventas
public async Task<IActionResult> Index()
{
var storeplacedbContext = _context.Venta.Include(v =>
v.IdclienteNavigation).Include(v => v.IdusuarioNavigation);
return View(await storeplacedbContext.ToListAsync());
}

// GET: Ventas/Details/5
public async Task<IActionResult> Details(uint? id)
{
if (id == null)
{
return NotFound();
}

var venta = await _context.Venta


.Include(v => v.IdclienteNavigation)
.Include(v => v.IdusuarioNavigation)
.FirstOrDefaultAsync(m => m.Idventa == id);
if (venta == null)
{
return NotFound();
}

return View(venta);
}

// GET: Ventas/Create
public IActionResult Create()
{
IEnumerable<Producto> Productos = _context.Productos.Include(p
=> p.IdcategoriaNavigation);
Tuple<Venta, IEnumerable<Producto>> model = new Tuple<Venta,
IEnumerable<Producto>>(new Venta(), Productos);
var Cliente = _context.Clientes.Select(x => new { x.Idcliente,
Nombre = string.Join(" ", x.Nit, x.Nombre, x.Apellido) }).ToList();
ViewData["Idcliente"] = new SelectList(Cliente, "Idcliente",
"Nombre");
ViewData["Idproducto"] = new SelectList(_context.Productos,
"Barcode", "Nombre");
return View(model);
}

// POST: Ventas/Create
// To protect from overposting attacks, enable the specific
properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?
LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult>
Create([Bind("Idventa,Idcliente,Idusuario,Fecha,Total")] Venta venta)
{
if (ModelState.IsValid)
{
_context.Add(venta);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["Idcliente"] = new SelectList(_context.Clientes,
"Idcliente", "Idcliente", venta.Idcliente);
ViewData["Idusuario"] = new SelectList(_context.Usuarios,
"Idusuario", "Idusuario", venta.Idusuario);
return View(venta);
}

// GET: Ventas/Edit/5
public async Task<IActionResult> Edit(uint? id)
{
if (id == null)
{
return NotFound();
}

var venta = await _context.Venta.FindAsync(id);


if (venta == null)
{
return NotFound();
}
ViewData["Idcliente"] = new SelectList(_context.Clientes,
"Idcliente", "Idcliente", venta.Idcliente);
ViewData["Idusuario"] = new SelectList(_context.Usuarios,
"Idusuario", "Idusuario", venta.Idusuario);
return View(venta);
}

[HttpPost]
public JsonResult Add(VentaViewModel venta)
{
using (var Transaccion = _context.Database.BeginTransaction())
{
try
{
Venta _Venta = new Venta
{
Idcliente = venta.Idcliente,
Idusuario = venta.Idusuario,
Fecha = Convert.ToDateTime(DateTime.Now),
Total = venta.Total
};

_context.Add(_Venta);
_context.SaveChanges();

foreach (var oC in venta.DetalleVenta)


{
DetalleVenta oConcepto = new DetalleVenta
{
Cantidad = oC.Cantidad,
Idproducto = oC.Idproducto,
Precio = oC.Precio,
Subtotal = oC.Cantidad * oC.Precio,
Idventa = _Venta.Idventa
};
_context.Add(oConcepto);
}

_context.SaveChanges();
//ViewBag.Message = "Registro insertado";
Transaccion.Commit();

return Json(true);
}
catch (Exception ex)
{
Transaccion.Rollback();
return Json(venta);
}
}

private bool VentaExists(uint id)


{
return _context.Venta.Any(e => e.Idventa == id);
}
}
}

MODELS
using System;
using System.Collections.Generic;

namespace StorePlace.Models
{
public partial class CategoriaCliente
{
public CategoriaCliente()
{
Clientes = new HashSet<Cliente>();
}

public int Idcategoria { get; set; }


public string Descripcion { get; set; } = null!;

public virtual ICollection<Cliente> Clientes { get; set; }


}
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace StorePlace.Models
{
public partial class Venta
{
public Venta()
{
DetalleVenta = new HashSet<DetalleVenta>();
}

public uint Idventa { get; set; }


[Display(Name = "Cliente")]
public int? Idcliente { get; set; }
public int Idusuario { get; set; }
public DateTime? Fecha { get; set; }
public decimal? Total { get; set; }

public virtual Cliente? IdclienteNavigation { get; set; }


public virtual Usuario IdusuarioNavigation { get; set; } = null!;
public virtual ICollection<DetalleVenta> DetalleVenta { get; set; }
}
}

using System;
using System.Collections.Generic;

namespace StorePlace.Models
{
public partial class Usuario
{
public Usuario()
{
Ingresos = new HashSet<Ingreso>();
Venta = new HashSet<Venta>();
}

public int Idusuario { get; set; }


public string Nombre { get; set; } = null!;
public string Apellido { get; set; } = null!;
public string Correo { get; set; } = null!;
public int Idrol { get; set; }
public string Contraseña { get; set; } = null!;

public virtual Rol IdrolNavigation { get; set; } = null!;


public virtual ICollection<Ingreso> Ingresos { get; set; }
public virtual ICollection<Venta> Venta { get; set; }
}
}

using System;
using System.Collections.Generic;

namespace StorePlace.Models
{
public partial class Proveedor
{
public Proveedor()
{
Ingresos = new HashSet<Ingreso>();
}

public int Idproveedor { get; set; }


public string Nombre { get; set; } = null!;
public string Direccion { get; set; } = null!;
public string Telefono { get; set; } = null!;

public virtual ICollection<Ingreso> Ingresos { get; set; }


}
}

using System;
using System.Collections.Generic;

namespace StorePlace.Models
{
public partial class Producto
{
public Producto()
{
DetalleIngresos = new HashSet<DetalleIngreso>();
DetalleVenta = new HashSet<DetalleVenta>();
}

public string Barcode { get; set; } = null!;


public int? Idcategoria { get; set; }
public string Nombre { get; set; } = null!;
public decimal Costo { get; set; }
public decimal Porcganacia { get; set; }
public int Stock { get; set; }
public decimal Precio { get; set; }

public virtual CategoriaProducto? IdcategoriaNavigation { get;


set; }
public virtual ICollection<DetalleIngreso> DetalleIngresos { get;
set; }
public virtual ICollection<DetalleVenta> DetalleVenta { get; set; }
}
}
using System;
using System.Collections.Generic;

namespace StorePlace.Models
{
public partial class DetalleIngreso
{
public int IddetalleIngreso { get; set; }
public int Idingreso { get; set; }
public string? Idproducto { get; set; }
public int Cantidad { get; set; }
public decimal? Precio { get; set; }

public virtual Ingreso IdingresoNavigation { get; set; } = null!;


public virtual Producto? IdproductoNavigation { get; set; }
}
}

using System;
using System.Collections.Generic;

namespace StorePlace.Models
{
public partial class Cliente
{
public Cliente()
{
Venta = new HashSet<Venta>();
}

public int Idcliente { get; set; }


public string? Nit { get; set; }
public int? Idctgcliente { get; set; }
public string Nombre { get; set; } = null!;
public string Apellido { get; set; } = null!;
public string Direccion { get; set; } = null!;
public string? Telefono { get; set; }

public virtual CategoriaCliente? IdctgclienteNavigation { get;


set; }
public virtual ICollection<Venta> Venta { get; set; }
}
}
DBCONTEXT. INJECCION DE DEPENDENCIAS

using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace StorePlace.Models
{
public partial class storeplacedbContext : DbContext
{
public storeplacedbContext()
{
}

public storeplacedbContext(DbContextOptions<storeplacedbContext>
options)
: base(options)
{
}

public virtual DbSet<CategoriaCliente> CategoriaClientes { get; set;


} = null!;
public virtual DbSet<CategoriaProducto> CategoriaProductos { get;
set; } = null!;
public virtual DbSet<Cliente> Clientes { get; set; } = null!;
public virtual DbSet<DetalleIngreso> DetalleIngresos { get; set; } =
null!;
public virtual DbSet<DetalleVenta> DetalleVenta { get; set; } =
null!;
public virtual DbSet<Ingreso> Ingresos { get; set; } = null!;
public virtual DbSet<Producto> Productos { get; set; } = null!;
public virtual DbSet<Proveedor> Proveedors { get; set; } = null!;
public virtual DbSet<Rol> Rols { get; set; } = null!;
public virtual DbSet<Usuario> Usuarios { get; set; } = null!;
public virtual DbSet<Venta> Venta { get; set; } = null!;

protected override void OnConfiguring(DbContextOptionsBuilder


optionsBuilder)
{

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");

modelBuilder.Entity<CategoriaCliente>(entity =>
{
entity.HasKey(e => e.Idcategoria)
.HasName("PRIMARY");

entity.ToTable("categoria_cliente");

entity.Property(e => e.Idcategoria)


.HasColumnType("int(11)")
.HasColumnName("IDCATEGORIA");

entity.Property(e => e.Descripcion)


.HasMaxLength(45)
.HasColumnName("DESCRIPCION");
});

modelBuilder.Entity<CategoriaProducto>(entity =>
{
entity.HasKey(e => e.Idcategoria)
.HasName("PRIMARY");

entity.ToTable("categoria_producto");

entity.Property(e => e.Idcategoria)


.HasColumnType("int(11)")
.HasColumnName("IDCATEGORIA");

entity.Property(e => e.Descripcion)


.HasMaxLength(45)
.HasColumnName("DESCRIPCION");
});

modelBuilder.Entity<Cliente>(entity =>
{
entity.HasKey(e => e.Idcliente)
.HasName("PRIMARY");

entity.ToTable("cliente");

entity.HasIndex(e => e.Idctgcliente, "IDCTGCLIENTE");

entity.Property(e => e.Idcliente)


.HasColumnType("int(11)")
.HasColumnName("IDCLIENTE");

entity.Property(e => e.Apellido)


.HasMaxLength(45)
.HasColumnName("APELLIDO");

entity.Property(e => e.Direccion)


.HasMaxLength(45)
.HasColumnName("DIRECCION");

entity.Property(e => e.Idctgcliente)


.HasColumnType("int(11)")
.HasColumnName("IDCTGCLIENTE");

entity.Property(e => e.Nit)


.HasMaxLength(11)
.HasColumnName("NIT");

entity.Property(e => e.Nombre)


.HasMaxLength(45)
.HasColumnName("NOMBRE");

entity.Property(e => e.Telefono)


.HasMaxLength(8)
.HasColumnName("TELEFONO");

entity.HasOne(d => d.IdctgclienteNavigation)


.WithMany(p => p.Clientes)
.HasForeignKey(d => d.Idctgcliente)
.HasConstraintName("cliente_ibfk_1");
});

modelBuilder.Entity<DetalleIngreso>(entity =>
{
entity.HasKey(e => e.IddetalleIngreso)
.HasName("PRIMARY");

entity.ToTable("detalle_ingreso");

entity.HasIndex(e => e.Idingreso, "IDINGRESO");

entity.HasIndex(e => e.Idproducto, "IDPRODUCTO");

entity.Property(e => e.IddetalleIngreso)


.HasColumnType("int(11)")
.HasColumnName("IDDETALLE_INGRESO");

entity.Property(e => e.Cantidad)


.HasColumnType("int(11)")
.HasColumnName("CANTIDAD");

entity.Property(e => e.Idingreso)


.HasColumnType("int(11)")
.HasColumnName("IDINGRESO");

entity.Property(e => e.Idproducto)


.HasMaxLength(45)
.HasColumnName("IDPRODUCTO");

entity.Property(e => e.Precio)


.HasPrecision(11, 2)
.HasColumnName("PRECIO");

entity.HasOne(d => d.IdingresoNavigation)


.WithMany(p => p.DetalleIngresos)
.HasForeignKey(d => d.Idingreso)
.HasConstraintName("detalle_ingreso_ibfk_1");

entity.HasOne(d => d.IdproductoNavigation)


.WithMany(p => p.DetalleIngresos)
.HasForeignKey(d => d.Idproducto)
.HasConstraintName("detalle_ingreso_ibfk_2");
});

modelBuilder.Entity<DetalleVenta>(entity =>
{
entity.HasKey(e => e.IddetalleVenta)
.HasName("PRIMARY");

entity.ToTable("detalle_venta");

entity.HasIndex(e => e.Idproducto, "IDPRODUCTO");

entity.HasIndex(e => e.Idventa, "IDVENTA");

entity.Property(e => e.IddetalleVenta)


.HasColumnType("int(11)")
.HasColumnName("IDDETALLE_VENTA");

entity.Property(e => e.Cantidad)


.HasColumnType("int(11)")
.HasColumnName("CANTIDAD");

entity.Property(e => e.Idproducto)


.HasMaxLength(45)
.HasColumnName("IDPRODUCTO");

entity.Property(e => e.Idventa)


.HasColumnType("int(11) unsigned zerofill")
.HasColumnName("IDVENTA");

entity.Property(e => e.Precio)


.HasPrecision(6, 2)
.HasColumnName("PRECIO");

entity.Property(e => e.Subtotal)


.HasPrecision(6, 2)
.HasColumnName("SUBTOTAL");

entity.HasOne(d => d.IdproductoNavigation)


.WithMany(p => p.DetalleVenta)
.HasForeignKey(d => d.Idproducto)
.HasConstraintName("detalle_venta_ibfk_2");

entity.HasOne(d => d.IdventaNavigation)


.WithMany(p => p.DetalleVenta)
.HasForeignKey(d => d.Idventa)
.HasConstraintName("detalle_venta_ibfk_3");
});

modelBuilder.Entity<Ingreso>(entity =>
{
entity.HasKey(e => e.Idingreso)
.HasName("PRIMARY");

entity.ToTable("ingreso");

entity.HasIndex(e => e.Idproveedor, "IDPROVEEDOR");

entity.HasIndex(e => e.Idusuario, "IDUSUARIO");

entity.Property(e => e.Idingreso)


.HasColumnType("int(11)")
.HasColumnName("IDINGRESO");
entity.Property(e => e.Estado)
.HasMaxLength(45)
.HasColumnName("ESTADO");

entity.Property(e => e.Fecha)


.HasColumnType("datetime")
.HasColumnName("FECHA");

entity.Property(e => e.Idproveedor)


.HasColumnType("int(11)")
.HasColumnName("IDPROVEEDOR");

entity.Property(e => e.Idusuario)


.HasColumnType("int(11)")
.HasColumnName("IDUSUARIO");

entity.Property(e => e.Impuesto)


.HasPrecision(4, 2)
.HasColumnName("IMPUESTO");

entity.Property(e => e.Total)


.HasPrecision(11, 2)
.HasColumnName("TOTAL");

entity.HasOne(d => d.IdproveedorNavigation)


.WithMany(p => p.Ingresos)
.HasForeignKey(d => d.Idproveedor)
.HasConstraintName("ingreso_ibfk_1");

entity.HasOne(d => d.IdusuarioNavigation)


.WithMany(p => p.Ingresos)
.HasForeignKey(d => d.Idusuario)
.HasConstraintName("ingreso_ibfk_2");
});

modelBuilder.Entity<Producto>(entity =>
{
entity.HasKey(e => e.Barcode)
.HasName("PRIMARY");

entity.ToTable("producto");

entity.HasIndex(e => e.Idcategoria, "IDCATEGORIA");

entity.Property(e => e.Barcode)


.HasMaxLength(45)
.HasColumnName("BARCODE");

entity.Property(e => e.Costo)


.HasPrecision(4, 2)
.HasColumnName("COSTO");

entity.Property(e => e.Idcategoria)


.HasColumnType("int(11)")
.HasColumnName("IDCATEGORIA");

entity.Property(e => e.Nombre)


.HasMaxLength(45)
.HasColumnName("NOMBRE");

entity.Property(e => e.Porcganacia)


.HasPrecision(3, 2)
.HasColumnName("PORCGANACIA");

entity.Property(e => e.Precio)


.HasPrecision(4, 2)
.HasColumnName("PRECIO");

entity.Property(e => e.Stock)


.HasColumnType("int(11)")
.HasColumnName("STOCK");

entity.HasOne(d => d.IdcategoriaNavigation)


.WithMany(p => p.Productos)
.HasForeignKey(d => d.Idcategoria)
.HasConstraintName("producto_ibfk_2");
});

modelBuilder.Entity<Proveedor>(entity =>
{
entity.HasKey(e => e.Idproveedor)
.HasName("PRIMARY");

entity.ToTable("proveedor");

entity.Property(e => e.Idproveedor)


.HasColumnType("int(11)")
.HasColumnName("IDPROVEEDOR");

entity.Property(e => e.Direccion)


.HasMaxLength(45)
.HasColumnName("DIRECCION");

entity.Property(e => e.Nombre)


.HasMaxLength(45)
.HasColumnName("NOMBRE");

entity.Property(e => e.Telefono)


.HasMaxLength(8)
.HasColumnName("TELEFONO");
});

modelBuilder.Entity<Rol>(entity =>
{
entity.HasKey(e => e.Idrol)
.HasName("PRIMARY");

entity.ToTable("rol");

entity.Property(e => e.Idrol)


.HasColumnType("int(11)")
.HasColumnName("IDROL");

entity.Property(e => e.Descripcion)


.HasMaxLength(45)
.HasColumnName("DESCRIPCION");
});

modelBuilder.Entity<Usuario>(entity =>
{
entity.HasKey(e => e.Idusuario)
.HasName("PRIMARY");

entity.ToTable("usuario");

entity.HasIndex(e => e.Correo, "CORREO")


.IsUnique();

entity.HasIndex(e => e.Idrol, "IDROL");

entity.Property(e => e.Idusuario)


.HasColumnType("int(11)")
.HasColumnName("IDUSUARIO");

entity.Property(e => e.Apellido)


.HasMaxLength(45)
.HasColumnName("APELLIDO");

entity.Property(e => e.Contraseña)


.HasMaxLength(256)
.HasColumnName("CONTRASEÑA");

entity.Property(e => e.Correo)


.HasMaxLength(45)
.HasColumnName("CORREO");

entity.Property(e => e.Idrol)


.HasColumnType("int(11)")
.HasColumnName("IDROL");

entity.Property(e => e.Nombre)


.HasMaxLength(45)
.HasColumnName("NOMBRE");

entity.HasOne(d => d.IdrolNavigation)


.WithMany(p => p.Usuarios)
.HasForeignKey(d => d.Idrol)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("usuario_ibfk_1");
});

modelBuilder.Entity<Venta>(entity =>
{
entity.HasKey(e => e.Idventa)
.HasName("PRIMARY");

entity.ToTable("venta");

entity.HasIndex(e => e.Idcliente, "IDCLIENTE");

entity.HasIndex(e => e.Idusuario, "IDUSUARIO");

entity.Property(e => e.Idventa)


.HasColumnType("int(11) unsigned zerofill")
.HasColumnName("IDVENTA");

entity.Property(e => e.Fecha)


.HasColumnType("datetime")
.HasColumnName("FECHA");
entity.Property(e => e.Idcliente)
.HasColumnType("int(11)")
.HasColumnName("IDCLIENTE");

entity.Property(e => e.Idusuario)


.HasColumnType("int(11)")
.HasColumnName("IDUSUARIO");

entity.Property(e => e.Total)


.HasPrecision(6, 2)
.HasColumnName("TOTAL");

entity.HasOne(d => d.IdclienteNavigation)


.WithMany(p => p.Venta)
.HasForeignKey(d => d.Idcliente)
.HasConstraintName("venta_ibfk_1");

entity.HasOne(d => d.IdusuarioNavigation)


.WithMany(p => p.Venta)
.HasForeignKey(d => d.Idusuario)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("venta_ibfk_3");
});

OnModelCreatingPartial(modelBuilder);
}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);


}
}

CONEXIÓN
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"default": "server=localhost;port=3306;user=root;database=storeplacedb"
},
"AppSettings": {
"Language": "es"
}
}

CLASE ENCRIPTACION DE CONTRASEÑAS


using System.Security.Cryptography;
using System.Text;

namespace StorePlace
{
public class Encrypt
{
public static string Encriptar(string str)
{
if(str != null)
{
SHA256 sha256 = SHA256Managed.Create();
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] stream = null;
StringBuilder sb = new StringBuilder();
stream = sha256.ComputeHash(encoding.GetBytes(str));
for (int i = 0; i < stream.Length; i++)
sb.AppendFormat("{0:x2}", stream[i]);
return sb.ToString();
}
return "";
}

/// Esta función desencripta la cadena que le envíamos en el


parámentro de entrada.
public static string DesEncriptar(string _cadenaAdesencriptar)
{
string result = string.Empty;
byte[] decryted =
Convert.FromBase64String(_cadenaAdesencriptar);
//result = System.Text.Encoding.Unicode.GetString(decryted, 0,
decryted.ToArray().Length);
result = System.Text.Encoding.Unicode.GetString(decryted);
return result;
}
}
}

You might also like