/// <summary> /// Function is the equivelant of generating matches by putting names in a bowl mixing it and pulling names out at random. /// </summary> /// <param name="in_csv_list">List with CSV rows, each row has one person then a list of people who cannot be matched with that person</param> /// <param name="num_bowl_mixes">Number of times to "Mix the bowl" (randomize the list) before matching</param> /// <param name="max_retries">Max number of retries per person before failure</param> /// <returns></returns> public static List<string> RandomMatch(LOG_OPTIONS logger_options, List<string> in_csv_list, int num_bowl_mixes, int max_retries) { Random random = new Random(); List<string> output = new List<string>(); List<string> randomized_list = new List<string>(in_csv_list); //Console.WriteLine("Mixing the bowl..."); Logger.Write(logger_options, module, "Mixing the bowl..."); for (int i = 0; i < num_bowl_mixes; i++) { randomized_list = RandomizeList(logger_options, randomized_list); //Mix up the bowl Thread.Sleep(random.Next(100)); } List<string> randomized_list_copy = new List<string>(randomized_list); Logger.Write(logger_options, module, "Generating the matches..."); //Perform random matches foreach (string item in randomized_list) { string match; randomized_list_copy = RemoveRandomItem(logger_options, randomized_list_copy, new List<string>(item.Split(',')), out match, 0, max_retries); Logger.Write(logger_options, module, "Matched: " + item.Split(',')[0] + " With: " + match); output.Add(item.Split(',')[0] + "," + match); Thread.Sleep(random.Next(15)); } return output; }
/// <summary> /// Performs an SNMP get request /// </summary> /// <param name="log_options">Log options</param> /// <param name="ip">IP of target device</param> /// <param name="in_community">Community name</param> /// <param name="oid">OID</param> /// <returns></returns> public static SnmpV1Packet Get(LOG_OPTIONS log_options, IPAddress ip, string in_community, string oid, bool get_next) { // SNMP community name OctetString community = new OctetString(in_community); // Define agent parameters class AgentParameters param = new AgentParameters(community); // Set SNMP version to 1 (or 2) param.Version = SnmpVersion.Ver1; // Construct target UdpTarget target = new UdpTarget(ip, 161, 2000, 1); // Pdu class used for all requests Pdu pdu; if (get_next) { pdu = new Pdu(PduType.GetNext); } else { pdu = new Pdu(PduType.Get); } pdu.VbList.Add(oid); //sysDescr // Make SNMP request SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); // If result is null then agent didn't reply or we couldn't parse the reply. if (result != null) { // ErrorStatus other then 0 is an error returned by // the Agent - see SnmpConstants for error definitions if (result.Pdu.ErrorStatus != 0) { // agent reported an error with the request Logger.Write(log_options, module, "Error in SNMP reply. Error " + result.Pdu.ErrorStatus.ToString() + " index " + result.Pdu.ErrorIndex.ToString()); } else { // Reply variables are returned in the same order as they were added // to the VbList Logger.Write(log_options, module, "OID: " + result.Pdu.VbList[0].Oid.ToString() + " Value: " + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + " : " + result.Pdu.VbList[0].Value.ToString()); } } else { Logger.Write(log_options, module, "No response received from SNMP agent."); } target.Close(); return result; }
public static void writeLog(LOG_OPTIONS options, string strLine) { lock (m_oLock) { try { if (m_strFilePath.Trim().Length != 0) { m_strFile = m_strFilePath + getLogFile(); m_oFile = new FileStream(m_strFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); m_oSW = new StreamWriter(m_oFile); writeLine(options, strLine); } } catch (Exception) { m_oFile.Close(); } } }
/// <summary> /// Start the port monitoring process /// </summary> /// <param name="com">COM port to monitor (i.e COM4, COM3, COM7, etc)</param> /// <param name="baud">Baud rate of COM port (i.e 9600, 19200, 38400, 115200, etc)</param> /// <returns></returns> public GENERAL_RESULT Start(LOG_OPTIONS in_log_options, string com, int baud) { try { port = new SerialPort(com); port.BaudRate = baud; port.StopBits = StopBits.One; port.DataBits = 8; port.Handshake = Handshake.None; port.RtsEnable = true; port.DataReceived += new SerialDataReceivedEventHandler(Receive); port.Open(); log_options = in_log_options; Logger.Write(log_options, module, "Opening com port: " + com); } catch (Exception e) { Logger.Write(log_options, module, "Exception: Start: " + e.ToString()); return GENERAL_RESULT.FAILED; } return GENERAL_RESULT.SUCCEEDED; }
public void AppendInfo(string i_infoMessage, LOG_OPTIONS i_logOptions = LOG_OPTIONS.AddFooterAndHeader) { LOG_INFO logInfo = new LOG_INFO(); if (i_logOptions.HasFlag(LOG_OPTIONS.AddLogTitle)) { logInfo.SetMessage("INFO: " + i_infoMessage); } else { logInfo.SetMessage(i_infoMessage); } logInfo.Id = GetNextLogInfoId(); logInfo.Level = LOG_LEVEL.Info; logInfo.LogOptions = i_logOptions; if (i_logOptions.HasFlag(LOG_OPTIONS.AddTime)) { logInfo.HasLogTime = true; logInfo.LogTime = DateTime.Now; } _logInfo.Add(logInfo); Display(); }
/// <summary> /// Generates a CSV file that has names randomly matched (two names per row) /// </summary> /// <param name="logger_options">Logging options</param> /// <param name="input_csv_file">CSV file of the format [PERSON, EXCLUDEDPERSON, EXCLUDED PERSON]</param> /// <param name="output_csv_file">CSV output file of the format [PERSON, MATCH]</param> /// <param name="num_bowl_mixes">Number of times to "Mix the bowl" (randomize the list) before matching</param> /// <param name="max_retries">Max number of retries per person before failure</param> /// <returns></returns> public static GENERAL_RESULT GenerateRandomMatchCSV(LOG_OPTIONS logger_options, string input_csv_file, string output_csv_file, int num_bowl_mixes, int max_retries) { try { if (File.Exists(input_csv_file)) { string[] file_data = File.ReadAllLines(input_csv_file); List<string> csv_data = new List<string>(); //Process the CSV to prevent issues foreach (string row in file_data) { if (row.Length > 2) { csv_data.Add(row); } else { Logger.Write(logger_options, module, "WARNING: Skipping CSV row: " + row); } } List<string> matches = RandomMatch(logger_options, csv_data, num_bowl_mixes, max_retries); File.WriteAllLines(output_csv_file, matches); return GENERAL_RESULT.SUCCEEDED; } else { Logger.Write(logger_options, module, "ERROR: File: " + input_csv_file + " does not exist; Unable to generate random matches"); return GENERAL_RESULT.FAILED; } } catch (Exception ex) { Logger.Write(logger_options, module, "EXCEPTION: Unable to generate random matches: " + ex.ToString()); return GENERAL_RESULT.FAILED; } }
/**************************************************** * WORD COUNT * DESCRIPTION: Counts the number of words in the given file. ****************************************************/ private void wordCount(string[] args) { string wordFile = null; bool log = false; bool silent = false; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-file")) { wordFile = GetStringParam(args, i); } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****wordcount Command****"); Logger.Write(log_options, module, "USAGE: wordcount -file [ASKII_FILE_PATH] -log (OPTION)"); Logger.Write(log_options, module, " -silent (OPTION)"); Logger.Write(log_options, module, "EXAMPLE: wordcount -file C:\\TI\\log.txt"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } if (wordFile != null) { if (File.Exists(wordFile)) { WordTools.CountWords(log_options, wordFile); } else { Logger.Write(log_options, module, "ERROR: Unable to find file: '" + wordFile + "'"); } } else { Logger.Write(log_options, module, "ERROR: Missing parameters wordcount command"); } }
private static void writeLine(LOG_OPTIONS Option, string strLine) { string strDebugLine = ""; try { m_oFile.Seek(0, SeekOrigin.End); switch (Option) { case LOG_OPTIONS.DEBUG: if (m_bDebug) { strDebugLine = "[" + Convert.ToString(DateTime.Now) + "][DEBUG]" + strLine; } break; case LOG_OPTIONS.ERROR: if (m_bError) { strDebugLine = "[" + Convert.ToString(DateTime.Now) + "][ERROR]" + strLine; } break; case LOG_OPTIONS.INFO: if (m_bInfo) { strDebugLine = "[" + Convert.ToString(DateTime.Now) + "][INFO]" + strLine; } break; case LOG_OPTIONS.KEYS: if (m_bKeys) { strDebugLine = "[" + Convert.ToString(DateTime.Now) + "][KEY]" + strLine; } break; case LOG_OPTIONS.SECURE: if (m_bSecure) { strDebugLine = "[" + Convert.ToString(DateTime.Now) + "][SECURE]" + strLine; } break; case LOG_OPTIONS.SQL: if (m_bSql) { strDebugLine = "[" + Convert.ToString(DateTime.Now) + "][SQL]" + strLine; } break; case LOG_OPTIONS.WARNING: if (m_bWarning) { strDebugLine = "[" + Convert.ToString(DateTime.Now) + "][WARNING]" + strLine; } break; case LOG_OPTIONS.PROPERTIES: if (m_bProperties) { strDebugLine = "[" + Convert.ToString(DateTime.Now) + "][PROPERTIES]" + strLine; } break; case LOG_OPTIONS.XML: if (m_bXml) { if (!m_bSecure) { if ((strLine.IndexOf("<PIN_BLOCK>") >= 0) && (strLine.IndexOf("</PIN_BLOCK>") > strLine.IndexOf("<PIN_BLOCK>"))) { string strFirstPart = strLine.Substring(0, (strLine.IndexOf("<PIN_BLOCK>") + 11)); string strLastPart = strLine.Substring(strLine.IndexOf("</PIN_BLOCK>")); strLine = strFirstPart + "..." + strLastPart; } if ((strLine.IndexOf("<PIN_REF>") >= 0) && (strLine.IndexOf("</PIN_REF>") > strLine.IndexOf("<PIN_REF>"))) { string strFirstPart = strLine.Substring(0, (strLine.IndexOf("<PIN_REF>") + 9)); string strLastPart = strLine.Substring(strLine.IndexOf("</PIN_REF>")); strLine = strFirstPart + "..." + strLastPart; } if ((strLine.IndexOf("DECRYPTED_VALUE") >= 0) && (strLine.IndexOf("</DECRYPTED_VALUE>") > strLine.IndexOf("<DECRYPTED_VALUE>"))) { string strFirstPart = strLine.Substring(0, (strLine.IndexOf("<DECRYPTED_VALUE>") + 17)); string strLastPart = strLine.Substring(strLine.IndexOf("</DECRYPTED_VALUE>")); strLine = strFirstPart + "..." + strLastPart; } } strDebugLine = "[" + Convert.ToString(DateTime.Now) + "] " + strLine; } break; } if (strDebugLine.Trim().Length > 0) { m_oSW.WriteLine(strDebugLine); } m_oSW.Flush(); m_oSW.Close(); m_oFile.Close(); } catch { } }
/***************************************************************** * LOAD DICTIONARY * DESCRIPTION: Load a dictionary into memory. *****************************************************************/ private static GENERAL_RESULT LoadDictionary(LOG_OPTIONS log_options, string path) { try { if (loadedDictionary == null || !loadedDictionary.Equals(path)) { loadedDictionary = path; } else { return GENERAL_RESULT.SUCCEEDED; } dictionary = new Dictionary<string, int>(); string[] readText = File.ReadAllLines(path); int lineIndex = 1; foreach (string line in readText) { if (!line.Contains("%")) { if (!dictionary.ContainsKey(line)) { dictionary.Add(line, 1); } else { Logger.Write(log_options, module, "WARNING: LoadDictionary: Attempted to add item twice: " + line + " line number: " + lineIndex.ToString()); } } lineIndex++; } return GENERAL_RESULT.SUCCEEDED; } catch (Exception e) { Logger.Write(log_options, module, "EXCEPTION: LoadDictionary: " + e.Message); return GENERAL_RESULT.FAILED; } }
/******************************************************* * WRITE *******************************************************/ private static void Write(LOG_OPTIONS options, string module, string input, Stopwatch watch, int retries) { //Generate the Date/Time Stamp string date_stamp = GenerateDateTimeStamp(); //Write to Console if (options == LOG_OPTIONS.CONSOLE_AND_LOG || options == LOG_OPTIONS.CONSOLE_ONLY) { Console.WriteLine(module + " : " + input); } try { //Write to the log if ((options == LOG_OPTIONS.LOG_ONLY || options == LOG_OPTIONS.CONSOLE_AND_LOG) && logFile != null) { using (StreamWriter sw = File.AppendText(logFile)) { if (watch != null) { sw.WriteLine(date_stamp + " : " + module + " : " + input + " : " + watch.ElapsedMilliseconds.ToString()); } else { sw.WriteLine(date_stamp + " : " + module + " : " + input); } } } } catch (Exception e) { if (retries < 4) { Write(options, module, input, watch, retries); } else { throw e; } } }
/// <summary> /// Performs an SNMP set request on the target device /// </summary> /// <param name="log_options">Options on how to display the output</param> /// <param name="ip">IP address of target</param> /// <param name="in_community">Write-community name</param> /// <param name="oid">OID to set</param> /// <param name="new_value">Value (int or string)</param> /// <returns></returns> public static SnmpV2Packet Set(LOG_OPTIONS log_options, IPAddress ip, string in_community, string oid, object new_value) { // Prepare target UdpTarget target = new UdpTarget(ip); // Create a SET PDU Pdu pdu = new Pdu(PduType.Set); // Set sysLocation.0 to a new string if (new_value.GetType() == typeof(string)) { pdu.VbList.Add(new Oid(oid), new OctetString(new_value.ToString())); } else if (new_value.GetType() == typeof(int)) { // Set a value to integer pdu.VbList.Add(new Oid(oid), new Integer32(new_value.ToString())); } else { Logger.Write(log_options, module, "Invalid data type: " + new_value.GetType()); return null; //Invalid type } // Set Agent security parameters AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString(in_community)); // Response packet SnmpV2Packet response; try { // Send request and wait for response response = target.Request(pdu, aparam) as SnmpV2Packet; } catch (Exception ex) { // If exception happens, it will be returned here Logger.Write(log_options, module, "Request failed with exception: " + ex.Message); target.Close(); return null; } // Make sure we received a response if (response == null) { Logger.Write(log_options, module, "Error in sending SNMP request."); } else { // Check if we received an SNMP error from the agent if (response.Pdu.ErrorStatus != 0) { string message = String.Format("SNMP agent returned ErrorStatus {0} on index {1}", response.Pdu.ErrorStatus, response.Pdu.ErrorIndex); Logger.Write(log_options, module, message); } else { // Everything is ok. Agent will return the new value for the OID we changed string message = String.Format("Agent response {0}: {1}", response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString()); Logger.Write(log_options, module, message); } } return response; }
/**************************************************** * PING FLOOD * DESCRIPTION: Sends a series of pings to the target IP ****************************************************/ private void PingFlood(string[] args) { bool silent = false; bool log = false; IPAddress address = null; int pings = 1; int timeout = 2000; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-ip")) { address = GetIPParam(args, i); } else if (args[i].Equals("-timeout")) { timeout = GetIntParam(args, i); } else if (args[i].Equals("-pings")) { pings = GetIntParam(args, i); } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****pingflood Command****"); Logger.Write(log_options, module, "USAGE: pingflood -ip [TARGET_TO_PING] -pings [PINGS_TO_SEND](dft=1)"); Logger.Write(log_options, module, " -timeout [TIMEOUT_MS](dft=2000) -silent(OPTION) -log(OPTION)"); Logger.Write(log_options, module, "EXAMPLE: pingflood -ip 192.168.1.5 -pings 5000 -timeout 3000"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } if (address != null) { int failed = Web.ping_flood(address, pings, timeout); Logger.Write(log_options, module, "Pings Sent: " + pings + " pings returned: " + (pings-failed).ToString()); } }
/**************************************************** * HTTP POST * DESCRIPTION: Command line interface to perform an http post ****************************************************/ private void monitor_port(string[] args) { //int monitorNumber = 0; int baud_rate = 0; string comPort = null; bool log = false; bool silent = false; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-comport")) { comPort = GetStringParam(args, i); } else if (args[i].Equals("-baudrate")) { baud_rate = GetIntParam(args, i); } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****monitorport Command****"); Logger.Write(log_options, module, "USAGE: monitorport -monitornumber [PORT_MONITOR(1 | 2)] -comport [COM_PORT]"); Logger.Write(log_options, module, " -baudrate [COM_BAUD_RATE] -log(OPTION)"); Logger.Write(log_options, module, ""); Logger.Write(log_options, module, "EXAMPLE: monitorport -monitornumber 1 -comport COM3 -baudrate 9600"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } if (comPort != null && baud_rate > 0) { Program.portMonitor.Start(log_options, comPort, baud_rate); Console.ReadLine(); //Not sure what the COM monitor will do if the program exits } else { Logger.Write(log_options, module, "ERROR: Missing parameters monitor com_port command"); } }
/**************************************************** * HTTP POST * DESCRIPTION: Command line interface to perform an http post ****************************************************/ private void httpPost(string[] args) { string url = null; string postString = null; bool showResponse = false; bool silent = false; bool log = false; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-url")) { url = GetStringParam(args, i); } else if (args[i].Equals("-data")) { postString = GetStringParam(args, i); } else if (args[i].Equals("-showresponse")) { showResponse = true; } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****httppost Command****"); Logger.Write(log_options, module, "USAGE: httppost -url [TARGET_POST_URL] -data [POST_STRING]"); Logger.Write(log_options, module, " -showresponse(Optional) -log(OPTION) -silent(OPTION)"); Logger.Write(log_options, module, ""); Logger.Write(log_options, module, "EXAMPLE: httppost -url www.google.com -data JTool*Search"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } if (url != null && postString != null) { bool failed = false; string output; try { output = "HTTPPost Success: " + Web.http_post(url, postString); } catch (Exception ex) { failed = true; output = "Post failed: " + ex.ToString(); } if (showResponse == true) { Logger.Write(log_options, module, output); } else { if (failed) { Logger.Write(log_options, module, output); } } } else { Logger.Write(log_options, module, "ERROR: Missing parameters httppost command"); } }
/**************************************************** * HTTP GET * DESCRIPTION: Command line interface to perform an http get operation ****************************************************/ private void httpGet(string[] args) { string url = null; bool silent = false; bool log = false; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-url")) { url = GetStringParam(args, i); } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****httpget Command****"); Logger.Write(log_options, module, "USAGE: httpget -url [TARGET_POST_URL] -log(OPTION) -silent(OPTION)"); Logger.Write(log_options, module, ""); Logger.Write(log_options, module, "EXAMPLE: httpget -url www.google.com"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } if (url != null) { string data; GENERAL_RESULT result = GENERAL_RESULT.FAILED; try { result = Web.http_get(url, out data); if (result == GENERAL_RESULT.SUCCEEDED) { Logger.Write(log_options, module, "Get data success: " + data); } else { Logger.Write(log_options, module, "Get data failed"); } } catch (Exception ex) { Logger.Write(log_options, module, "Get data exception: " + ex.ToString()); } } else { Logger.Write(log_options, module, "ERROR: Missing parameters httpget command"); } }
/**************************************************** * GET NTP CMD * DESCRIPTION: Get the NTP time from the input server * (or the default server if no param is entered). ****************************************************/ private void GetNtpCmd(string[] args) { string ntpServer = "pool.ntp.org"; bool silent = false; bool log = false; for (int i = 0; i < args.Length; i++ ) { if (args[i].Equals("-server")) { ntpServer = GetStringParam(args, i); } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****getntp Command****"); Logger.Write(log_options, module, "USAGE: getntp -server [TARGET_NTP_SERVER](Optional)"); Logger.Write(log_options, module, " -silent(OPTION) -log(OPTION)"); Logger.Write(log_options, module, "EXAMPLE: getntp -server pool.ntp.org"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } Logger.Write(log_options, module, "NTP Time: " + Web.GetNtp(ntpServer).ToString()); }
/**************************************************** * CHECK FOLDERS * DESCRIPTION: Runs the folder checker on the input directory tree. ****************************************************/ private void CheckFolders(string[] args) { bool silent = false; bool log = false; string path = null; bool findEmptyFolders = false; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-path")) { path = GetStringParam(args, i); } else if (args[i].Equals("-findemptyfolders")) { findEmptyFolders = true; } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****checkfolders Command****"); Logger.Write(log_options, module, "USAGE: checkfolders -path [PATH_OF_DIR_TO_CHECK] -findemptyfolders(OPTION)"); Logger.Write(log_options, module, " -silent(OPTION) -log(OPTION)"); Logger.Write(log_options, module, "EXAMPLE: snmpmibwalk -ip 192.168.1.2 -oid 1.3"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } if (path != null) { FolderTools.CheckForBadFiles(path, findEmptyFolders); } else { Logger.Write(log_options, module, "Invalid path, please see usage"); } }
/************************************************************** * RANDOMIZE LIST * DESCRIPTION: Takes the input list and puts the items in a random order **************************************************************/ private static List<string> RandomizeList(LOG_OPTIONS logger_options, List<string> input_list) { Random random = new Random(); List<string> random_list = new List<string>(); List<string> input_copy = new List<string>(input_list); foreach (string item in input_list) { string remove_item; input_copy = RemoveRandomItem(logger_options, input_copy, null, out remove_item, 0, 5); random_list.Add(remove_item); Thread.Sleep(random.Next(20)); //Sleep for a random period of time } return random_list; }
/**************************************************** * REMOVE RANDOM ITEM * DESCRIPTION: Gets a random item from the input list * and removes it. If that item is in the "Unmatchable" list then the function retries in 200ms ****************************************************/ private static List<string> RemoveRandomItem(LOG_OPTIONS logger_options, List<string> input_list, List<string>unmatchables, out string item, int retries, int max_retries) { Random random = new Random(); int random_index = random.Next(input_list.Count); string couple_str = input_list[random_index]; if (unmatchables == null) //We are just searching for items to re-arrange the list (we don't need to split) { item = couple_str; } else { string[] couple = couple_str.Split(','); item = couple[0]; } if (isUnmatchable(item, unmatchables)) //We accidentally chose a match we were not supposed to, retry { Thread.Sleep(random.Next(200)); retries++; if (retries < max_retries) { Logger.Write(logger_options, module, "WARNING: Attempted to match person with himself, retrying: " + retries.ToString()); input_list = RemoveRandomItem(logger_options, input_list, unmatchables, out item, retries, max_retries); } else { Logger.Write(logger_options, module, "Failed to generate random match for: " + unmatchables[0]); return input_list; } } else { input_list.RemoveAt(random_index); } return input_list; }
/**************************************************** * RANDOM MATCH CSV * DESCRIPTION: Matches family members randomly ****************************************************/ private void RandomMatchCSV(string[] args) { bool silent = false; bool log = false; int num_retries = 10; int num_bowl_mixes = 5; string family_csv = null; string output_csv = null; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-familycsv")) { family_csv = GetStringParam(args, i); } else if (args[i].Equals("-outputcsv")) { output_csv = GetStringParam(args, i); } else if (args[i].Equals("-bowlmixes")) { num_bowl_mixes = GetIntParam(args, i); } else if (args[i].Equals("-numretries")) { num_retries = GetIntParam(args, i); } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****randmatchcsv Command****"); Logger.Write(log_options, module, "USAGE: randmatchcsv -familycsv [CSV_FILEPATH_INPUT] -outputcsv [CSV_FILEPATH_OUTPUT"); Logger.Write(log_options, module, " -bowlmixes [NUM_RANDOMIZATIONS](dft=5) -numretries [MAX_RETRIES_PER_MATCH](dft=10)"); Logger.Write(log_options, module, " -silent(OPTION) -log(OPTION)"); Logger.Write(log_options, module, "EXAMPLE: randmatchcsv -familycsv C:\\User\\Me\\Docs\\myfamily.csv -outputcsv C:\\User\\Me\\Desktop\\outputmatch.csv"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } if (family_csv != null && output_csv != null) { RandomMatcher.GenerateRandomMatchCSV(log_options, family_csv, output_csv, num_bowl_mixes, num_retries); } else { Logger.Write(log_options, module, "Invalid Paramaters; please see usage"); } }
/// <summary> /// Write a message to the log and console /// </summary> /// <param name="options">Options on how to show this output</param> /// <param name="module">Module that the output is coming from</param> /// <param name="input">Message</param> public static void Write(LOG_OPTIONS options, string module, string input) { Write(options, module, input, null, 0); }
/**************************************************** * SENDEMAIL * DESCRIPTION: Sends out an email via the command line ****************************************************/ private void SendEmail(string[] args) { bool silent = false; bool log = false; string userName = null; string userPassword = null; string to = null; string from = null; string subject = null; string message = null; List<string> attachments = new List<string>(); for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-username")) { userName = GetStringParam(args, i); } else if (args[i].Equals("-password")) { userPassword = GetStringParam(args, i); } else if (args[i].Equals("-to")) { to = GetStringParam(args, i); } else if (args[i].Equals("-from")) { from = GetStringParam(args, i); } else if (args[i].Equals("-subject")) { subject = GetStringParam(args, i); } else if (args[i].Equals("-message")) { message = GetStringParam(args, i); } else if (args[i].Equals("-attach")) { attachments.Add(GetStringParam(args, i)); } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****sendemail Command****"); Logger.Write(log_options, module, "USAGE: sendemail -username [USERNAME_OF_EMAILACCOUNT] -password [PASSWORD_OF_EMAIL_ACCOUNT]"); Logger.Write(log_options, module, " -to [EMAIL_SENT_TO] -from [EMAIL_SENT_FROM]"); Logger.Write(log_options, module, " -subject [SUBJECT_OF_EMAIL] -message [MESSAGE_OF_EMAIL]"); Logger.Write(log_options, module, " -attach [FILE_PATH_TO_ATTACHMENT](Multiple-Allowed)"); Logger.Write(log_options, module, " -silent(OPTION) -log(OPTION)"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } if (userName != null && userPassword != null && to != null && from != null && message != null && subject != null) { Web.SendMail(userName, userPassword, to, from, subject, message, attachments); } else { Logger.Write(log_options, module, "Missing paramaters"); } }
/// <summary> /// Walks an SNMP mib table displaying the results on the fly (unless otherwise desired) /// </summary> /// <param name="log_options">Logging options</param> /// <param name="ip">IPAddress of device to walk</param> /// <param name="in_community">Read-community of device to walk</param> /// <param name="start_oid">Start OID (1.3, etc)</param> /// <returns></returns> public static List<SnmpV1Packet> MibWalk(LOG_OPTIONS log_options, IPAddress ip, string in_community, string start_oid) { stop = false; List<SnmpV1Packet> packets = new List<SnmpV1Packet>(); // SNMP community name OctetString community = new OctetString(in_community); // Define agent parameters class AgentParameters param = new AgentParameters(community); // Set SNMP version to 1 param.Version = SnmpVersion.Ver1; // Construct target UdpTarget target = new UdpTarget(ip, 161, 2000, 1); // Define Oid that is the root of the MIB // tree you wish to retrieve Oid rootOid = new Oid(start_oid); // ifDescr // This Oid represents last Oid returned by // the SNMP agent Oid lastOid = (Oid)rootOid.Clone(); // Pdu class used for all requests Pdu pdu = new Pdu(PduType.GetNext); // Loop through results while (lastOid != null) { // When Pdu class is first constructed, RequestId is set to a random value // that needs to be incremented on subsequent requests made using the // same instance of the Pdu class. if (pdu.RequestId != 0) { pdu.RequestId += 1; } if (stop) { return packets; } // Clear Oids from the Pdu class. pdu.VbList.Clear(); // Initialize request PDU with the last retrieved Oid pdu.VbList.Add(lastOid); // Make SNMP request SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); // You should catch exceptions in the Request if using in real application. // If result is null then agent didn't reply or we couldn't parse the reply. if (result != null) { // ErrorStatus other then 0 is an error returned by // the Agent - see SnmpConstants for error definitions packets.Add(result); if (result.Pdu.ErrorStatus != 0) { // agent reported an error with the request Logger.Write(log_options, module, "Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex); lastOid = null; break; } else { // Walk through returned variable bindings foreach (Vb v in result.Pdu.VbList) { // Check that retrieved Oid is "child" of the root OID if (rootOid.IsRootOf(v.Oid)) { Logger.Write(log_options, module, v.Oid.ToString() + " " + SnmpConstants.GetTypeName(v.Value.Type) + ": " + v.Value.ToString()); lastOid = v.Oid; } else { // we have reached the end of the requested // MIB tree. Set lastOid to null and exit loop lastOid = null; } } } } else { Console.WriteLine("No response received from SNMP agent."); } } target.Close(); return packets; }
/// <summary> /// Spell checks every askii file in the input directory /// </summary> /// <param name="log_options">Options on how to display the output</param> /// <param name="directory">Directory tree to be checked</param> /// <param name="dictionary_location">Path to ASKII dictionary file</param> /// <param name="excludedFiles">ASKII files to be ignored</param> /// <param name="excludeDirectories">Directories to be ignored</param> /// <returns>Number of spelling errors found</returns> public static List<string> SpellCheckDirectory(LOG_OPTIONS log_options, string directory, string dictionary_location, List<string> excludedFiles, List<string> excludeDirectories) { List<string> error_list = new List<string>(); if (LoadDictionary(log_options, dictionary_location) == GENERAL_RESULT.FAILED) { return error_list; } List<string> file_list = new List<string>(); GetAllFiles(directory, excludedFiles, excludeDirectories, file_list, out file_list); Logger.Write(log_options, module, "Spell Checking directory: " + directory); foreach (string file in file_list) { List<string> file_output = SpellCheckFile(log_options, file, dictionary_location); error_list.AddRange(file_output); error_list.Add(""); Logger.Write(log_options, module, ""); } return error_list; }
/**************************************************** * SNMP GET REQUEST * DESCRIPTION: Performs an SNMP get with the input params. ****************************************************/ private void SNMPGet(string[] args) { bool silent = false; bool log = false; bool get_next = false; int max_repeaters = 0; IPAddress ip = null; string community = "public"; string start_oid = "1.3"; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-ip")) { ip = GetIPParam(args, i); } else if (args[i].Equals("-community")) { community = GetStringParam(args, i); } else if (args[i].Equals("-oid")) { start_oid = GetStringParam(args, i); } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-getnext")) { get_next = true; } else if (args[i].Equals("-maxrepeaters")) { max_repeaters = GetIntParam(args, i); } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****snmpget Command****"); Logger.Write(log_options, module, "USAGE: snmpget -ip [IP_ADDRESS_OF_TARGET] -community [READ_COMMUNITY](dft='public'"); Logger.Write(log_options, module, " -oid [START_OID_OF_WALK](dft='1.3') -getbulk(OPTION)"); Logger.Write(log_options, module, " -silent(OPTION) -log(OPTION) -getnext(OPTION)"); Logger.Write(log_options, module, "EXAMPLE: snmpmibwalk -ip 192.168.1.2 -oid 1.3"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } if (ip != null) { if (max_repeaters > 0) { SnmpV2Packet packet = SNMP_Tools.GetBulk(log_options, ip, community, start_oid, max_repeaters); foreach (Vb binding in packet.Pdu.VbList) { Logger.Write(log_options, module, "OID: " + binding.Oid.ToString() + " Value: " + binding.Value.ToString()); } } else { SnmpV1Packet packet = SNMP_Tools.Get(log_options, ip, community, start_oid, get_next); foreach (Vb binding in packet.Pdu.VbList) { Logger.Write(log_options, module, "OID: " + binding.Oid.ToString() + " Value: " + binding.Value.ToString()); } } } else { Logger.Write(log_options, module, "Invalid IP address, please see usage"); } }
/// <summary> /// Write a message to the log and console /// </summary> /// <param name="options">Options on how to show this output</param> /// <param name="module">Module that the output is coming from</param> /// <param name="input">Message</param> /// <param name="watch">Stopwatch for timed operations</param> public static void Write(LOG_OPTIONS options, string module, string input, Stopwatch watch) { Write(options, module, input, watch, 0); }
public LOG_INFO(string message, LOG_OPTIONS options) { SetMessage(message); LogOptions = options; }
/**************************************************** * SNMP MIB WALK * DESCRIPTION: Performs an SNMP mib walk with the input * params. ****************************************************/ private void SNMPMibWalk(string[] args) { bool silent = false; bool log = false; IPAddress ip = null; string community = "public"; string start_oid = "1.3"; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-ip")) { ip = GetIPParam(args, i); } else if (args[i].Equals("-community")) { community = GetStringParam(args, i); } else if (args[i].Equals("-oid")) { start_oid = GetStringParam(args, i); } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****snmpmibwalk Command****"); Logger.Write(log_options, module, "USAGE: snmpmibwalk -ip [IP_ADDRESS_OF_TARGET] -community [READ_COMMUNITY](dft='public'"); Logger.Write(log_options, module, " -oid [START_OID_OF_WALK](dft='1.3')"); Logger.Write(log_options, module, " -silent(OPTION) -log(OPTION)"); Logger.Write(log_options, module, "EXAMPLE: snmpmibwalk -ip 192.168.1.2 -oid 1.3"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } if (ip != null) { SNMP_Tools.MibWalk(log_options, ip, community, start_oid); } else { Logger.Write(log_options, module, "Invalid IP address, please see usage"); } }
/// <summary> /// Spell checks the input ASKII file. /// </summary> /// <param name="log_options">Options on how to display the output</param> /// <param name="file">Path to file to be checked</param> /// <param name="dictionary_location">Path to ASKII dictionary file</param> /// <returns></returns> public static List<string> SpellCheckFile(LOG_OPTIONS log_options, string file, string dictionary_location) { int numberOfErrors = 0; int totalWords = 0; List<string> errors = new List<string>(); if (LoadDictionary(log_options, dictionary_location) == GENERAL_RESULT.FAILED) { return errors; } errors.Add("Spell Checking file: " + file); Logger.Write(log_options, module, "Spell Checking file: " + file); try { if (!File.Exists(file)) { Logger.Write(log_options, module, "ERROR: SpellCheck: Unable to find file: " + file); errors.Add("ERROR: Unable to find file: " + file); return errors; } int lineNumber = 1; string[] textLines = File.ReadAllLines(file); foreach (string line in textLines) { int wordNumber = 0; string readText = RemoveSpecialCharacters(line); readText = RemoveNumbers(readText); readText = readText.Replace(".", " "); readText = readText.ToLower(); string[] words = readText.Split(' '); foreach (string word in words) { if (!word.Equals("") && !dictionary.ContainsKey(word)) { Logger.Write(log_options, module, "Spelling Error: Line#: " + lineNumber.ToString() + " Word#: " + wordNumber.ToString() + " Word: " + word); errors.Add("Spelling Error: Line#: " + lineNumber.ToString() + " Word#: " + wordNumber.ToString() + " Word: " + word); numberOfErrors++; } else if (!word.Equals("")) { totalWords++; wordNumber++; } } lineNumber++; } errors.Add("FILE: " + file + " CHECKED: Words Checked: " + totalWords.ToString() + " Spelling Errors: " + numberOfErrors.ToString()); Logger.Write(log_options, module, "SPELL CHECK FINISHED: Words Checked: " + totalWords.ToString() + " Spelling Errors: " + numberOfErrors.ToString()); } catch (Exception e) { Logger.Write(log_options, module, "EXCEPTION: SpellCheckFile: " + e.Message); errors.Add("EXCEPTION: Unable to spell check file: " + file + " " + e.Message); } return errors; }
/**************************************************** * SNMP SET REQUEST * DESCRIPTION: Performs an SNMP set with the input params. ****************************************************/ private void SNMPSet(string[] args) { bool silent = false; bool log = false; IPAddress ip = null; string community = "public"; string start_oid = "1.3"; int int_param = 0; bool int_set = false; string string_param = null; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-ip")) { ip = GetIPParam(args, i); } else if (args[i].Equals("-community")) { community = GetStringParam(args, i); } else if (args[i].Equals("-oid")) { start_oid = GetStringParam(args, i); } else if (args[i].Equals("-intparam")) { int_param = GetIntParam(args, i); int_set = true; } else if (args[i].Equals("-strparam")) { string_param = GetStringParam(args, i); } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****snmpset Command****"); Logger.Write(log_options, module, "USAGE: snmpset -ip [IP_ADDRESS_OF_TARGET] -community [READ_COMMUNITY](dft='public'"); Logger.Write(log_options, module, " -oid [START_OID_OF_WALK](dft='1.3') -intparam [INTEGER_TO_SET] -strparam [INT_TO_SET]"); Logger.Write(log_options, module, " -silent(OPTION) -log(OPTION)"); Logger.Write(log_options, module, "EXAMPLE: snmpmibwalk -ip 192.168.1.2 -oid 1.3"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } if (ip != null) { if (string_param == null && int_set) { SNMP_Tools.Set(log_options, ip, community, start_oid, int_param); } else if (string_param != null) { SNMP_Tools.Set(log_options, ip, community, start_oid, string_param); } else { Logger.Write(log_options, module, "ERROR: No params for SNMP set request"); } } else { Logger.Write(log_options, module, "Invalid IP address, please see usage"); } }
/// <summary> /// Counts the number of words in the file specified, outputs the results to a sorted dictionary /// </summary> /// <param name="file">Path to ASKII file</param> /// <returns></returns> public static SortedDictionary<string, int> CountWords(LOG_OPTIONS log_options, string file) { SortedDictionary<string, int> output = new SortedDictionary<string, int>(); try { string tempLine; string[] data = File.ReadAllLines(file); foreach (string line in data) { tempLine = line.ToLower(); //Count the punctuations in this line foreach (char punc in punctuation) { int count = tempLine.Split(punc).Length - 1; if (count > 0) { if (!output.ContainsKey(punc.ToString())) { output[punc.ToString()] = count; } else { output[punc.ToString()] += count; } } tempLine = tempLine.Replace(punc.ToString(), " "); } tempLine = RemoveSpecialCharacters(tempLine); tempLine = RemoveNumbers(tempLine); //Count the words in this line string[] words = tempLine.Split(' '); foreach (string word in words) { if (!output.ContainsKey(word)) { output[word] = 1; } else { output[word]++; } } } var sortedDictionary = from entry in output orderby entry.Value ascending select entry; int index = 0; int lineNumber = 0; foreach (KeyValuePair<string, int> pair in sortedDictionary) { Logger.Write(log_options, module, "Line: " + lineNumber.ToString() + " Word " + index.ToString() + " '" + pair.Key + "': " + pair.Value.ToString()); index++; } } catch (Exception e) { Logger.Write(log_options, module, "EXCEPTION: CountWords: " + e.Message); } return output; }
/**************************************************** * WORD COUNT * DESCRIPTION: Counts the number of words in the given * file. ****************************************************/ private void spellCheck(string[] args) { string wordFile = null; string dictionary = null; string directory = null; List<string> excludeFiles = new List<string>(); List<string> excludeDirectories = new List<string>(); bool log = false; bool silent = false; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-file")) { wordFile = GetStringParam(args, i); } else if (args[i].Equals("-directory")) { directory = GetStringParam(args, i); } else if (args[i].Equals("-excludefile")) { excludeFiles.Add(GetStringParam(args, i)); } else if (args[i].Equals("-excludedir")) { excludeDirectories.Add(GetStringParam(args, i)); } else if (args[i].Equals("-dictionary")) { dictionary = GetStringParam(args, i); } else if (args[i].Equals("-log")) { log_options = LOG_OPTIONS.CONSOLE_AND_LOG; log = true; } else if (args[i].Equals("-silent")) { log_options = LOG_OPTIONS.NONE; silent = true; } else if (args[i].Equals("/?")) { Logger.Write(log_options, module, "****Spellcheck Command****"); Logger.Write(log_options, module, "USAGE: spellcheck -file [ASKII_FILE_PATH] -dictionary [TARGET_DICTIONARY]"); Logger.Write(log_options, module, " -directory [DIRECTORY_TO_CHECK] -excludefile [FILE_TO_EXCLUDE](multiple|optional)"); Logger.Write(log_options, module, " -excludedir [DIRECTORY_TO_EXCLUDE](multiple|optional) -log (OPTION) -silent (OPTION)"); Logger.Write(log_options, module, ""); Logger.Write(log_options, module, "EXAMPLE: spellcheck -file C:\\TI\\log.txt -dictionary C:\\Storage\\myDictionary.dic"); } } if (silent && log) //Logging and silent is just logging { log_options = LOG_OPTIONS.LOG_ONLY; } //No dictionary was set so use the default one. if (dictionary == null) { dictionary = Environment.CurrentDirectory + "\\Dictionary.dic"; } List<string> errors; //We want to spellcheck a file and a directory if (wordFile != null && directory != null) { errors = WordTools.SpellCheckFile(log_options, wordFile, dictionary); errors.AddRange(WordTools.SpellCheckDirectory(log_options, directory, dictionary, excludeFiles, excludeDirectories)); } else if (wordFile != null) { errors = WordTools.SpellCheckFile(log_options, wordFile, dictionary); } else if (directory != null) { errors = WordTools.SpellCheckDirectory(log_options, directory, dictionary, excludeFiles, excludeDirectories); } else { Logger.Write(log_options, module, "ERROR: Missing parameters wordcount command"); } }