Stuck with writting to Registry Key..getting error messages.

I have a window service. I know the getting the hard drive information works since I tested it prior to putting in the registry key information.

Now the service installs starts then stops right away. Here are the three errors that are going into the eventlog

Event Type:      Error
Event Source:      Service1
Event Category:      None
Event ID:      0
Date:            4/6/2005
Time:            12:22:52 PM
User:            N/A
Computer:      
Description:
Service cannot be started. System.Exception: Failed to get Drive Space Information ---> System.Exception: Failed to get registry information ---> System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
   at System.Management.ManagementDateTimeConverter.ToDateTime(String dmtfDate)
   at WindowsService1.LastBootUpTask.GetLastBootupInfo() in c:\windowsservice1\lastbootuptask.cs:line 124
   --- End of inner exception stack trace ---
   at WindowsService1.LastBootUpTask.GetLastBootupInfo() in c:\windowsservice1\lastbootuptask.cs:line 159
   --- End of inner exception stack trace ---
   at WindowsService1.LastBootUpTask.GetLastBootupInfo() in c:\windowsservice1\lastbootuptask.cs:line 177
   at WindowsService1.Service1.OnStart(String[] args) in c:\windowsservice1\service1.cs:line 74
   at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

Event Type:      Information
Event Source:      WindowsService1.LastBootUpTask
Event Category:      None
Event ID:      0
Date:            4/6/2005
Time:            12:32:01 PM
User:            N/A
Computer:
Description:
System.Exception: Failed to get registry information ---> System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
   at System.Management.ManagementDateTimeConverter.ToDateTime(String dmtfDate)
   at WindowsService1.LastBootUpTask.GetLastBootupInfo() in c:\windowsservice1\lastbootuptask.cs:line 124
   --- End of inner exception stack trace ---
   at WindowsService1.LastBootUpTask.GetLastBootupInfo() in c:\windowsservice1\lastbootuptask.cs:line 160

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

Event Type:      Error
Event Source:      Service1
Event Category:      None
Event ID:      0
Date:            4/6/2005
Time:            12:32:01 PM
User:            N/A
Computer:      
Description:
Service cannot be started. System.Exception: Failed to get Drive Space Information ---> System.Exception: Failed to get registry information ---> System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
   at System.Management.ManagementDateTimeConverter.ToDateTime(String dmtfDate)
   at WindowsService1.LastBootUpTask.GetLastBootupInfo() in c:\windowsservice1\lastbootuptask.cs:line 124
   --- End of inner exception stack trace ---
   at WindowsService1.LastBootUpTask.GetLastBootupInfo() in c:\windowsservice1\lastbootuptask.cs:line 160
   --- End of inner exception stack trace ---
   at WindowsService1.LastBootUpTask.GetLastBootupInfo() in c:\windowsservice1\lastbootuptask.cs:line 177
   at WindowsService1.Service1.OnStart(String[] args) in c:\windowsservice1\service1.cs:line 74
   at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.


lastbootuptask.cs

using System;
using System.Management;
using System.Management.Instrumentation;
using System.Windows.Forms;
using System.Globalization;
using Microsoft.Win32;

namespace WindowsService1
{
      /// <summary>
      /// Summary description for LastBootUpTask.
      /// </summary>
      
     public class LastBootUpTask
    {
      public const string REG_QTI = "SOFTWARE\\QTI";
      public const string REG_HARDDRIVE_DATE   = "Harddrive date";

