Advertisement
Guest User

C# to java

a guest
Jul 27th, 2014
1,779
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 29.21 KB | None | 0 0
  1. Hi,
  2. I have a piece of code in C#. It reads some services in windows and logs it into a file. Can we do the same thing in Java. Please Help! Its urgent.
  3. I am pasting the code.
  4.  
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net.Mail;
  11. using System.ServiceProcess;
  12. using System.Text;
  13. using Microsoft.Win32;
  14.  
  15. namespace MineStarAvailabilityMonitor
  16. {
  17.     public class Monitor
  18.     {
  19.  
  20.         private int year;
  21.         private int month;
  22.         private string filename;
  23.  
  24.         private int mineTrackingDownCount = 0;
  25.         private int iAssignmentServerDownCount = 0;
  26.         private int cycleGeneratorDownCount = 0;
  27.         private static int MAX_DOWN_COUNT = 4;
  28.         private Properties props, custProps;
  29.         private string fileRoot;
  30.         private string systemName;
  31.         private bool writeHeader;
  32.         private string overridesFilename;
  33.         private string mamFilename;
  34.         private DayOfWeek dayOfWeek;
  35.         private int day;
  36.  
  37.         public Monitor(string systemName, string file)
  38.         {
  39.             year = DateTime.Now.Year;
  40.             month = DateTime.Now.Month;
  41.             dayOfWeek = DateTime.Now.DayOfWeek;
  42.             day = DateTime.Now.Day;
  43.  
  44.             if (systemName == null)
  45.             {
  46.                 this.systemName = "main";
  47.             }
  48.             else
  49.                 this.systemName = systemName;
  50.  
  51.             LoadConfig(file);
  52.             filename = GetFilename(this.systemName);
  53.         }
  54.  
  55.         public void CheckJVM(object stateObject)
  56.         {
  57.             ServiceController svcCtrl;
  58.             ServiceControllerStatus srvStatus;
  59.  
  60.             // Always update month and year to make sure we get the monthly roll over of MAM log file
  61.             var newyear = DateTime.Now.Year;
  62.             var newmonth = DateTime.Now.Month;
  63.             var newDay = DateTime.Now.Day;
  64.             var newDayOfWeek = DateTime.Now.DayOfWeek;
  65.  
  66.             if (newmonth != month)
  67.             {
  68.                 // Log is about to change so send it before creating new one
  69.                 generateEmail("MAM - " + custProps.get("/MineStar.properties._CUSTCODE", "DEFAULT"), "Attached is the current MAM log", true);
  70.                 year = newyear;
  71.                 month = newmonth;
  72.                 day = newDay;
  73.                 dayOfWeek = newDayOfWeek;
  74.  
  75.                 GetFilename(systemName);
  76.             }
  77.  
  78.             // Start by checking to see if it's a new day or week
  79.  
  80.             if (day != newDay)
  81.             {
  82.                 // First update day
  83.                 day = newDay;
  84.                 // Send alive message
  85.                 generateEmail("MAM - " + custProps.get("/MineStar.properties._CUSTCODE", "DEFAULT"),
  86.                               "MAM is alive at " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString(),
  87.                               false);
  88.             }
  89.  
  90.  
  91.             if (newDayOfWeek != dayOfWeek && newDayOfWeek == DayOfWeek.Sunday)
  92.             {
  93.                 dayOfWeek = newDayOfWeek;
  94.                 // Send log
  95.                 generateEmail("MAM - " + custProps.get("/MineStar.properties._CUSTCODE", "DEFAULT"), "Attached is the current MAM log", true);
  96.             }
  97.  
  98.             if (!System.IO.File.Exists(mamFilename))
  99.                 writeHeader = true;
  100.             else
  101.                 writeHeader = false;
  102.  
  103.             StreamWriter sw = new StreamWriter(mamFilename, true);
  104.  
  105.             if (writeHeader)
  106.                 WriteFileHeader(sw);
  107.  
  108.             // This is where we will look for the state of the required services
  109.             // M*MineTracking, M*IAssignmentServer, M*CycleGenerator
  110.             StringBuilder sb = new StringBuilder();
  111.  
  112.             //ServiceController[] scServices;
  113.             //scServices = ServiceController.GetServices();
  114.             Process proc = Process.GetCurrentProcess();
  115.  
  116.             //writeSpeedo(sw, proc);
  117.  
  118.             proc.Dispose();
  119.  
  120.             if (!IsInstalled("M*MineTracking"))
  121.             {
  122.                 sw.WriteLine("Unable to locate the service M*MineTracking. Possible causes:");
  123.                 sw.WriteLine("MineStar is not installed");
  124.                 sw.WriteLine("MineStar is not configured to run as a service");
  125.                 sw.WriteLine("This is a non standard install");
  126.                 sw.Flush();
  127.                 sw.Close();
  128.                 return;
  129.             }
  130.  
  131.             svcCtrl = new ServiceController("M*MineTracking");
  132.  
  133.             srvStatus = svcCtrl.Status;
  134.             if (srvStatus != ServiceControllerStatus.Running)
  135.             {
  136.                 mineTrackingDownCount++;
  137.             }
  138.             else
  139.             {
  140.                 mineTrackingDownCount = 0;
  141.             }
  142.  
  143.             svcCtrl.Dispose();
  144.  
  145.             sb.Append(DateTime.Now.ToLongDateString());
  146.  
  147.             sb.Append(" ");
  148.  
  149.             sb.Append(DateTime.Now.ToLongTimeString());
  150.  
  151.             sb.Append("   M*MineTracking");
  152.             sb.Append("=");
  153.             sb.Append(srvStatus);
  154.             sb.Append(",");
  155.  
  156.             if (IsInstalled("M*IAssignmentServer"))
  157.             {
  158.                 svcCtrl = new ServiceController("M*IAssignmentServer");
  159.                 srvStatus = svcCtrl.Status;
  160.  
  161.                 if (srvStatus != ServiceControllerStatus.Running)
  162.                 {
  163.                     iAssignmentServerDownCount++;
  164.                 }
  165.                 else
  166.                 {
  167.                     iAssignmentServerDownCount = 0;
  168.                 }
  169.  
  170.                 sb.Append("M*IAssignmentServer");
  171.                 sb.Append("=");
  172.                 sb.Append(srvStatus);
  173.                 sb.Append(",");
  174.  
  175.                 svcCtrl.Dispose();
  176.             }
  177.  
  178.  
  179.             if (IsInstalled("M*CycleGenerator"))
  180.             {
  181.                 svcCtrl = new ServiceController("M*CycleGenerator");
  182.                 srvStatus = svcCtrl.Status;
  183.  
  184.                 if (srvStatus != ServiceControllerStatus.Running)
  185.                 {
  186.                     cycleGeneratorDownCount++;
  187.                 }
  188.                 else
  189.                 {
  190.                     cycleGeneratorDownCount = 0;
  191.                 }
  192.  
  193.                 sb.Append("M*CycleGenerator");
  194.                 sb.Append("=");
  195.                 sb.Append(srvStatus);
  196.                 sw.WriteLine(sb.ToString());
  197.  
  198.                 svcCtrl.Dispose();
  199.             }
  200.  
  201.  
  202.             sw.Flush();
  203.  
  204.             sw.Close();
  205.  
  206.             if (iAssignmentServerDownCount >= MAX_DOWN_COUNT || cycleGeneratorDownCount >= MAX_DOWN_COUNT || mineTrackingDownCount >= MAX_DOWN_COUNT)
  207.             {
  208.                 // Send email
  209.                 string body = "MAM has detected a potential failure on " +
  210.                                System.Windows.Forms.SystemInformation.ComputerName +
  211.                                "\n This is a system generated email\n Please contact the MineStar System Administrator";
  212.  
  213.                 generateEmail("MineStar Availability Monitor - ALERT", body, true);
  214.  
  215.                 mineTrackingDownCount = 0;
  216.                 iAssignmentServerDownCount = 0;
  217.                 cycleGeneratorDownCount = 0;
  218.  
  219.                 sw = new StreamWriter(mamFilename, true);
  220.                 sw.WriteLine(DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "   Alert email sent");
  221.                 sw.Flush();
  222.                 sw.Close();
  223.  
  224.             }
  225.  
  226.  
  227.         }
  228.  
  229.         private void writeSpeedo(StreamWriter sw, Process proc)
  230.         {
  231.             sw.Write(" ****************    ");
  232.             sw.Write("Peak Working Set = " + proc.PeakWorkingSet64);
  233.             sw.Write(" Working Set = " + proc.WorkingSet64);
  234.             sw.Write(" Handle Count = " + proc.HandleCount);
  235.             sw.Write(" Private Memory Size = " + proc.PrivateMemorySize64);
  236.             sw.WriteLine("    ****************");
  237.  
  238.         }
  239.  
  240.  
  241.  
  242.         private static bool IsInstalled(string serviceName)
  243.         {
  244.             using (ServiceController controller =
  245.                 new ServiceController(serviceName))
  246.             {
  247.                 try
  248.                 {
  249.                     ServiceControllerStatus status = controller.Status;
  250.                 }
  251.                 catch
  252.                 {
  253.                     controller.Dispose();
  254.                     return false;
  255.                 }
  256.                 controller.Dispose();
  257.                 return true;
  258.             }
  259.         }
  260.  
  261.         private void WriteFileHeader(StreamWriter sw)
  262.         {
  263.             string line1, line2, line3;
  264.  
  265.             line1 = custProps.get("/MineStar.properties._CUSTCODE", "DEFAULT");
  266.             line2 = custProps.get("/MineStar.properties._CUSTSITE", "DEFAULT");
  267.             line3 = custProps.get("/Versions.properties.CURRENT_BUILD", "UNKNOWN");
  268.  
  269.             sw.Write("*******  ");
  270.             sw.Write(line1);
  271.             sw.WriteLine("  ********");
  272.  
  273.             sw.Write("*******  ");
  274.             sw.Write(line2);
  275.             sw.WriteLine("  ********");
  276.  
  277.             sw.Write("*******  ");
  278.             sw.Write(line3);
  279.             sw.WriteLine("  ********");
  280.         }
  281.  
  282.         public string GetFilename(String system)
  283.         {
  284.             fileRoot = props.get("MSTAR_SYSTEMS");
  285.  
  286.             mamFilename = fileRoot + "\\" + system + "\\logs\\monitoring\\MAM" + year + month + ".txt";
  287.             overridesFilename = fileRoot + "\\" + system + "\\config\\MineStar.overrides";
  288.  
  289.             custProps = new Properties(overridesFilename);
  290.  
  291.             return fileRoot;
  292.         }
  293.  
  294.         public string GetOverridesFilename()
  295.         {
  296.             return overridesFilename;
  297.         }
  298.  
  299.         private void generateEmail(string subject, string body, bool attachLog)
  300.         {
  301.             // Check if email enabled
  302.             EventLog.WriteEntry("MAM", "Check if email enabled");
  303.             string strEmailEnabled = custProps.get("/MineStar.properties._EMAIL_ENABLED_EXT", "true");
  304.             bool emailEnabled = Convert.ToBoolean(strEmailEnabled);
  305.  
  306.             if (!emailEnabled)
  307.             {
  308.                 EventLog.WriteEntry("MAM", "Email is NOT enabled");
  309.                 StreamWriter sw = new StreamWriter(mamFilename, true);
  310.                 sw.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
  311.                 sw.WriteLine("Email not enabled so the following message could not be sent");
  312.                 sw.WriteLine(subject);
  313.                 sw.WriteLine(body);
  314.                 sw.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
  315.                 sw.Flush();
  316.                 sw.Close();
  317.                 return;
  318.             }
  319.  
  320.             EventLog.WriteEntry("MAM", "Email enabled");
  321.  
  322.             // Get properties from MineStar.Overrides
  323.             var smtpServ = custProps.get("/MineStar.properties._EMAILSERVER", "smtp.gmail.com");
  324.             var smtpPort = custProps.get("/MineStar.properties._EMAILPORT", "587");
  325.  
  326.             EventLog.WriteEntry("MAM", "Email enabled - authenticated SMTP");
  327.             // Lets do authenticated SMTP
  328.             MailMessage mail = new MailMessage();
  329.             SmtpClient smtpServer = new SmtpClient(smtpServ, Convert.ToInt16(smtpPort));
  330.  
  331.             EventLog.WriteEntry("MAM", "Email enabled - get credentials");
  332.  
  333.             var emailUser = custProps.get("/MineStar.properties._EMAILUSER", "empty");
  334.             var emailPass = custProps.get("/MineStar.properties._EMAILPASSWORD", "empty");
  335.  
  336.             EventLog.WriteEntry("MAM", "Email enabled - set credentials");
  337.             try
  338.             {
  339.                 smtpServer.Credentials = new System.Net.NetworkCredential(emailUser, emailPass);
  340.             }
  341.             catch (SystemException excep)
  342.             {
  343.                 EventLog.WriteEntry("MAM", excep.Message);
  344.  
  345.             }
  346.  
  347.             smtpServer.EnableSsl = true;
  348.  
  349.             EventLog.WriteEntry("MAM", "Email enabled - set sender");
  350.             mail.From = new MailAddress(custProps.get("/MineStar.properties._EMAILUSER", ""));
  351.  
  352.             EventLog.WriteEntry("MAM", "Email enabled - set reciever");
  353.             mail.To.Add(custProps.get("/MineStar.properties._EMAILRECIPIENT", ""));
  354.  
  355.             //mail.Subject = "MineStar Availability Monitor - ALERT";
  356.             mail.Subject = subject;
  357.             //mail.Body = "MAM has detected a potential failure on " + System.Windows.Forms.SystemInformation.ComputerName + "\nThis is a system generated email\nPlease contact the MineStar System Administrator";
  358.             mail.Body = body;
  359.  
  360.             if (attachLog)
  361.             {
  362.                 EventLog.WriteEntry("MAM", "Email enabled - attach log");
  363.                 System.Net.Mail.Attachment attachment;
  364.                 attachment = new Attachment(mamFilename);
  365.                 mail.Attachments.Add(attachment);
  366.             }
  367.  
  368.             try
  369.             {
  370.                 EventLog.WriteEntry("MAM", "Email enabled - send mail");
  371.                 smtpServer.Send(mail);
  372.             }
  373.             catch (System.Net.Mail.SmtpException)
  374.             {
  375.                 StreamWriter sw = new StreamWriter(mamFilename, true);
  376.                 sw.WriteLine("Failed to send email ALERT");
  377.                 sw.Flush();
  378.                 sw.Close();
  379.             }
  380.             mail.Dispose();
  381.             //smtpServer.Dispose();
  382.             //smtpServer = null;
  383.         }
  384.  
  385.         internal void LoadConfig(string file)
  386.         {
  387.             props = new Properties(file);
  388.  
  389.         }
  390.     }
  391. }
  392. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  393. using System;
  394. using System.Collections;
  395. using System.Collections.Generic;
  396. using System.Configuration.Install;
  397. using System.Linq;
  398. using System.ServiceProcess;
  399. using System.Text;
  400.  
  401. namespace MineStarAvailabilityMonitor
  402. {
  403.     static class Program
  404.     {
  405.         /// <summary>
  406.         /// The main entry point for the application.
  407.         /// </summary>
  408.         static void Main(string[] args)
  409.         {
  410.             if (args.Length != 0)
  411.             {
  412.                 switch (args[0])
  413.                 {
  414.                     case "-install":
  415.                         Console.WriteLine("Attempting to install MineStar Application Monitor on this machine.\n Administrator privilage required");
  416.                         InstallService();
  417.                         return;
  418.  
  419.                     case "-uninstall":
  420.                         UninstallService();
  421.                         return;
  422.  
  423.                     default:
  424.                         // Must be normal args
  425.                         break;
  426.  
  427.                 }
  428.             }
  429.  
  430.             ServiceBase[] ServicesToRun;
  431.             ServicesToRun = new ServiceBase[]
  432.             {
  433.                 new Service1()
  434.             };
  435.             ServiceBase.Run(ServicesToRun);
  436.         }
  437.  
  438.         private static void InstallService()
  439.         {
  440.             if (IsInstalled()) return;
  441.             try
  442.             {
  443.                 using (AssemblyInstaller installer = GetInstaller())
  444.                 {
  445.                     IDictionary state = new Hashtable();
  446.                     try
  447.                     {
  448.                         installer.Install(state);
  449.                         installer.Commit(state);
  450.                     }
  451.                     catch
  452.                     {
  453.                         try
  454.                         {
  455.                             installer.Rollback(state);
  456.                         }
  457.                         catch { }
  458.                         throw;
  459.                     }
  460.                 }
  461.             }
  462.             catch
  463.             {
  464.                 throw;
  465.             }
  466.  
  467.         }
  468.  
  469.         private static void UninstallService()
  470.         {
  471.             if (!IsInstalled()) return;
  472.             try
  473.             {
  474.                 using (AssemblyInstaller installer = GetInstaller())
  475.                 {
  476.                     IDictionary state = new Hashtable();
  477.                     try
  478.                     {
  479.                         installer.Uninstall(state);
  480.                     }
  481.                     catch
  482.                     {
  483.                         throw;
  484.                     }
  485.                 }
  486.             }
  487.             catch
  488.             {
  489.                 throw;
  490.             }
  491.         }
  492.  
  493.         private static bool IsInstalled()
  494.         {
  495.             using (ServiceController controller =
  496.                 new ServiceController("MAM"))
  497.             {
  498.                 try
  499.                 {
  500.                     ServiceControllerStatus status = controller.Status;
  501.                 }
  502.                 catch
  503.                 {
  504.                     return false;
  505.                 }
  506.                 return true;
  507.             }
  508.         }
  509.  
  510.         private static AssemblyInstaller GetInstaller()
  511.         {
  512.             AssemblyInstaller installer = new AssemblyInstaller(typeof(Service1).Assembly, null);
  513.             installer.UseNewContext = true;
  514.             return installer;
  515.         }
  516.     }
  517. }
  518. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  519.  
  520. using System;
  521. using System.Collections;
  522. using System.Collections.Generic;
  523. using System.ComponentModel;
  524. using System.Configuration.Install;
  525. using System.Linq;
  526.  
  527. namespace MineStarAvailabilityMonitor
  528. {
  529.     [RunInstaller(true)]
  530.     public partial class ProjectInstaller : System.Configuration.Install.Installer
  531.     {
  532.         public ProjectInstaller()
  533.         {
  534.             InitializeComponent();
  535.         }
  536.  
  537.         private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
  538.         {
  539.  
  540.         }
  541.     }
  542. }
  543. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  544.  
  545. namespace MineStarAvailabilityMonitor
  546. {
  547.     partial class ProjectInstaller
  548.     {
  549.         /// <summary>
  550.         /// Required designer variable.
  551.         /// </summary>
  552.         private System.ComponentModel.IContainer components = null;
  553.  
  554.         /// <summary>
  555.         /// Clean up any resources being used.
  556.         /// </summary>
  557.         /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  558.         protected override void Dispose(bool disposing)
  559.         {
  560.             if (disposing && (components != null))
  561.             {
  562.                 components.Dispose();
  563.             }
  564.             base.Dispose(disposing);
  565.         }
  566.  
  567.         #region Component Designer generated code
  568.  
  569.         /// <summary>
  570.         /// Required method for Designer support - do not modify
  571.         /// the contents of this method with the code editor.
  572.         /// </summary>
  573.         private void InitializeComponent()
  574.         {
  575.             this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
  576.             this.MAMServiceInstaller = new System.ServiceProcess.ServiceInstaller();
  577.             //
  578.             // serviceProcessInstaller1
  579.             //
  580.             this.serviceProcessInstaller1.Password = null;
  581.             this.serviceProcessInstaller1.Username = null;
  582.             this.serviceProcessInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_AfterInstall);
  583.             //
  584.             // MAMServiceInstaller
  585.             //
  586.             this.MAMServiceInstaller.Description = "MineStar Availability Monitoring Service";
  587.             this.MAMServiceInstaller.DisplayName = "MineStar Availability Monitor";
  588.             this.MAMServiceInstaller.ServiceName = "MAM";
  589.             this.MAMServiceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
  590.             //
  591.             // ProjectInstaller
  592.             //
  593.             this.Installers.AddRange(new System.Configuration.Install.Installer[] {
  594.             this.serviceProcessInstaller1,
  595.             this.MAMServiceInstaller});
  596.  
  597.         }
  598.  
  599.         #endregion
  600.  
  601.         private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
  602.         private System.ServiceProcess.ServiceInstaller MAMServiceInstaller;
  603.     }
  604. }
  605.  
  606. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  607.  
  608. using System;
  609. using System.Collections.Generic;
  610. using System.Linq;
  611. using System.Text;
  612.  
  613. namespace MineStarAvailabilityMonitor
  614. {
  615.     public class Properties
  616.     {
  617.         private Dictionary<String, String> list;
  618.         private String filename;
  619.  
  620.         public Properties(String file)
  621.         {
  622.             reload(file);
  623.         }
  624.  
  625.         public String get(String field, String defValue)
  626.         {
  627.             return (get(field) == null) ? (defValue) : (get(field));
  628.         }
  629.         public String get(String field)
  630.         {
  631.             return (list.ContainsKey(field)) ? (list[field]) : (null);
  632.         }
  633.  
  634.         public void set(String field, Object value)
  635.         {
  636.             if (!list.ContainsKey(field))
  637.                 list.Add(field, value.ToString());
  638.             else
  639.                 list[field] = value.ToString();
  640.         }
  641.  
  642.         public void Save()
  643.         {
  644.             Save(this.filename);
  645.         }
  646.  
  647.         public void Save(String filename)
  648.         {
  649.             this.filename = filename;
  650.  
  651.             if (!System.IO.File.Exists(filename))
  652.                 System.IO.File.Create(filename);
  653.  
  654.             System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
  655.  
  656.             foreach (String prop in list.Keys.ToArray())
  657.                 if (!String.IsNullOrEmpty(list[prop]))
  658.                     file.WriteLine(prop + "=" + list[prop]);
  659.  
  660.             file.Close();
  661.         }
  662.  
  663.         public void reload()
  664.         {
  665.             reload(this.filename);
  666.         }
  667.  
  668.         public void reload(String filename)
  669.         {
  670.             this.filename = filename;
  671.             list = new Dictionary<String, String>();
  672.  
  673.             if (System.IO.File.Exists(filename))
  674.                 loadFromFile(filename);
  675.             else
  676.                 System.IO.File.Create(filename);
  677.         }
  678.  
  679.         private void loadFromFile(String file)
  680.         {
  681.             foreach (String line in System.IO.File.ReadAllLines(file))
  682.             {
  683.                 if ((!String.IsNullOrEmpty(line)) &&
  684.                     (!line.StartsWith(";")) &&
  685.                     (!line.StartsWith("#")) &&
  686.                     (!line.StartsWith("'")) &&
  687.                     (line.Contains('=')))
  688.                 {
  689.                     int index = line.IndexOf('=');
  690.                     String key = line.Substring(0, index).Trim();
  691.                     String value = line.Substring(index + 1).Trim();
  692.  
  693.                     if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
  694.                         (value.StartsWith("'") && value.EndsWith("'")))
  695.                     {
  696.                         value = value.Substring(1, value.Length - 2);
  697.                     }
  698.  
  699.                     try
  700.                     {
  701.                         //ignore dublicates
  702.                         list.Add(key, value);
  703.                     }
  704.                     catch { }
  705.                 }
  706.             }
  707.         }
  708.  
  709.  
  710.     }
  711. }
  712. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  713.  
  714. using System;
  715. using System.Collections.Generic;
  716. using System.ComponentModel;
  717. using System.Data;
  718. using System.Diagnostics;
  719. using System.Linq;
  720. using System.Runtime.InteropServices;
  721. using System.ServiceProcess;
  722. using System.Text;
  723. using System.Threading;
  724.  
  725.  
  726. namespace MineStarAvailabilityMonitor
  727. {
  728.     [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
  729.     public struct SERVICE_STATUS
  730.     {
  731.         public int serviceType;
  732.         public int currentState;
  733.         public int controlsAccepted;
  734.         public int win32ExitCode;
  735.         public int serviceSpecificExitCode;
  736.         public int checkPoint;
  737.         public int waitHint;
  738.     }
  739.  
  740.     public enum State
  741.     {
  742.         SERVICE_STOPPED = 0x00000001,
  743.         SERVICE_START_PENDING = 0x00000002,
  744.         SERVICE_STOP_PENDING = 0x00000003,
  745.         SERVICE_RUNNING = 0x00000004,
  746.         SERVICE_CONTINUE_PENDING = 0x00000005,
  747.         SERVICE_PAUSE_PENDING = 0x00000006,
  748.         SERVICE_PAUSED = 0x00000007,
  749.     }
  750.  
  751.     public partial class Service1 : ServiceBase
  752.     {
  753.         [DllImport("ADVAPI32.DLL", EntryPoint = "SetServiceStatus")]
  754.         public static extern bool SetServiceStatus(
  755.                         IntPtr hServiceStatus,
  756.                         SERVICE_STATUS lpServiceStatus
  757.                         );
  758.         private SERVICE_STATUS myServiceStatus;
  759.  
  760.  
  761.         private Monitor monitor;
  762.         private Timer monTimer;
  763.         private TimerCallback timerDelegate;
  764.         private string systemName = "main";
  765.         private long startDelay = 1000;
  766.         private long period = 300000;
  767.  
  768.         public Service1()
  769.         {
  770.             InitializeComponent();
  771.         }
  772.  
  773.         protected override void OnStart(string[] args)
  774.         {
  775.  
  776.             // If we have some args use them before checking the image path args
  777.             if (args.Length != 0)
  778.             {
  779.                 // 0 = system 1 = start delay 2 = period
  780.                 if (args[0] != String.Empty)
  781.                 {
  782.                     systemName = args[0];
  783.                     if (args[1] != String.Empty)
  784.                     {
  785.                         startDelay = Convert.ToInt64(args[1]);
  786.                         if (args[2] != String.Empty)
  787.                         {
  788.                             period = Convert.ToInt64(args[2]);
  789.                         }
  790.                     }
  791.  
  792.                 }
  793.             }
  794.             else
  795.             {
  796.                 string[] imagePathArgs = Environment.GetCommandLineArgs();
  797.                 if (imagePathArgs.Length == 1)
  798.                 {
  799.                     // Use defaults
  800.                 }
  801.                 else
  802.                 {
  803.                     // The first arg needs to be the system name
  804.                     if (imagePathArgs[1] != String.Empty)
  805.                     {
  806.                         systemName = imagePathArgs[1];
  807.                         if (imagePathArgs[2] != String.Empty)
  808.                         {
  809.                             startDelay = Convert.ToInt64(imagePathArgs[2]);
  810.                             if (imagePathArgs[3] != String.Empty)
  811.                             {
  812.                                 period = Convert.ToInt64(imagePathArgs[3]);
  813.                             }
  814.                         }
  815.                     }
  816.                 }
  817.             }
  818.  
  819.             IntPtr handle = this.ServiceHandle;
  820.             myServiceStatus.currentState = (int)State.SERVICE_START_PENDING;
  821.             SetServiceStatus(handle, myServiceStatus);
  822.  
  823.             // Check for properties file
  824.             string file = FindConfigFile();
  825.             if (file.Equals("NOFILE"))
  826.             {
  827.                 myServiceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
  828.                 SetServiceStatus(handle, myServiceStatus);
  829.                 return;
  830.             }
  831.  
  832.             monitor = new Monitor(systemName, file);
  833.  
  834.             timerDelegate = new TimerCallback(monitor.CheckJVM);
  835.             monTimer = new Timer(timerDelegate, null, startDelay, period);
  836.  
  837.             myServiceStatus.currentState = (int)State.SERVICE_RUNNING;
  838.             SetServiceStatus(handle, myServiceStatus);
  839.  
  840.  
  841.         }
  842.  
  843.         protected override void OnStop()
  844.         {
  845.             //monTimer.Dispose();
  846.         }
  847.  
  848.         /*******************************
  849.          * Search for a file in known location on various drives
  850.          * C,D,E,F
  851.          * mstarFiles/systems/main
  852.          *
  853.          *******************************/
  854.         protected String FindConfigFile()
  855.         {
  856.             char drive = 'C';
  857.  
  858.             string dir = ":\\mstar\\";
  859.  
  860.             string filename = "LICENSE.key";
  861.             bool found = false;
  862.  
  863.             while (!found && drive <= 'Z')
  864.             {
  865.  
  866.                 if (System.IO.File.Exists(drive + dir + filename))
  867.                 {
  868.                     found = true;
  869.  
  870.                     return drive + dir + filename;
  871.                 }
  872.                 else
  873.                     drive++;
  874.             }
  875.             return "NOFILE";
  876.         }
  877.     }
  878. }
  879. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  880. namespace MineStarAvailabilityMonitor
  881. {
  882.     partial class Service1
  883.     {
  884.         /// <summary>
  885.         /// Required designer variable.
  886.         /// </summary>
  887.         private System.ComponentModel.IContainer components = null;
  888.  
  889.         /// <summary>
  890.         /// Clean up any resources being used.
  891.         /// </summary>
  892.         /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  893.         protected override void Dispose(bool disposing)
  894.         {
  895.             if (disposing && (components != null))
  896.             {
  897.                 components.Dispose();
  898.             }
  899.             base.Dispose(disposing);
  900.         }
  901.  
  902.         #region Component Designer generated code
  903.  
  904.         /// <summary>
  905.         /// Required method for Designer support - do not modify
  906.         /// the contents of this method with the code editor.
  907.         /// </summary>
  908.         private void InitializeComponent()
  909.         {
  910.             components = new System.ComponentModel.Container();
  911.             this.ServiceName = "Service1";
  912.         }
  913.  
  914.         #endregion
  915.     }
  916. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement