2011-03-28 82 views
-1
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data; 
using System.Data.SqlClient; 
using System.IO; 
using System.Net; 
using System.Diagnostics; 
using System.Configuration; 
using System.Collections; 
using System.Timers; 
using System.Text.RegularExpressions; 
using System.Globalization; 
using System.Net.Mail; 


namespace VSATStatusReader 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      //Modified by Reema for generating log in table and trigger mail on success or failure of this utility on 16-feb-2011. 
       try 
       { 
        InsertIntoJobLogTable("Utility Started", "S"); 
        UtilityMainFunction(); 
       } 
       catch (Exception ex) 
       { 
        InsertIntoJobLogTable("Error on returning from UtilityMainFunction function: '" + ex.Message + "' ", "E"); 
        UtilityRunMailToProMonSys("0", "'" + ex.Message + "'", "", ""); 
       } 
     } 

     public static void UtilityMainFunction() 
     { 
      DataSet ds; 
      string IP = ""; 

      ds = new DataSet(); 

      try 
      { 
       ds = getDataSet("select gateway_ip as IP from shannonnew..gateway_info").Copy(); 

       foreach (DataRow dRow in ds.Tables[0].Rows) 
       { 
        IP = dRow["IP"].ToString(); 

        CreateRunBatchFile(IP); 

        string[] DNCCfileEntries = Directory.GetFiles("c:/VSATStatus/VSATStatusFiles"); 
        string connString = getConnString(); 
        SqlConnection myDbConnection = new SqlConnection(connString); 
        myDbConnection.Open(); 

        foreach (string fileName in DNCCfileEntries) 
        { 
         FileStream file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read); 

         StreamReader sr = new StreamReader(file); 

         ArrayList finalWordList; 

         string s = sr.ReadToEnd(); 
         string[] lines = Regex.Split(s, "\r\n"); 

         foreach (string line in lines) 
         { 
          string formatedLine = line.Replace("iso.3.6.1.4.1.303.3.3.19.6.3.25.1.3.", ""); 
          string[] words = formatedLine.Split(' '); 
          finalWordList = new ArrayList(); 
          if (words[0].ToString() != "") 
          { 
           finalWordList.Add(words[0]); 
           finalWordList.Add(words[1]); 

           //Database Insert Code here 
           if (line.Trim() != "") 
           { 
            string strCmd = "Insert into ipgw_evp (Serial_No, VSAT_Status, Gateway_IP) values ('" + finalWordList[0] + "', '" + finalWordList[1] + "', '" + IP + "')"; 
            SqlCommand command = new SqlCommand(strCmd, myDbConnection); 
            command.ExecuteNonQuery(); 
           } 
          } 
         } 
         sr.Close(); 
         file.Close(); 
        } 
        myDbConnection.Close(); 
       } 
       InsertIntoJobLogTable("Utility Ended", "C"); 
       //UtilityRunMailToProMonSys("1", "success", ""); 
      } 
      catch (Exception ex) 
      { 
       InsertIntoJobLogTable("Error in UtilityMainFunction:'" + ex.Message + "' ", "F"); 
       UtilityRunMailToProMonSys("0", "'" + ex.StackTrace.ToString() + "'", "'" + IP + "'", "'" + ex.Message + "'"); 
       Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString()); 
      } 
     } 

     private static string getConnString() 
     { 
      string connectionProperties = ConfigurationSettings.AppSettings["ProMonSysConsoleString"]; 
      return connectionProperties; 
     } 

     public static void CreateRunBatchFile(string IP) 
     { 
      //change the path as required 
      string filepath = "c:/VSATStatus\\VSATStatus.bat"; 

      try 
      { 
       StreamWriter sw = File.CreateText(filepath); 

       sw.WriteLine("del C:\\VSATStatus\\VSATStatusFiles\\VSATStatus.txt"); 
       sw.WriteLine("@echo off"); 
       sw.WriteLine("Snmpwalk -v 1 -O q -c public " + IP + " 1.3.6.1.4.1.303.3.3.19.6.3.25.1.3 >>C:\\VSATStatus\\VSATStatusFiles\\VSATStatus.txt"); 
       sw.Close(); 

       Process p = null; 

       string targetDir; 
       targetDir = string.Format(@"C:\VSATStatus"); 
       p = new Process(); 
       p.StartInfo.WorkingDirectory = targetDir; 
       p.StartInfo.FileName = "VSATStatus.bat"; 
       p.StartInfo.Arguments = string.Format("C-Sharp Console application"); 
       p.StartInfo.CreateNoWindow = true; 
       p.Start(); 
       p.WaitForExit(); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString()); 
      } 
     } 

     public static DataSet getDataSet(string strCmd) 
     { 
      SqlCommand command; 
      SqlDataAdapter da; 
      DataSet ds; 

      string connString = getConnString(); 
      SqlConnection myDbConnection = new SqlConnection(connString); 
      myDbConnection.Open(); 

      command = new SqlCommand(strCmd, myDbConnection); 
      command.CommandType = CommandType.Text; 
      da = new SqlDataAdapter(command); 
      ds = new DataSet(); 
      da.Fill(ds); 

      myDbConnection.Close(); 

      return ds; 
     } 

     //changed by Reema for sending massage and stacktrace in mails. 
     public static void UtilityRunMailToProMonSys(string str, string stacktr, string IP, string error) 
     { 
      try 
      { 
       string msg = ""; 
       msg += "<BR>"; 
       if (str == "0") 
       { 
        msg += "VSATStatusReader Utillity fails."; 
        msg += "<BR>"; 
        msg += "<BR>Failed IP Gateway is : '" + IP + "' "; 
        msg += "<BR>"; 
        msg += "<BR>"; 
        msg += "Exception is : '" + error + "' "; 
        msg += "<BR>"; 
        msg += "<BR>"; 
        msg += "'" + stacktr + "'"; 
        msg += "<BR>"; 
       } 
       //else 
       //{ 
       // msg += "VSATStatusReader Utility run successfully. "; 
       //} 
       msg += "<BR>"; 
       msg += "<BR>Regards,"; 
       msg += "<BR>ProMonSys Admin"; 
       msg += "<BR>"; 
       var message = new MailMessage(ConfigurationSettings.AppSettings["DefaultEmail"], ConfigurationSettings.AppSettings["ToMail"]) 
       { 
        Subject = " ProMonSys VSATStatusReader Utility Status", 
        Body = msg, 
        IsBodyHtml = true 
       }; 

       var client = new SmtpClient(ConfigurationSettings.AppSettings["MailServer"]); 
       client.Send(message); 
      } 
      catch (Exception ex) 
      { 

      } 
     } 


     public static void InsertIntoJobLogTable(string Msg, string MsgType) 
     { 
      SqlCommand Cmd = new SqlCommand(); 
      SqlConnection Conn = new SqlConnection(ConfigurationSettings.AppSettings["ProMonSysConsoleString"]); 
      try 
      { 

       if (Msg.Length > 8000) 
       { 
        Msg = Msg.Substring(0, 7999); 
       } 
       else if (Msg.IndexOf("'") >= 0) 
       { 
        Msg = Msg.Replace("'", ""); 
       } 

       Cmd.Connection = Conn; 
       Cmd.CommandType = CommandType.StoredProcedure; 
       Cmd.CommandText = "Create_Job_Utility_Log_SP"; 
       Cmd.Parameters.Clear(); 
       Cmd.Parameters.Add("@vcJobName", "VSATStatusReader_Utility"); 
       Cmd.Parameters.Add("@vcModule", "ProMonSys"); 
       Cmd.Parameters.Add("@dtType", MsgType); 
       Cmd.Parameters.Add("@vcJobType", "U"); 
       Cmd.Parameters.Add("@vcDBUsed", "VSATStatusProgram, ProMonSys"); 
       Cmd.Parameters.Add("@vcJobStatus", Msg); 
       Conn.Open(); 
       Cmd.ExecuteNonQuery(); 
       Conn.Close(); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString()); 
      } 
      finally 
      { 
       Conn.Dispose(); 
       Cmd.Dispose(); 
      } 

     } 
    } 

    //public class MailHelper 
    //{ 
    // public static void SendMailMessage(string from, string to, string bcc, string cc, string subject, string body) 
    // { 
    //  MailMessage mMailMessage = new MailMessage(); 
    //  mMailMessage.From = new MailAddress(from); 
    //  mMailMessage.To.Add(new MailAddress(to)); 

    //  if ((bcc != null) && (bcc != string.Empty)) 
    //  { 
    //   mMailMessage.Bcc.Add(new MailAddress(bcc)); 
    //  } 
    //  if ((cc != null) && (cc != string.Empty)) 
    //  { 
    //   mMailMessage.CC.Add(new MailAddress(cc)); 
    //  } 
    //  mMailMessage.Subject = subject;    
    //  mMailMessage.Body = body; 

    //  mMailMessage.IsBodyHtml = true; 
    //  mMailMessage.Priority = MailPriority.Normal; 

    //  SmtpClient mSmtpClient = new SmtpClient(); 
    //  mSmtpClient.Send(mMailMessage); 
    // } 
    //} 


} 

