How to execute query in C # for request control

1

I'm new to programming and need to add some functionality in a C # asp.net application. One is a control that prevents the user from proceeding with the request if it has any pending on the system. I'll describe it step by step.

My view

@using Integracao.ImpressoRequests.Model.Entities.ImpressoRequest
@model Request
@{
  ViewBag.Title = "Requisição";
  Layout = "~/Views/Shared/_Layout.cshtml";
}

    ...

    @foreach (RequestItem item in Model.Items)
    {
        <tr>
            <td>
                @Html.DisplayFor(x => item.Usuario.Nome)
            </td>
            <td>
                @Html.DisplayFor(x => item.Date)
            </td>
            <td>
                @Html.DisplayFor(x => item.Unidade.Nome)
            </td>
            <td>
                @Html.DisplayFor(x => item.ResultCenter.Nome)
            </td>
        </tr>
    }
</table>
<div class="formfooter">

    <input type="button" value="Gerar pedido" onclick="window.open('@Url.Action("ProcessRequest", new { requestId = Model.Id })','_blank');window.location.href='@Url.Action("Index", "Home")'" /></div>

Controller

    [HttpGet]
    public ActionResult ProcessRequest(int requestId)
    {
        Request request = _data.Requests.GetByID(requestId);
        if (request.Processed)
            return RedirectToAction("PrintRequest", new { requestId = request });
        foreach (RequestItem item in request.Items.OrderBy(x => x.Usuario_Id))
        {
            AssignImpressos assignIItems = new AssignImpressos(item.Id);
            assignIItems.Assign();
        }
        request.Processed = true;
        _data.Save();
        return RedirectToAction("PrintRequest", new { requestId = request.Id });
    }

Model

    public Request()
    {
        Date = DateTime.Now;
        UsedItems = new List<Impresso>();
        RequestsHistory = new List<RequestHistory>();
        Items = new List<RequestItem>();
    }

    public int Id { get; set; }

    public DateTime? Date { get; set; }

    public string Justification { get; set; }

    public string Usuario_Id { get; set; }

    public virtual Usuario Usuario { get; set; }
    public virtual ICollection<Impresso> UsedItems { get; set; }

    Model Impresso

        public class Impresso : IEntity
{
    public Impresso()
    {
        RequestsHistory = new List<RequestHistory>();
    }

    public int Id { get; set; }

    public int Code { get; set; }

    public string Purpose { get; set; }

    public DateTime? Data_Controle { get; set; }

    public decimal AdjustedValue { get; set; }

    public int Status { get; set; }
    public ItemStatus EnumeratedStatus
    {
        get { return (ItemStatus)Status; }
        set { Status = (int)value; }
    }        
    public string Note { get; set; }

    public string Usuario_Id { get; set; }
    public virtual Usuario Usuario { get; set; }

    public int? Request_Id { get; set; }
    public virtual Request Request { get; set; }

    public string Unidade_Id { get; set; }
    public virtual Unidade Unidade { get; set; }

    public string ResultCenter_Id { get; set; }
    public virtual ResultCenter ResultCenter { get; set; }

    public virtual ICollection<RequestHistory> RequestsHistory { get; set; }

    object IEntity.Id
    {
        get { return Id; }
        set { Id = (int)value; }
    }
}

What I need is the following: When the user clicks 'Generate Order' in the view, in my controller class I need to scan the Order table in the database, looking for if that user already authenticated by the system has in the printed table the 'Data_Controle' null or Status = 1. If positive, the system should prevent the continuation by triggering an alert with the information. If false, the program continues and generates the request normally. The question is, I know how to select one in the bank to get it but what the syntax in C # according to my code to make this control? I thought of query because I move with database and the logic is clearer for me, or if not for query, what would be the best way to achieve this in logic programming? Thanks

Edit

        private string GetUser()
    {
        string userId = string.Empty;
        try
        {
            string id = User.Identity.Name.Split('\')[1];
            Usuario _currentUsuario = _data.Usuario.GetByID(id);
            userId = _currentUsuario.Id;
            ViewBag.UserName = _currentUsuario.Name;
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("UserName", ex.Message);
        }
        return userId;
    }
    
asked by anonymous 11.09.2014 / 21:45

2 answers

2

You can create an ActionFilterAttribute for this:

public class VerificarPendencia : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        // Assumindo que você possui um ICollection<Impresso> Impressos para a entidade Usuario, e que esta coleção está populada ao obter o Usuario.
        if (_data.Usuarios.GetByID(GetUser()).Impressos.Any(x => x.Data_Controlle == null && x.Status == 1))
        {
           // Açoes...
        } 
    }
}

Search a little about the ActionFilterAttribute for the methods you can use. And then you just need to decorate Action with this attribute:

[VerificarPendencia]
[HttpGet]
public ActionResult ProcessRequest(int requestId)

All Actions decorated with this attribute (if you prefer, can decorate the entire Controller) now go through the methods created in it, such as OnResultExecuting, OnActionExecuted, etc ...

    
12.09.2014 / 17:58
1

The code is very close to what you need. I guess ProcessRequest is that code up, so I would do the following:

[HttpGet]
public ActionResult ProcessRequest(int requestId)
{
    // Estou supondo que aqui você carregue seu usuário dentro de um objeto 'Usuario'
    // var usuario = contexto.Usuarios.SingleOrDefault(u => u.Nome == User.Identity.UserName);
    var usuario = _data.Usuarios.GetByID(GetUser());

    if (contexto.Impresso.Any(i => i.Usuario_Id == usuario.Usuario_Id && (i.Data_Controle == null || i.Status == 1))) {
        ModelState.AddModelError("", "Coloque aqui a mensagem que explica porque o sistema não pode continuar");
        return View();
    }

    Request request = _data.Requests.GetByID(requestId);

    if (request.Processed)
        return RedirectToAction("PrintRequest", new { requestId = request });

    foreach (RequestItem item in request.Items.OrderBy(x => x.Usuario_Id))
    {
        AssignImpressos assignIItems = new AssignImpressos(item.Id);
        assignIItems.Assign();
    }

    request.Processed = true;
    _data.Save();
    return RedirectToAction("PrintRequest", new { requestId = request.Id });
}
    
12.09.2014 / 21:07