Save data to client for later use

Asked

Viewed 216 times

2

I have a web form application where the user enters with some values to perform an analysis. It is two values item and quantity, this data is in one List<> which is used as DataSource of a GridView. They can have up to 50 items, but usually does not exceed 5 items.

Use the following code to manipulate typed valuables:

public class Analise
{
    public int Item { get; set; }
    public int Quantidade { get; set; }
    public double CustoUnitario { get; set; }
    public double CustoAnual { get; set; }
}

static List<Analise> analiseLista = new List<Analise>();


protected void btnAdicionar_Click(object sender, EventArgs e)
{
    try
    {
        lblErro.Text = "";
        //Regex para validar somente números
        Regex soNumeros = new Regex(@"^[0-9]+$");
        if (!soNumeros.IsMatch(txtItem.Text) || !soNumeros.IsMatch(txtQuantidade.Text))
        {
            lblErro.Text = "Valore devem ser numéricos";
            return;
        }

        Int32 item = Convert.ToInt32(txtitem.Text);
        Int32 quantidade = Convert.ToInt32(txtQuantidade.Text);

        using (BDEntities db = new BDEntities())
        {
            //Verifica ser item existe em TB_item 
            var itemBD = (from c in db.TB_item
                                where c.item == item
                                select new
                                {
                                    c.CUSTO_item
                                }).ToList();
            if (itemBD.Count == 0)
            {
                //Se não existir mensagem de erro
                lblErro.Text = "item: " + item + " não cadastrada!";
            }
            else
            {
                //Se existir continua o processo
                custoUnitarioitem = (Double)itemBD.FirstOrDefault().CUSTO_item;
                custoAnual = (quantidade * custoUnitarioitem);

                //Verifica se item existe na lista analiseLista
                var existeAnalise = analiseLista.Where(c => c.item.Equals(item)).FirstOrDefault();
                if (existeAnalise == null)
                {
                    //Se não existir INCLUI
                    var novo = new Analise() { item = item, Quantidade = quantidade, CustoUnitarioitem = custoUnitarioitem, CustoAnual = custoAnual };
                    analiseLista.Add(novo);
                }
                else
                {
                    //Se existir ALTERA ou EXLCUI
                    if (quantidade == 0)
                    {
                        //Se quantidade zero exclui item da analiseLista
                        analiseLista.Remove(existeAnalise);
                    }
                    else
                    {
                        //Se quantidade maior que zero e capcacidade existe em analiseLista ALTERA 
                        existeAnalise.item = item;
                        existeAnalise.Quantidade = quantidade;
                        existeAnalise.CustoUnitarioitem = custoUnitarioitem;
                        existeAnalise.CustoAnual = custoAnual;
                    }
                }
                //Atualiza o grid com os valores
                gdvAnalise.DataSource = analiseLista.OrderBy(a => a.item).ToList();
                gdvAnalise.DataBind();
                double somatorio = analiseLista.Sum(x => Convert.ToDouble(x.CustoAnual));
                txtTotal.Text = somatorio.ToString();
            }
        }
        txtitem.Text = null;
        txtQuantidade.Text = null;
        txtitem.Focus();
    }
    catch (Exception ex)
    {
        throw ex;

    }
}

Stay like this:

inserir a descrição da imagem aqui

I need to save the contents of this List so that whenever the user enters the application they are available and are loaded in a GridView with the last analysis performed. I didn’t want a table in the comic book for this.

How you could do this using Cache or there is another option?

Or I’ll have to create a comic book table for this

  • You want to know three different unrelated things so it should be three questions. But try to elaborate more the question, give some context.

  • I’ll try to elaborate on the question.

  • I don’t know what you’re trying to do, but these three things are completely unrelated. You can’t choose between the three to solve what you want. Probably only cache is related to the problem. Of course, I may have misunderstood, but then you need to clarify more because you’re thinking of those three possibilities. What do you understand that they will help.

  • So I’m mixing things up. I’ll edit. But the idea is to save a list with some data and when the user logs in and loads one gridview with him.

  • 1

    I think the easiest is to use BinarySerialization to a file. On loading the program you read this file and de-serialize the data.

  • Is it now clearer?

  • @Vinícius Gobbo A. de Oliveira Ao usar BinarySerialization where the data is recorded?

  • The most common is to record it in any file. The biggest advantage of it is beyond write and read speed, is that it supports recording complex object trees. And it is very easy to use.

  • @Vinícius Gobbo A. de Oliveira I think I expressed myself badly. Is it in the client’s machine? I saw an example and it seemed simple. http://www.centerspace.net/examples/nmath/csharp/core/binary-serialization-example.php

  • Yes, as long as your application is not ASP.Net. If it is C#, using WPF or Winforms, for example, the file can be client-side yes. If your application is ASP.Net, you will not be able to record files to the client because there is no support for this.

  • Every time I see one catch (Exception ex) throw ex; I feel like crying.

Show 6 more comments

1 answer

2


Of course there are other options but it may be that using a table in the bank is really the best.

Think about this scenario: the user opens the page on the work computer, creates such analysis, after a while goes back to this page and the last analysis appears automatically because it was saved in the client (browser.) Then this user decides to use another browser or even another computer and nothing is remembered. Would that be intuitive for the user? That’s what you really want to implement?

If you find that the above scenario is no problem then you can search for local storage alternatives (on client) like window.localStorage, window.indexedDB or the File API. All these alternatives may not work in all types of browser.

Other alternatives involving server storage are equivalent to using a database and, worse, they may suffer from limitations such as not functioning properly when you have more than one web server (web Farms). I would suggest reconsidering and using the database instead of creating something more fragile.

  • Thank you very much for the suggestions I will research. The scenario described would not be a problem, are few users on an intranet each with their micro and browser is unique. There’s a comic book with the data and the table generates a bureaucracy, so I made this page that uses the comic data and breaks a branch. So they asked me if I could save it. If I give work I won’t do it. It’s a scam, but it helps the user a lot, so the precariousness is compensated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.