?
Solved

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

Posted on 2005-04-06
7
Medium Priority
?
542 Views
Last Modified: 2012-05-05
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);
        }
     }
  }
}





0
Comment
Question by:NewMom2Brandon
  • 4
  • 3
7 Comments
 
LVL 8

Expert Comment

by:RomanPetrenko
ID: 13719770
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
 
LVL 2

Author Comment

by:NewMom2Brandon
ID: 13719891
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
 
LVL 2

Author Comment

by:NewMom2Brandon
ID: 13719947
oh ya I have

string sDate = null;
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 8

Accepted Solution

by:
RomanPetrenko earned 2000 total points
ID: 13719971
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
 
LVL 2

Author Comment

by:NewMom2Brandon
ID: 13720098
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
 
LVL 2

Author Comment

by:NewMom2Brandon
ID: 13720474
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
 
LVL 8

Expert Comment

by:RomanPetrenko
ID: 13720550
"ddMMMyyyy" is not correct format for ManagementDateTimeConverter.ToDateTime function
Look here:
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemmanagementmanagementdatetimeconverterclasstodatetimetopic.asp
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses
Course of the Month15 days, 5 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question