List declaration help please

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hello,
First off, Im no where near an expert to C# programming, but I wouldnt consider myself a beginner. Most of the problems Ive had with this service Im writing Ive been able to figure out, this one has me stumped, mainly because I still have a hard
time grasping the public, private, static stuff. Anyway, Ill describe the problem and then paste my code.
My current problem is that Im trying to populate a List<> from an XML file. I do this right after the InitializeComponent(). When I put some debugging lines to write to the event log within the LoadFromXML region, it shows that it has
populated the List<>. But, when the _timer_elapsed executes, its showing there are no items in the List and therefor throwing an exception of index out of range in my Vars region. I think it has something to do with the way I declare the
list, but Ive tried many different things and none seem to fix it.
So, if you can help me, Id appreciate it. Also, if there are any other "best practices" type things I should take into account for this service, Id appreciate those as well. As a side note, I dont have as much error handling in there as the
final product will have, Ill be adding a few more try-catch things in there.
<pre lang="x-c# using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using System.IO;
using System.Net.Mail;
using System.Net;
using System.Timers;
using System.Xml;

namespace HostFileService
{
public partial class HostFileService : ServiceBase
{
private static EventLog appLog = new EventLog();

//grab the information from app.config
private static string FTPServer = ConfigurationManager.AppSettings["FTPServer"];
private static string sendto = ConfigurationManager.AppSettings["SendTo"];
private static string mailserver = ConfigurationManager.AppSettings["MailServer"];
private static int timerinterval = Convert.ToInt32(ConfigurationManager.AppSettings["timerinterval"]);
private static string XMLFileLocation = ConfigurationManager.AppSettings["XMLFileLocation"];
private static List<Facility> FacilityList = new List<Facility>();
private static string tempDir = Path.GetTempPath();
private static DateTime now = DateTime.Now;
private static int ListSize = 0;
private Timer _timer;

public HostFileService()
{
InitializeComponent();

//take the information from the app.config file and put it into a List
#region LoadFromXML
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(XMLFileLocation + "HostFileService.xml");
XmlNodeList XmlDocNodes = XmlDoc.SelectNodes("/facilities/facility");
List<Facility> FacilityList = new List<Facility>();
foreach (XmlNode node in XmlDocNodes)
{
Facility obj = new Facility(node["name"].InnerText,
node["username"].InnerText,
node["password"].InnerText,
node["filenametemplate"].InnerText,
node["DFSPath"].InnerText,
node["modifydate"].InnerText,
node["FTPDir"].InnerText);
FacilityList.Add(obj);
}
ListSize = FacilityList.Count();
#endregion

if (!EventLog.SourceExists("HostFileService"))
{
EventLog.CreateEventSource("HostFileService", "Application");
}

_timer = new Timer();
_timer.Interval = timerinterval;
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);

}

protected override void OnStart(string[] args)
{
_timer.Start();
}

protected override void OnStop()
{
_timer.Stop();
}

private static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
WriteToEventLog("Timer Execution - Facilities: " + ListSize, "HostFileService", EventLogEntryType.Information, "Application");
try
{
WriteToEventLog("ListSize: " + FacilityList.Count(), "HostFileService", EventLogEntryType.Information, "Application");
for (int i = 0; i < ListSize; i++)
{
WriteToEventLog("Declare variables - Count " + i + " of " + ListSize, "HostFileSerivce", EventLogEntryType.Information, "Application");
//define some variables to make the code more readable below
#region Vars
string _facility = FacilityList._facility;
string _username = FacilityList._username;
string _password = FacilityList._password;
string _filenametemplate = FacilityList._filenametemplate;
string _DFSPath = FacilityList._DFSPath;
string _datemodify = FacilityList._datemodify;
string _ftpdir = FacilityList._ftpdir;
#endregion

WriteToEventLog("Working on " + _facility, "HFS: " + _facility, EventLogEntryType.Information, "Application");

now = (Convert.ToBoolean(_datemodify) ? DateTime.Now.AddDays(-1) : DateTime.Now);

//generate a filename based on a template
WriteToEventLog("Attempting GenerateFileName", "HFS: " + _facility, EventLogEntryType.Information, "Application");
string FTPFile = GenerateFilename(_filenametemplate);

//download the file from the FTP server
WriteToEventLog("Attempting to download the file", "HFS: " + _facility, EventLogEntryType.Information, "Application");
string OutFile = downloadFile(FTPFile, _username, _password, _ftpdir);

//check to see if a file was downloaded
if (OutFile != "")
{
WriteToEventLog("The file was downloaded", "HFS: " + _facility, EventLogEntryType.Information, "Application");
FileInfo FileName = new FileInfo(OutFile);
string DecryptedFile = DecryptFile(FileName, _DFSPath);
//check to see if a file was decrypted
if (DecryptedFile != "")
{
if (File.Exists(DecryptedFile))
{
WriteToEventLog("The file was decrypted", "HFS: " + _facility, EventLogEntryType.Information, "Application");
//move the file on the FTP server to the processed folder
//MoveFTPFile(FTPFile, FileName, _username, _password, _ftpdir);
SendMail(_facility + "Host File Upload Success", "The host file upload for " + _facility + " was successfully transferred." + Environment.NewLine + Environment.NewLine + DecryptedFile);
WriteToEventLog("The host file upload for " + _facility + " was successfully transferred." + Environment.NewLine + Environment.NewLine + DecryptedFile, "HFS: " + _facility, EventLogEntryType.Information, "Application");
}
}
else //no file was decrypted
{
SendMail(_facility + " Host File Upload Failure", "The file for " + _facility + " is on the FTP server, but not on the L: drive");
WriteToEventLog("The host file upload for " + _facility + " was unsuccessfull." + Environment.NewLine + Environment.NewLine + DecryptedFile, "HFS: " + _facility, EventLogEntryType.Information, "Application");
}
FileName.Delete();
}
else //no file was downloaded
{
string FTPString = FTPServer + "processed/" + FTPFile;
//if the file doesnt exist in the main folder, and it doesnt exist in the processed folder, then the host hasnt uploaded the file yet.
if (!ftpFileExist(FTPString, _username, _password))
{
SendMail(_facility + " Host File Upload Failure", "The file for " + _facility + " is not on the FTP server" + Environment.NewLine + Environment.NewLine + FTPFile + " was not on the FTP Server");
WriteToEventLog("The host file upload for " + _facility + " was unsuccessfull." + Environment.NewLine + Environment.NewLine + FTPFile + " was not on the FTP Server", "HFS: " + _facility, EventLogEntryType.Information, "Application");
}

}
}
WriteToEventLog("After For Loop", "HostFileService", EventLogEntryType.Information, "Application");
}
catch (Exception ex)
{
WriteToEventLog(ex.Message.ToString(), "HostFileService", EventLogEntryType.Information, "Application");
throw;
}
}

