2009-11-03 29 views
20

Necesito que mi aplicación caduque 30 días a partir de hoy, almacenaré la fecha actual en la configuración de la aplicación. ¿Cómo comprobaré si la aplicación ha expirado? No me importa si el usuario cambió el reloj y la aplicación funciona (un usuario demasiado estúpido para hacerlo).C# 30 días a partir de la fecha de hoy

if (appmode == "Trial") {    

      ???? 

      } 

Respuesta

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);' no es necesario – Scoregraphic

+5

'DateTime expiryDate = startDate.AddDays (30);' sería correcto, porque 'expiryDate.AddDays (30)' escribirá el resultado en nirvana. – Oliver

+0

Oliver, gracias por el parche :) –

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

Una puedo responder con seguridad!

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

O, posiblemente, - si lo que desea la fecha sin un tiempo adjunto, que podría ser más apropiado:

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

DateTime.AddDays hace eso:

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

Recuerde recordar para asignar el resultado. Siempre estoy haciendo tu fecha.AddDays (30) y luego me pregunto por qué tu fecha no ha cambiado. –

+1

yourDate no está cambiando, es la fecha de caducidad, por lo que en este caso está bien. – James

+0

@Cameron: ahí es donde entra la parte 'DateTime expires' –

1

Una solución mejor podría ser para presentar un archivo de licencia con un contador. Escriba en el archivo de licencia la fecha de instalación de la aplicación (durante la instalación). Entonces cada vez que se ejecuta la aplicación se puede editar el archivo de licencia y incrementar la cuenta en 1. Cada vez que se inicia la aplicación que acaba de hacer una comprobación rápida para ver si se han alcanzado los 30 usos de la aplicación es decir

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

también esto va a resolver el problema si el usuario ha puesto el reloj del sistema como se puede hacer una verificación simple decir

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

el problema con su configuración actual es el usuario tendrá que utilizar la aplicación de todos los días durante 30 días para obtener su prueba completa de 30 días.

+0

30 días desde la fecha de instalación o desde la fecha del primer uso no es nada infrecuente o poco razonable. – Murph

+1

Sí, pero como mencioné, tendría que usar la aplicación todos los días durante 30 días seguidos para obtener la prueba completa de 30 días. La mayoría de las aplicaciones hoy en día se aseguran de que obtenga sus 30 días completos independientemente de cuándo utilizó/instaló la aplicación por primera vez. – James

2

Una posible solución estaría en la primera ejecución, cree un archivo que contenga la fecha actual y colóquelo en IsolatedStorage. Para ejecuciones posteriores, verifique el contenido del archivo y compárelo con la fecha actual; si la diferencia de fecha es superior a 30 días, informe al usuario y cierre la aplicación.

+1

+1 almacenamiento aislado en acción ... el registro también podría ser otro candidato, aunque requiere más seguridad que el almacenamiento aislado. – Ian

0

@Ed courtenay, @James, Tengo una pregunta estúpida. ¿Cómo mantener al usuario alejado de este archivo? (Archivo que contiene la fecha de caducidad). Si el usuario tiene derechos de instalación, obviamente el usuario también tiene acceso para ver archivos. Cambiar la extensión del archivo no ayudará. Entonces, ¿cómo mantener este archivo seguro y alejado de las manos de los usuarios?

+0

Soluciones: cifrar datos y/o agregar hash de archivos. Si el archivo está dañado, considere la opción de prueba como caducada. –

+0

Gracias por responder a Victor.Encrypting seguramente hará que el archivo sea ilegible. – Shekhar

+0

DPAPI podría ser útil? Especialmente con una sal única de la aplicación y posiblemente utilizando el contexto de la máquina en lugar del contexto del usuario (envoltorios en C# en System.Security.Cryptography.DataProtection) –

0

Debe guardar el primer tiempo de ejecución del programa para poder hacerlo. Cómo probablemente lo haría usando la configuración de la aplicación integrada en Visual Studio. Realice uno llamado InstallDate, que es una configuración de usuario y está predeterminado en DateTime.MinValue o algo así (por ejemplo, 1/1/1900).

Luego, cuando el programa se ejecuta la comprobación es sencilla:

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.) 
    } 
} 

configuración de usuario se almacenan en un lugar bastante raro (algo así como C: \ Documents and Settings \ SuNombre \ Configuración local \ Datos de programa) por lo para el Joe promedio será bastante difícil encontrarlo de todos modos. Si quieres ser paranoico, solo encripta la fecha antes de guardarla en la configuración.

EDIT: Suspiro, leí la pregunta, no tan compleja como pensaba>.>

13

DateTime.Now.Add (-30)

que da la fecha 30 días posterior a partir de ahora

+0

¡Un gran punto! Feliz de ver esto aquí. –

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; 
     } 
    } 

vi ese código en alguna parte de algún sitio web. Hacer el ejemplo anterior expone una falla: Cambiar la hora y fecha actuales a la fecha de inicio prolongaría la caducidad de la aplicación.

La solución? Consulte un servidor de tiempo en línea.

-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

Si realmente cree que su bloque de código agrega algo significativo que aún no se menciona en otras 10 respuestas, proporcione explicaciones. Sin embargo, las explicaciones siempre deben seguir el código aquí en StackOverflow. – ZygD

Cuestiones relacionadas