2009-11-03 18 views
20

Ho bisogno che la mia domanda scada 30 giorni da oggi, memorizzerò la data corrente nella configurazione dell'applicazione. Come posso controllare se l'applicazione è scaduta? Non mi importa se l'utente ha cambiato l'orologio e l'app funziona (un utente troppo stupido per farlo).C# 30 giorni dalla data odierna

if (appmode == "Trial") {    

      ???? 

      } 

risposta

42
string dateInString = "01.10.2009"; 

DateTime startDate = DateTime.Parse(dateInString); 
DateTime expiryDate = startDate.AddDays(30); 
if (DateTime.Now > expiryDate) { 
    //... trial expired 
} 
+0

'DateTime expiryDate = new DateTime (startDate);' non è richiesto – Scoregraphic

+5

'DateTime expiryDate = startDate.AddDays (30);' sarebbe corretto, causa 'expiryDate.AddDays (30)' scriverà il risultato in nirvana. – Oliver

+0

Oliver, grazie per la patch :) –

4
DateTime _expiryDate = DateTime.Now + TimeSpan.FromDays(30); 
13

Una posso rispondere con fiducia!

DateTime expiryDate = DateTime.Now.AddDays(30); 

O forse - se si desidera solo la data senza un'ora allegato che potrebbe essere più appropriato:

DateTime expiryDate = DateTime.Today.AddDays(30); 
18

DateTime.AddDays fa che:

DateTime expires = yourDate.AddDays(30); 
+2

Ricordarsi di assegnare il risultato. Sto sempre facendo yourdate.AddDays (30) e poi mi chiedo perché yourDate non è cambiato. –

+1

yourDate non sta cambiando però, la sua data di scadenza che è così in questo caso è ok. – James

+0

@ Cameron: è qui che la parte di 'DateTime expires' entra nell'immagine –

1

Una soluzione migliore potrebbe essere quello di introdurre un file di licenza con un contatore. Scrivi nel file di licenza la data di installazione dell'applicazione (durante l'installazione). Poi ogni volta che l'applicazione viene eseguita è possibile modificare il file di licenza e incrementare il conteggio di 1. Ogni volta che l'applicazione si avvia basta fare un rapido controllo per vedere se è stato raggiunto il 30 usi dell'applicazione cioè

if (LicenseFile.Counter == 30) 
    // go into expired mode 

anche questo risolverà il problema se l'utente ha messo l'orologio di sistema indietro come si può fare un semplice controllo per dire

if (LicenseFile.InstallationDate < SystemDate) 
    // go into expired mode (as punishment for trying to trick the app!) 

il problema con la configurazione attuale è che l'utente dovrà utilizzare l'applicazione ogni giorno per 30 giorni per ottenere la prova completa di 30 giorni.

+0

30 giorni dalla data di installazione o dalla data del primo utilizzo non è affatto raro o irragionevole. – Murph

+1

Sì, ma come ho detto, dovresti utilizzare l'applicazione ogni giorno per 30 giorni sul trotto per ottenere la tua prova completa di 30 giorni. La maggior parte delle applicazioni al giorno d'oggi farebbe in modo di ottenere i tuoi 30 giorni completi indipendentemente dal primo utilizzo/installazione dell'applicazione. – James

2

Una possibile soluzione sarebbe al primo avvio, creare un file contenente la data corrente e inserirlo in IsolatedStorage. Per le esecuzioni successive, controllare il contenuto del file e confrontarlo con la data corrente; se la differenza di data è superiore a 30 giorni, informare l'utente e chiudere l'applicazione.

+1

+1 archiviazione isolata in azione ... il registro potrebbe anche essere un altro candidato, sebbene richieda più sicurezza rispetto all'archiviazione isolata. – Ian

0

@Ed courtenay, @James, Ho una domanda stupida. Come mantenere l'utente lontano da questo file? (File contenente la data di scadenza). Se l'utente ha i diritti di installazione, ovviamente anche l'utente ha accesso alla visualizzazione dei file. La modifica dell'estensione del file non aiuta. Quindi, come mantenere questo file al sicuro e lontano dalle mani degli utenti?

+0

Soluzioni: codifica dati e/o aggiungi hash file. Se il file è danneggiato, considera il processo come scaduto –

+0

Grazie per aver risposto a Victor.Encrypting renderà il file illeggibile. – Shekhar

+0

DPAPI potrebbe essere utile? Soprattutto con un'applicazione salt unica e possibilmente utilizzando il contesto macchina invece del contesto utente (wrapper in C# a System.Security.Cryptography.DataProtection) –