private static void WriteToEventLog(string Entry, string AppName, EventLogEntryType EventType, String LogName)
{
EventLog objEventLog = new EventLog();
objEventLog.Source = AppName;
objEventLog.WriteEntry(Entry, EventType);
}

private static bool ftpFileExist(string fileName, string username, string password)
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential(username, password);
byte[] fData = wc.DownloadData(fileName);
if (fData.Length > -1) return true;
else return false;
}

private static void SendMail(string subject, string body)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient(mailserver);
mail.From = new MailAddress("automated_file_upload@test.com");
mail.To.Add(sendto);
mail.Subject = subject;
mail.Body = body;
SmtpServer.Send(mail);
}

private static void MoveFTPFile(string FTPfilename, FileInfo localfile, string username, string password, string ftpdir)
{
string FTPString = FTPServer + "processed/" + FTPfilename;

WebClient request = new WebClient();
request.Credentials = new NetworkCredential(username, password);
request.UploadFile(FTPString, localfile.FullName);
FTPString = (ftpdir == "null" ? FTPServer + FTPfilename : FTPServer + ftpdir + FTPfilename);
FtpWebRequest requestdelete = (FtpWebRequest)WebRequest.Create(FTPString);
requestdelete.Credentials = new NetworkCredential(username, password);
requestdelete.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse responsedelete = (FtpWebResponse)requestdelete.GetResponse();
}

private static string GenerateFilename(string filename)
{
filename = filename.Replace("mm", String.Format("{0:MM}", now));
filename = filename.Replace("dd", String.Format("{0:dd}", now));
filename = filename.Replace("yyyy", String.Format("{0:yyyy}", now));
filename = filename.Replace("yy", String.Format("{0:yy}", now));
return filename;
}

private static string downloadFile(string FTPfilename, string username, string password, string ftpdir)
{
string SaveFile = tempDir + username + String.Format("{0:yy}", now) + String.Format("{0:MM}", now) + String.Format("{0:dd}", now) + ".pgp";
string FTPString = (ftpdir == "null" ? FTPServer + FTPfilename : FTPServer + ftpdir + FTPfilename);

try
{
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(username, password);
request.DownloadFile(FTPString, SaveFile);

return SaveFile;
}
catch { return ""; }
}

private static string DecryptFile(FileInfo encryptedFile, string DFSPath)
{
string FileName = encryptedFile.Name;
string outputFileName = DFSPath + FileName.Substring(0, FileName.Length - 4) + ".txt";

try
{
ProcessStartInfo pInfo = new ProcessStartInfo("cmd.exe");
pInfo.CreateNoWindow = true;
pInfo.UseShellExecute = false;
pInfo.RedirectStandardInput = true;
pInfo.RedirectStandardOutput = true;
pInfo.RedirectStandardError = true;
pInfo.WorkingDirectory = "C:\pgphome";
string sCommandLine = "pgp.exe --passphrase passphrase" +
" --output "" + outputFileName +
"" --decrypt "" + encryptedFile.FullName + """;

Process process = Process.Start(pInfo);
process.StandardInput.WriteLine(sCommandLine);
process.StandardInput.Flush();
process.StandardInput.Close();
process.WaitForExit();
process.Close();

return outputFileName;
}
catch { return ""; }
}

public class Facility
{
public string _facility { get; set; }
public string _username { get; set; }
public string _password { get; set; }
public string _filenametemplate { get; set; }
public string _DFSPath { get; set; }
public string _datemodify { get; set; }
public string _ftpdir { get; set; }

public Facility(string f, string u, string p, string fnt, string d, string dm, string fd)
{
this._facility = f;
this._username = u;
this._password = p;
this._filenametemplate = fnt;
this._DFSPath = d;
this._datemodify = dm;
this._ftpdir = fd;
}
}
}
}[/code]

View the full article
 
Back
Top