      public void GetLastBootupInfo()
      {
           System.DateTime today = System.DateTime.Today;
         try
         {      
               string DriveNamespace = @"\\.\root\cimv2";
               string sDate = null;
                              
               string DriveFindings = "select * from Win32_LogicalDisk where DriveType=3";
      
                         ManagementObjectSearcher DriveSearcher = new
            ManagementObjectSearcher( DriveNamespace, DriveFindings );
                              
              ManagementObjectCollection collection = DriveSearcher.Get();
      
              foreach (ManagementObject item in collection)
              {
                 double total=Math.Round(double.Parse(item["size"].ToString())/1024/1024/1024,1);
                 double free=Math.Round(double.Parse(item["freespace"].ToString())/1024/1024/1024,1);
                 double used=total-free;                                                            double percentfull=Math.Round(used/total,2);
                 double NoDecimalFullPercent = percentfull * 100;
             try
             {
*************************ERROR IS IN HERE
                if (NoDecimalFullPercent >= 20 && NoDecimalFullPercent <= 25)//set .85 and .80 as a constant
                {
            RegistryKey localMachine = Registry.LocalMachine;
            RegistryKey HardDriveDateInfo = localMachine.OpenSubKey(REG_QTI);

            sDate = HardDriveDateInfo.GetValue(REG_HARDDRIVE_DATE).ToString();


            if( sDate != null )
            {
                 DateTime NewHDDate = ManagementDateTimeConverter.ToDateTime(sDate).Date;
                 DateTime AddSevenDays = NewHDDate.AddDays(7);

                 if (today > AddSevenDays)//if newHDdate is
                 {
                   HardDriveDateInfo.SetValue(REG_HARDDRIVE_DATE, today.ToString("ddMMMyyyy"));                  //Send a warning message weekly
                   MessageBox.Show(NoDecimalFullPercent.ToString() + "%","today >addseven days",  
                                         MessageBoxButtons.OK,MessageBoxIcon.Error, MessageBoxDefaultButton.Button1,       
                                          MessageBoxOptions.ServiceNotification);
                  }
                                                
            }
            else
            {
                                    HardDriveDateInfo.SetValue(REG_HARDDRIVE_DATE, today.ToString("ddMMMyyyy"));
                                    //Send a warning message weekly                                               MessageBox.Show(NoDecimalFullPercent.ToString() + "%","Reg key was null",
                                       MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1,       
                                         MessageBoxOptions.ServiceNotification);
            }

            HardDriveDateInfo.Close();
            localMachine.Close();

            //Send a warning message weekly
            MessageBox.Show(NoDecimalFullPercent.ToString() + "%","Made it to if %full warning",
                                  MessageBoxButtons.OK,MessageBoxIcon.Error, MessageBoxDefaultButton.Button1,
                                    MessageBoxOptions.ServiceNotification);
            }
                  }
                 catch (Exception e)
                 {
            System.Diagnostics.EventLog.WriteEntry(this.ToString(),e.ToString());
            throw new Exception("Failed to get registry information", e);
                }
*******************************************ERROR AREA STOP
      if (percentfull >= 0.90 && percentfull <= 0.95)//set .85 and .80 as a constant
      {
          //Send a error message daily
        MessageBox.Show(percentfull.ToString(),"Made it to if %full error", MessageBoxButtons.OK,
           MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
      }

            }
           DriveSearcher.Dispose();
         }
         catch (Exception e)
        {
          System.Diagnostics.EventLog.WriteEntry(this.ToString(),e.ToString());
          throw new Exception("Failed to get Drive Space Information", e);
        }
     }
  }
}





LVL 2
NewMom2BrandonAsked:
Who is Participating?
 
RomanPetrenkoConnect With a Mentor Commented:
sdate is not null in your case but not contains correct value.
try this :
sDate = HardDriveDateInfo.GetValue(REG_HARDDRIVE_DATE).ToString();
if( sDate.Trim() != string.Empty)
{
   DateTime NewHDDate = ManagementDateTimeConverter.ToDateTime(sDate).Date;
...
...
...
}
       
0
 
RomanPetrenkoCommented:
In this line:
DateTime NewHDDate = ManagementDateTimeConverter.ToDateTime(sDate).Date;

What is the value of sDate? Is this value string representing the datetime in DMTF format?
Does the same code works in simple windows application?

if you answered yes for last two questions that means you have a problem with security and access rights for your service.
look here:
Using Libraries from Partially Trusted Code - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconUsingLibrariesFromPartiallyTrustedCode.asp

and also try to set another user(For example: Administrator) in Log on tab of the service's properties.


0
 
NewMom2BrandonAuthor Commented:
sdate is this. Right now I have the registry key there but there is nothing in it. The key has a datatype of string.

I do have full admin rights on the PC. I normally write to the registry often but have done it in Borland C++

public const string REG_HARDDRIVE_DATE   = "Harddrive date";
sDate = HardDriveDateInfo.GetValue(REG_HARDDRIVE_DATE).ToString();

What I am trying to do is this:
(post the message only once a week)
If the registry key has data
then
take the data string information change it to datetime format
add seven days to the data  (make it new variable)
if todays date is greater than the new variable then send a message

if the registry key has nothing in it then post the message and fill in the registry key with todays date
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
NewMom2BrandonAuthor Commented:
oh ya I have

string sDate = null;
0
 
NewMom2BrandonAuthor Commented:
Thank you!!

I also needed to do the following in order for it to work

RegistryKey HardDriveDateInfo = localMachine.OpenSubKey(REG_QTI);
chaged to this
RegistryKey HardDriveDateInfo = localMachine.OpenSubKey(REG_QTI,true);
the true enables me to write to the key
0
 
NewMom2BrandonAuthor Commented:
However when I search after the key has been filled in I get an error on the line

DateTime NewHDDate = ManagementDateTimeConverter.ToDateTime(sDate).Date;

the registry key shows the following data "06Apr2005"

any suggestions or do I need to post another question
0
 
RomanPetrenkoCommented:
"ddMMMyyyy" is not correct format for ManagementDateTimeConverter.ToDateTime function
Look here:
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemmanagementmanagementdatetimeconverterclasstodatetimetopic.asp
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.