0

Per eseguire questa operazione è necessario memorizzare la prima ora di esecuzione del programma. Come probabilmente farei è usare le impostazioni dell'applicazione incorporate in Visual Studio. Creane uno chiamato InstallDate che è un User Setting e imposta come valore predefinito DateTime.MinValue o qualcosa del genere (ad es. 1/1/1900).

Poi, quando il programma viene eseguito il controllo è semplice:

if (appmode == "trial") 
{ 
    // If the FirstRunDate is MinValue, it's the first run, so set this value up 
    if (Properties.Settings.Default.FirstRunDate == DateTime.MinValue) 
    { 
    Properties.Settings.Default.FirstRunDate = DateTime.Now; 
    Properties.Settings.Default.Save(); 
    } 

    // Now check whether 30 days have passed since the first run date 
    if (Properties.Settings.Default.FirstRunDate.AddMonths(1) < DateTime.Now) 
    { 
    // Do whatever you want to do on expiry (exception message/shut down/etc.) 
    } 
} 

impostazioni utente vengono memorizzati in una posizione piuttosto strano (qualcosa di simile a C: \ Documents and Settings \ YourName \ Impostazioni locali \ Dati applicazioni), in modo sarà abbastanza difficile per me, in media, trovarlo comunque. Se vuoi essere paranoico, basta crittografare la data prima di salvarla nelle impostazioni.

MODIFICA: Sospiro, ho letto male la domanda, non così complessa come pensavo>.>

13

DateTime.Now.Add (-30)

Vi dà la data di 30 giorni indietro da ora

+0

Ottimo punto! Felice di vederlo qui. –

1
string[] servers = new string[] { 
     "nist1-ny.ustiming.org", 
     "nist1-nj.ustiming.org", 
     "nist1-pa.ustiming.org", 
     "time-a.nist.gov", 
     "time-b.nist.gov", 
     "nist1.aol-va.symmetricom.com", 
     "nist1.columbiacountyga.gov", 
     "nist1-chi.ustiming.org", 
     "nist.expertsmi.com", 
     "nist.netservicesgroup.com" 
     }; 
string dateStart, dateEnd; 

void SetDateToday() 
    { 
     Random rnd = new Random(); 
     DateTime result = new DateTime(); 
     int found = 0; 
     foreach (string server in servers.OrderBy(s => rnd.NextDouble()).Take(5)) 
     { 
      Console.Write("."); 
      try 
      { 
       string serverResponse = string.Empty; 
       using (var reader = new StreamReader(new System.Net.Sockets.TcpClient(server, 13).GetStream())) 
       { 
        serverResponse = reader.ReadToEnd(); 
        Console.WriteLine(serverResponse); 
       } 

       if (!string.IsNullOrEmpty(serverResponse)) 
       { 
        string[] tokens = serverResponse.Split(' '); 
        string[] date = tokens[1].Split(' '); 
        string time = tokens[2]; 
        string properTime; 

        dateStart = date[2] + "/" + date[0] + "/" + date[1]; 

        int month = Convert.ToInt16(date[0]), day = Convert.ToInt16(date[2]), year = Convert.ToInt16(date[1]); 
        day = day + 30; 
        if ((month % 2) == 0) 
        { 
         //MAX DAYS IS 30 
         if (day > 30) 
         { 
          day = day - 30; 
          month++; 
          if (month > 12) 
          { 
           month = 1; 
           year++; 
          } 
         } 
        } 
        else 
        { 
         //MAX DAYS IS 31 
         if (day > 31) 
         { 
          day = day - 31; 
          month++; 
          if (month > 12) 
          { 
           month = 1; 
           year++; 
          } 
         } 
        } 
        string sday, smonth; 
        if (day < 10) 
        { 
         sday = "0" + day; 
        } 
        if (month < 10) 
        { 
         smonth = "0" + month; 
        } 
        dateEnd = sday + "/" + smonth + "/" + year.ToString(); 

       } 

      } 
      catch 
      { 
       // Ignore exception and try the next server 
      } 
     } 
     if (found == 0) 
     { 
      MessageBox.Show(this, "Internet Connection is required to complete Registration. Please check your internet connection and try again.", "Not connected", MessageBoxButtons.OK, MessageBoxIcon.Information); 
      Success = false; 
     } 
    } 

ho visto che il codice in qualche parte qualche sito web. Fare l'esempio sopra espone un problema tecnico: la modifica dell'ora e della data attuali alla data di inizio prolungherebbe la scadenza dell'applicazione.

