-1

Can you tell me why it does not work? I get an error. I tried using your method but it does not seem like it is working.

public void OnSignOut(int pin)
    {
        if (this.pin == pin && this.SignIn == true)
        {

            stopwatch.Stop();
            double elasped = stopwatch.Elapsed.TotalSeconds;
            stopwatch.Reset();
            this.total += elasped;
            MessageBox.Show("You have worked for " + elasped + " seconds." + " You have worked for " + this.total + " seconds in total.");
            this.SignIn = false;
            this.end = Convert.ToString(DateTime.Now);
            this.log.Add(this.name + " worked for " + elasped + " seconds." + "\r\n" + "Total Time: " + this.total + " seconds" + "\r\n" + "Log in: " + this.start + "   Log out: " + this.end + "\r\n\r\n\r\n");
            this.logbook.Add(DateTime.Now, elasped);
            json = JsonConvert.SerializeObject(this.logbook);
            System.IO.File.WriteAllText(@"D:\path.json", json);

        }

    }
    public double AddUp_Hours(DateTime start_date, DateTime end_date)
    {
    System.IO.File.ReadAllText(@"D:\path.json");
    this.logbook = JsonConvert.DeserializeObject<Dictionary< DateTime, double> > (json);
        DateTime first = start_date;
        DateTime second = end_date;
        double sums = this.logbook.Where(x => x.Key > first && x.Key < second)
              .Sum(x => x.Value);
        return sums;
Daniel
  • 103
  • 1
  • 1
  • 6

1 Answers1

1

You have a number of options, depending on your needs regarding scalability, features, security, etc:

  • use the app-settings as key-value storage: if you only very little data, no strings attached
  • serialize your data to XML/JSON/Binary: if you have some more data, and value data portability
  • use a light-weight file-based database storage like SQLite: if you have quite some data, need to do some basic reporting, etc.
  • use a full-fledged database if you have a massive amount of data, intend to do reporting, load balancing, replication, and much more.

Assuming you look for a small-scale, low-bar data-storage solution: Try Serialization to JSON for a start

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace Dict2JsonSO
{
    class Program
    {
        static void Main(string[] args)
        {

            Dictionary<DateTime, int> dict = new Dictionary<DateTime, int>();
            dict.Add(DateTime.Now, 100);
            dict.Add(DateTime.Now.AddSeconds(10), 10);

            //save
            string json = JsonConvert.SerializeObject(dict);
            System.IO.File.WriteAllText(@"D:\path.txt", json);

            //load
            string loadedJson = System.IO.File.ReadAllText(@"D:\path.txt");
            Dictionary<DateTime, int> loaded = JsonConvert.DeserializeObject<Dictionary<DateTime, int>>(loadedJson);
        }
    }
}

PS: This requires Newtonsoft.Json. Install it via NuGet.

wp78de
  • 18,207
  • 7
  • 43
  • 71