這是我的代碼..這個代碼運行良好,我以前的服務器是在Windows 2008上配置的,但是當我想嘗試在Windows 2003中運行此代碼時,有時會運行但有時在 SYSTEM \ VSATStatus \ VSATStatusFiles \ VSATStatus.txt ' 被拒絕。 ''Windows IO錯誤

'':這是給此異常:

的例外是: '' 訪問路徑 ' C。 IO .__ Error.WinIOError(Int32 errorCode,String ma ybeFullPath)在 System.IO.FileStream.Init(字符串路徑, 的FileMode模式,FileAccess的訪問, 的Int32權利,布爾useRights, 文件共享份額,緩衝區大小的Int32, FileOptions選項, SECURITY_ATTRIBUTES secAttrs,字符串 MSGPATH,布爾bFromProxy )在 System.IO.FileStream..ctor(字符串 路徑,的FileMode模式,FileAccess的 訪問)在 VSATStatusReader.Program.UtilityMainFunction() 在 C:\的Inetpub \ wwwroot的\ VSATStatusReader \ VSATStatusReader \ Program.cs中: line 61''

回答

0

是否存在路徑並且是否有權寫入它?從例外檢查您有wwwroot浮動事實檢查您正在使用的服務帳戶有寫入權限C:\VSATStatus\VSATStatusFiles

+0

Ya此路徑存在且VSATStatus文件夾具有寫入權限。 – 2011-03-28 10:36:43

0

我相信這是因爲正在使用文本文件。要麼在調試/測試時沒有正確關閉它。或者正在被另一個程序使用。

+0

此應用程序在生產服務器上運行,不在調試/測試。此文件僅用於此特定文件夾,並在上面我正確地關閉文件。 – 2011-03-28 10:43:04

+0

@Reema:如果這是一個可被多人訪問的網站,那麼當另一個人試圖訪問該文件時,該文件可能會被一個人使用。 – 2011-03-28 11:08:12

+0

1)所有IPGW的IP都從shannonnew..gateway_info獲取。 2)爲每個IPGW服務器啓動一個循環。 3)在每個循環中,使用函數CreateRunBatchFile創建並執行批處理文件,如c:/ VSATStatus \\ VSATStatus.bat,其中包含使用snmpwalk.exe的簡單SNMP命令,該文件保存在VSATStatus文件夾中,輸出結果寫入在VSATStatusFiles文件夾內有一個名爲VSATStatus.txt的文本文件,它具有一個路徑C:\\ VSATStatus \\ VSATStatusFiles \\ VSATStatus.txt。 – 2011-03-28 11:37:46