La soluzione? Fare riferimento a un server orario online.

-2
if (cmb_mode_of_service.SelectedItem != null && cmb_term_of_service.SelectedItem != null) 
      { 
       if (cmb_mode_of_service.SelectedIndex > 0 && cmb_term_of_service.SelectedIndex > 0) 
       { 
        if (cmb_mode_of_service.SelectedItem.ToString() == "Single Service/Installation" || cmb_term_of_service.SelectedItem.ToString() == "Single Time") 
        { 
         int c2 = 1; 
         char c1 = 'A'; 
         DataRow dr = dt.NewRow(); 
         dr["SN"] = c2++; 
         dr["serviceid"] = txt_service_id.Text + "-" + c1++; 
         dr["servicedate"] = service_start_date.Text; 
         dr["servicestatus"] = "Pending"; 
         dr["serviceexcutive"] = "Not Alowed"; 
         dt.Rows.Add(dr); 
         dataGridView1.DataSource = dt; 

         txtexpirydate.Text = (Convert.ToDateTime(service_start_date.Text).AddDays(1)).ToString(); 

        } 
        else 
        { 



         if (cmb_mode_of_service.SelectedItem.ToString() == "Weekly Service") 
         { 
          int year = 0; 
          if (cmb_term_of_service.SelectedItem.ToString() == "One Year") 
          { 
           year = 1; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "Two Year") 
          { 
           year = 2; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "three year") 
          { 
           year = 3; 
          } 

          DateTime currentdate = Convert.ToDateTime(service_start_date.Text); 
          DateTime Enddate = currentdate.AddYears(+year); 
          txtexpirydate.Text = Enddate.ToString(); 

          char c1 = 'A'; 
          int c2 = 1; 
          for (var dt1 = currentdate.AddDays(7); dt1 <= Enddate; dt1 = dt1.AddDays(7)) 
          { 
           DataRow dr = dt.NewRow(); 
           dr["SN"] = c2++; 
           dr["serviceid"] = txt_service_id.Text + "-" + c1++; 
           dr["servicedate"] = dt1.ToString(); 
           dr["servicestatus"] = "Pending"; 
           dr["serviceexcutive"] = "Not Alowed"; 
           //txtexpirydate.Text = dt1.ToString(); 
           dt.Rows.Add(dr); 

          } 
          dataGridView1.DataSource = dt; 

         } 

         if (cmb_mode_of_service.SelectedItem.ToString() == "Fortnight Service") 
         { 
          int year = 0; 
          if (cmb_term_of_service.SelectedItem.ToString() == "One Year") 
          { 
           year = 1; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "Two Year") 
          { 
           year = 2; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "three year") 
          { 
           year = 3; 
          } 

          DateTime currentdate = Convert.ToDateTime(service_start_date.Text); 
          DateTime Enddate = currentdate.AddYears(+year); 
          txtexpirydate.Text = Enddate.ToString(); 

          char c1 = 'A'; 
          int c2 = 1; 
          for (var dt1 = currentdate.AddDays(15); dt1 <= Enddate; dt1 = dt1.AddDays(15)) 
          { 
           DataRow dr = dt.NewRow(); 
           dr["SN"] = c2++; 
           dr["serviceid"] = txt_service_id.Text + "-" + c1++; 
           dr["servicedate"] = dt1.ToString(); 
           dr["servicestatus"] = "Pending"; 
           dr["serviceexcutive"] = "Not Alowed"; 
           // txtexpirydate.Text = dt1.ToString(); 
           dt.Rows.Add(dr); 

          } 
          dataGridView1.DataSource = dt; 

         } 

         if (cmb_mode_of_service.SelectedItem.ToString() == "Monthly Service") 
         { 
          int year = 0; 
          if (cmb_term_of_service.SelectedItem.ToString() == "One Year") 
          { 
           year = 1; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "Two Year") 
          { 
           year = 2; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "three year") 
          { 
           year = 3; 
          } 

          DateTime currentdate = Convert.ToDateTime(service_start_date.Text); 
          DateTime Enddate = currentdate.AddYears(+year); 
          txtexpirydate.Text = Enddate.ToString(); 

          char c1 = 'A'; 
          int c2 = 1; 
          for (var dt1 = currentdate.AddDays(30); dt1 <= Enddate; dt1 = dt1.AddDays(30)) 
          { 
           DataRow dr = dt.NewRow(); 
           dr["SN"] = c2++; 
           dr["serviceid"] = txt_service_id.Text + "-" + c1++; 
           dr["servicedate"] = dt1.ToString(); 
           dr["servicestatus"] = "Pending"; 
           dr["serviceexcutive"] = "Not Alowed"; 
           // txtexpirydate.Text = dt1.ToString(); 
           dt.Rows.Add(dr); 

          } 
          dataGridView1.DataSource = dt; 

         } 


         if (cmb_mode_of_service.SelectedItem.ToString() == "Trimister Service") 
         { 
          int year = 0; 
          if (cmb_term_of_service.SelectedItem.ToString() == "One Year") 
          { 
           year = 1; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "Two Year") 
          { 
           year = 2; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "three year") 
          { 
           year = 3; 
          } 

          DateTime currentdate = Convert.ToDateTime(service_start_date.Text); 
          DateTime Enddate = currentdate.AddYears(+year); 
          txtexpirydate.Text = Enddate.ToString(); 

          char c1 = 'A'; 
          int c2 = 1; 
          for (var dt1 = currentdate.AddDays(90); dt1 <= Enddate; dt1 = dt1.AddDays(90)) 
          { 
           DataRow dr = dt.NewRow(); 
           dr["SN"] = c2++; 
           dr["serviceid"] = txt_service_id.Text + "-" + c1++; 
           dr["servicedate"] = dt1.ToString(); 
           dr["servicestatus"] = "Pending"; 
           dr["serviceexcutive"] = "Not Alowed"; 
           // txtexpirydate.Text = dt1.ToString(); 
           dt.Rows.Add(dr); 

          } 
          dataGridView1.DataSource = dt; 

         } 

         if (cmb_mode_of_service.SelectedItem.ToString() == "Half Yearly Service") 
         { 
          int year = 0; 
          if (cmb_term_of_service.SelectedItem.ToString() == "One Year") 
          { 
           year = 1; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "Two Year") 
          { 
           year = 2; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "three year") 
          { 
           year = 3; 
          } 

          DateTime currentdate = Convert.ToDateTime(service_start_date.Text); 
          DateTime Enddate = currentdate.AddYears(+year); 
          txtexpirydate.Text = Enddate.ToString(); 

          char c1 = 'A'; 
          int c2 = 1; 
          for (var dt1 = currentdate.AddDays(180); dt1 <= Enddate; dt1 = dt1.AddDays(180)) 
          { 
           DataRow dr = dt.NewRow(); 
           dr["SN"] = c2++; 
           dr["serviceid"] = txt_service_id.Text + "-" + c1++; 
           dr["servicedate"] = dt1.ToString(); 
           dr["servicestatus"] = "Pending"; 
           dr["serviceexcutive"] = "Not Alowed"; 
           // txtexpirydate.Text = dt1.ToString(); 
           dt.Rows.Add(dr); 

          } 
          dataGridView1.DataSource = dt; 

         } 

         if (cmb_mode_of_service.SelectedItem.ToString() == "Yearly Service") 
         { 
          int year = 0; 
          if (cmb_term_of_service.SelectedItem.ToString() == "One Year") 
          { 
           year = 1; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "Two Year") 
          { 
           year = 2; 
          } 

          if (cmb_term_of_service.SelectedItem.ToString() == "three year") 
          { 
           year = 3; 
          } 

          DateTime currentdate = Convert.ToDateTime(service_start_date.Text); 
          DateTime Enddate = currentdate.AddYears(+year); 
          txtexpirydate.Text = Enddate.ToString(); 

          char c1 = 'A'; 
          int c2 = 1; 
          for (var dt1 = currentdate.AddDays(365); dt1 <= Enddate; dt1 = dt1.AddDays(365)) 
          { 
           DataRow dr = dt.NewRow(); 
           dr["SN"] = c2++; 
           dr["serviceid"] = txt_service_id.Text + "-" + c1++; 
           dr["servicedate"] = dt1.ToString(); 
           dr["servicestatus"] = "Pending"; 
           dr["serviceexcutive"] = "Not Alowed"; 
           //txtexpirydate.Text = dt1.ToString(); 
           dt.Rows.Add(dr); 

          } 
          dataGridView1.DataSource = dt; 

         } 

        } 
       } 
+1

Se davvero pensi che il tuo blocco di codice aggiunga qualcosa di significativo a ciò che non è ancora menzionato in altre 10 risposte, ti preghiamo di fornire spiegazioni. Tuttavia, le spiegazioni dovrebbero sempre seguire il codice qui in StackOverflow! – ZygD

Problemi correlati