public DataTable InsertItemDetails(FeedRetailPL objFeedRetPL)
{
DataTable GetListID = new DataTable();
try
{
SqlParameter[] arParams = new SqlParameter[4];
arParams[0] = new SqlParameter("#Date", typeof(DateTime));
arParams[0].Value = objFeedRetPL.requestdate;
}
catch (Exception ex)
{
string dir = #"C:\Error.txt"; // folder location
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
File.AppendAllText(Server.MapPath("~/Error.txt"), "Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
string New = Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine;
File.AppendAllText(Server.MapPath("~/Error.txt"), New);
}
}
}
Here, I want to save an Exception in "C:\" ..I am trying In DAL... How to save the Exception In
C drive Error.txt
Since you want to save the exception to C:\Error.txt, you don't need Directory.Exists, Directory.CreateDirectory, or Server.MapPath("~/Error.txt"). You can simply use StreamWriter like this:
string filePath = #"C:\Error.txt";
Exception ex = ...
using( StreamWriter writer = new StreamWriter( filePath, true ) )
{
writer.WriteLine( "-----------------------------------------------------------------------------" );
writer.WriteLine( "Date : " + DateTime.Now.ToString() );
writer.WriteLine();
while( ex != null )
{
writer.WriteLine( ex.GetType().FullName );
writer.WriteLine( "Message : " + ex.Message );
writer.WriteLine( "StackTrace : " + ex.StackTrace );
ex = ex.InnerException;
}
}
The above code will create C:\Error.txt if it doesn't exist, or append C:\Error.txt if it already exists.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ErrorLoggingSample
{
class Program
{
static void Main(string[] args)
{
try
{
string str = string.Empty;
if (string.IsNullOrEmpty(str))
{
throw new Exception("Wrong Data");
}
}
catch (Exception ex)
{
ErrorLogging(ex);
ReadError();
}
}
public static void ErrorLogging(Exception ex)
{
string strPath = #"D:\Rekha\Log.txt";
if (!File.Exists(strPath))
{
File.Create(strPath).Dispose();
}
using (StreamWriter sw = File.AppendText(strPath))
{
sw.WriteLine("=============Error Logging ===========");
sw.WriteLine("===========Start============= " + DateTime.Now);
sw.WriteLine("Error Message: " + ex.Message);
sw.WriteLine("Stack Trace: " + ex.StackTrace);
sw.WriteLine("===========End============= " + DateTime.Now);
}
}
public static void ReadError()
{
string strPath = #"D:\Rekha\Log.txt";
using (StreamReader sr = new StreamReader(strPath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
}
I use that one
catch (Exception e)
{
new MessageWriteToFile(e).WriteToFile();
}
public class MessageWriteToFile
{
private const string Directory = "C:\\AppLogs";
public string Message { get; set; }
public Exception Exception { get; set; }
public string DefaultPath
{
get
{
var appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var folder = $"{Directory}\\{appName}";
if (!System.IO.Directory.Exists(folder))
{
System.IO.Directory.CreateDirectory(folder);
}
var fileName = $"{DateTime.Today:yyyy-MM-dd}.txt";
return $"{Directory}\\{appName}\\{fileName}";
}
}
public MessageWriteToFile(string message)
{
Message = message;
}
public MessageWriteToFile(Exception ex)
{
Exception = ex;
}
public bool WriteToFile(string path = "")
{
if (string.IsNullOrEmpty(path))
{
path = DefaultPath;
}
try
{
using (var writer = new StreamWriter(path, true))
{
writer.WriteLine("-----------------------------------------------------------------------------");
writer.WriteLine("Date : " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
writer.WriteLine();
if (Exception != null)
{
writer.WriteLine(Exception.GetType().FullName);
writer.WriteLine("Source : " + Exception.Source);
writer.WriteLine("Message : " + Exception.Message);
writer.WriteLine("StackTrace : " + Exception.StackTrace);
writer.WriteLine("InnerException : " + Exception.InnerException?.Message);
}
if (!string.IsNullOrEmpty(Message))
{
writer.WriteLine(Message);
}
writer.Close();
}
}
catch (Exception)
{
return false;
}
return true;
}
}
Try This
try
{
int i = int.Parse("Prashant");
}
catch (Exception ex)
{
this.LogError(ex);
}
private void LogError(Exception ex)
{
string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
message += string.Format("Message: {0}", ex.Message);
message += Environment.NewLine;
message += string.Format("StackTrace: {0}", ex.StackTrace);
message += Environment.NewLine;
message += string.Format("Source: {0}", ex.Source);
message += Environment.NewLine;
message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
string path = Server.MapPath("~/ErrorLog/ErrorLog.txt");
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(message);
writer.Close();
}
}
string[] path1 = Directory.GetFiles(#"E:\storage", "*.txt");//it get the all textfiles from the folder
for (var i = 0; i < path1.Length; i++)
{
var file = Directory.GetDirectories(networkPath);
var path = file;
string temp_FilePath = "E:\\temp.txt";
string temp_FilePath1 = #"E:\ExceptionFiles\Cs_regular\\Cs_regular.txt";
string temp_FilePath2 = #"E:\ExceptionFiles\CC_eBilling\\CC_eBilling.txt";
string folder = #"E:\ExceptionFiles\Cs_regular";
string folder1 = #"E:\ExceptionFiles\CC_eBilling";
string[] lines;
var list = new List<string>();
var list1 = new List<string>();
var list2 = new List<string>();
var error = false;
var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
var fileStream1 = new FileStream(path, FileMode.Open, FileAccess.Read);
var fileStream2 = new FileStream(path, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
var res = line.Substring(20, 16);
//var timenow = DateTime.Now.ToString("yyyy /MM/dd HH:mm");
var timenow1 = "2020/10/31 10:11";
if (res == timenow1)
{
string linesRemoved = "ERROR";
if (!line.Contains(linesRemoved))
{
if (error == true)
{
if (line.Contains("at"))
{
list1.Add(line);
error = true;
}
else
{
error = false;
}
}
}
else
{
error = false;
}
if (line.Contains("Exception1") && error == false)
{
list1.Add(line);
error = true;
}
}
}
}
using (var streamReader2 = new StreamReader(fileStream2, Encoding.UTF8))
{
string line;
while ((line = streamReader2.ReadLine()) != null)
{
string linesRemoved = "ERROR";
var res = line.Substring(20, 16);
//var timenow = DateTime.Now.ToString("yyyy/MM/dd HH:mm");
var timenow1 = "2020/10/29 12:38";
if (res == timenow1)
{
if (!line.Contains(linesRemoved))
{
if (error == true)
{
if (line.Contains("at"))
{
list2.Add(line);
error = true;
}
else
{
error = false;
}
}
}
else
{
error = false;
}
if ((line.Contains("Exception2") && line.Contains("Exception:")) && error == false)
{
list2.Add(line);
error = true;
}
}
}
}
if ((System.IO.File.Exists(temp_FilePath1) || System.IO.File.Exists(temp_FilePath2)))
{
int fileCount = Directory.GetFiles(folder).Length;
int fileCount1 = Directory.GetFiles(folder1).Length;
fileCount++;
fileCount1++;
temp_FilePath1 = temp_FilePath1 + "(" + fileCount.ToString() + ").txt";
temp_FilePath2 = temp_FilePath2 + "(" + fileCount1.ToString() + ").txt";
}
{
System.IO.File.WriteAllLines(temp_FilePath1, list1);
System.IO.File.WriteAllLines(temp_FilePath2, list2);
}
System.IO.File.WriteAllLines(temp_FilePath, list);
System.IO.File.WriteAllLines(temp_FilePath1, list1);
System.IO.File.WriteAllLines(temp_FilePath2, list2);
}
}
}
catch (Exception ex)
{
}
return null;
Related
I'm stuck in a doubt, any way I put it to block some files, example attached .exe it continues to allow.
The code is like this now
private void AnexaArquivo(string pCodigo)
{
clBRLAnexo brlAnexo = new clBRLAnexo();
clDTOAnexo dtoAnexo = new clDTOAnexo();
string anexo;
try
{
foreach (HttpPostedFile postedFile in uplAnexo.PostedFiles)
{
if (postedFile.ContentLength > 0)
{
if (ValidaExtensao(postedFile.FileName))
{
string complemento = Guid.NewGuid().ToString().Substring(0, 4) + "_" + pCodigo;
anexo = complemento + Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(Server.MapPath(caminho) + complemento + Path.GetExtension(postedFile.FileName));
dtoAnexo.NomeAnexo = anexo;
dtoAnexo.RlTbAuditoria = Convert.ToInt32(pCodigo);
brlAnexo.InsereAnexo(dtoAnexo);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
anexo = null;
}
}
private bool ValidaExtensao(string sFileName)
{
bool bValido = true;
string fileExtension = System.IO.Path.GetExtension(sFileName).ToLower();
foreach (string ext in new string[] { ".exe", ".msi" })
{
if (fileExtension == ext)
bValido = false;
}
return bValido;
}
if you can help i will be very grateful
if you can help i will be very grateful
if you can help i will be very grateful
I have a custom add-in which gets the body on clicking a button when it got installed. so I am getting this error on a customer machine. code is working fine on my side and for other customers but one customer is facing this problem.
this is my code
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = olApp.GetNamespace("MAPI");
Explorer olExp = olApp.ActiveExplorer();
Selection olSel = olExp.Selection;
string msg = "";
int iterate = 1;
MAPIFolder inbox = null;
if (olSel.Count > 1)
{
MessageBox.Show("Sorry! You can't report more then 1 email at a time", "Report Email");
return;
}
foreach (_MailItem mail in olSel)
{
inbox = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
mail.GetInspector.Display(false);
Thread.Sleep(2100);
string screenShot = getScreenShot(mail);
mail.GetInspector.Close(OlInspectorClose.olDiscard);
String msgToShow = "Are you sure you want to report this email as suspicious?";
if (mail != null && mail.Subject != null)
msgToShow += "\n\nSubject : " + mail.Subject.ToString();
DialogResult dr = MessageBox.Show(msgToShow, "Please Confirm", MessageBoxButtons.YesNo,
MessageBoxIcon.Exclamation);
if (dr == DialogResult.Yes)
{
msg += reportMail(mail, screenShot, e);
}
else {
return;
}
iterate++;
break;
}
if (!msg.Equals(""))
MessageBox.Show(msg, "Report Email");
else
return;
if (!msg.Contains("Success"))
return;
MailItem moveMail = null;
MAPIFolder subfolder = null;
try
{
subfolder = inbox.Folders["Reported Emails"];
}
catch (System.Exception ex) {
subfolder = inbox.Folders.Add("Reported Emails", OlDefaultFolders.olFolderInbox);
}
foreach (MailItem eMail in olSel)
{
try
{
moveMail = eMail;
if (moveMail != null)
{
string titleSubject = (string)moveMail.Subject;
moveMail.Move(subfolder);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private string reportMail(_MailItem mail, string screenShot, RibbonControlEventArgs e)
{
try
{
var m = Globals.ThisAddIn.Application.GetNamespace("MAPI");
var mailitem = mail;
if (mailitem != null)
{
// Console.WriteLine("Email body ::: " + mailitem.HTMLBody);
String reporterEmail = getReporterEmail(mailitem);
String senderEmailAddress = "";
String senderName = "";
AddressEntry mailsender;
if (reporterEmail.Equals(""))
{
MessageBox.Show("Sorry! This email can't be reported because you are not included in Recipients.", "Report Email");
}
else
{
if (mailitem.SenderEmailType == "EX")
{
mailsender = mailitem.Sender;
if (mailsender != null)
{
if (mailsender.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry || mailsender.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
{
ExchangeUser exchUser = mailsender.GetExchangeUser();
if (exchUser != null)
{
senderEmailAddress = exchUser.PrimarySmtpAddress;
senderName = exchUser.Name;
}
}
}
}
else
{
senderEmailAddress = mailitem.SenderEmailAddress;
senderName = mailitem.SenderName;
}
String emailHeader = mailitem.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E");
String emailBody = mailitem.Body.Replace("%"," percent").Replace("#","").Replace("|", "");
//String res = HttpPost(Properties.Settings.Default.address, "ReporterEmail=" + reporterEmail + "&suspectedName=" + senderName + "&FromEmail=" + senderEmailAddress
// + "&ToEmail=" + mailitem.To + "&Subject=" + mailitem.Subject + "&EmailBody=" + emailBody + "&AttachmentName=" + GetAttachments(mailitem)
// + "&reporter=" + reporterEmail + "&emailHeader=" + emailHeader + "&mailImage=" + screenShot);
String htmlBody = mail.HTMLBody;
MessageBox.Show(htmlBody);
Dictionary<string, object> postParameters = new Dictionary<string, object>();
postParameters.Add("ReporterEmail", reporterEmail);
postParameters.Add("suspectedName", senderName);
postParameters.Add("FromEmail", senderEmailAddress);
postParameters.Add("ToEmail", mailitem.To);
postParameters.Add("Subject", mailitem.Subject);
postParameters.Add("EmailBody", emailBody);
List<String> attachmentDetails = GetAttachments(mailitem);
postParameters.Add("AttachmentName", attachmentDetails[0]);
postParameters.Add("reporter", reporterEmail);
postParameters.Add("emailHeader", emailHeader);
postParameters.Add("mailImage", screenShot);
string res = HttpPost(Properties.Settings.Default.serverAddress+ "/PhishRod-portlet/reporter", postParameters, htmlBody,attachmentDetails[1]);
return res + "\n";
}
}
}
catch (System.Exception ex)
{
log.Error(ex);
return "Error: " + ex + "-- - " + ex.StackTrace.ToString() + "\n";
}
return "";
}
In the event handler of your button I see the following lines of code:
Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = olApp.GetNamespace("MAPI");
There is no need to create a new Outlook Application instance in the add-in. Instead, you need to use the Application property which doesn't trigger a security issue when dealing with OOM from external applications:
var app = Globals.ThisAddIn.Application
I have an issue in LDAP with Asp.net IIS application.
I am just reading the user from Active directory, like below,
public class ActiveDirectoryRepository : IActiveDirectoryRepository
{
#region Public methods
List<User> IActiveDirectoryRepository.GetActiveDirectoryUsers(string loginName)
{
List<User> activeDirectoryUsersList = new List<User>();
try
{
string activeDirectory = System.Configuration.ConfigurationManager.AppSettings["EDPUserDomain"];
var searchRoot = new DirectoryEntry(activeDirectory);
var search = new DirectorySearcher(searchRoot);
FormUserSearchFilter(loginName, search);
SearchResultCollection activeDirectoryUsers = search.FindAll();
if (activeDirectoryUsers != null)
{
for (int counter = 0; counter < activeDirectoryUsers.Count; counter++)
{
string userNameEmailString = string.Empty;
SearchResult result = activeDirectoryUsers[counter];
if (result != null && result.Properties.Contains("displayname"))
{
User activeDirectoryUser = new User();
if (result.Properties["givenname"].Count > 0)
{
activeDirectoryUser.FirstName = Convert.ToString(result.Properties["givenname"][0], CultureInfo.InvariantCulture);
}
if (result.Properties["sn"].Count > 0)
{
activeDirectoryUser.LastName = Convert.ToString(result.Properties["sn"][0], CultureInfo.InvariantCulture);
}
if (result.Properties["mail"].Count > 0)
{
activeDirectoryUser.email = Convert.ToString(result.Properties["mail"][0], CultureInfo.InvariantCulture);
}
if (result.Properties["distinguishedname"].Count > 0)
{
string[] domain = Convert.ToString(result.Properties["distinguishedname"][0], CultureInfo.InvariantCulture).Split(',');
if (domain[2] != null)
{
activeDirectoryUser.DomainName = domain[2].Replace("DC=", String.Empty);
}
}
if (result.Properties["samaccountname"].Count > 0)
{
activeDirectoryUser.UserName = Convert.ToString(result.Properties["samaccountname"][0], CultureInfo.InvariantCulture);
}
activeDirectoryUsersList.Add(activeDirectoryUser);
}
}
}
}
catch (Exception ex)
{
string filePath = #"C:\Mails\Error.txt";
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
}
}
return activeDirectoryUsersList;
}
The above code works well in debugging mode, but it throws the below error after deployed the application in IIS 6.1
Message :An operations error occurred.
<br/>
StackTrace : at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindAll()
at PW.EPD.DataAccess.Repository.ActiveDirectoryRepository.PW.EPD.DataAccess.Repository.IActiveDirectoryRepository.GetActiveDirectoryUsers(String loginName)
Date :5/20/2015 11:50:30 PM
-----------------------------------------------------------------------------
Please help me.
Thanks in advance.
How I can't attach to splited string file name from DB row (I need for "mode = 2" and "case 2:").
In my log file error:
FILE TO ATTACH ERR : Could not find file
'C:\inetpub\wwwroot\PLATFORM_700_NTFSRV\PLATFORM_700_NTFSRV_LAB\Attachments\text.txt,text2.txt'.
Here my example code and my row in DB
Row in db:
|FILE_TO_ATTACH |
|text1.txt,text2.txt|
public DataTable GetAttachmentFiles(int mode , string fileIDList)
{
try
{
DataTable DTB = new DataTable();
if (mode == 1)
{
SqlCommand TheCommand = GetCommand("application_MessageAttachFiles", CommandType.StoredProcedure,
GetConnection("APP"));
TheCommand.Parameters.Add("FILEIDLIST", SqlDbType.VarChar, 8000);
TheCommand.Parameters["FILEIDLIST"].Value = fileIDList;
SqlDataAdapter SDA = new SqlDataAdapter();
SDA.SelectCommand = TheCommand;
SDA.Fill(DTB);
}
else if(mode == 2)
{
try
{
DTB.Columns.Add("FILENAME");
string[] fileList = fileIDList.Split(',');
for (int c = 0; c < fileList.Length; c++)
{
DataRow DR = DTB.NewRow();
DR["FILENAME"] = fileList[c];
DTB.Rows.Add(DR);
}
}
catch (Exception ex)
{
RecordLine("ERROR Reading GetAttachmentFiles: " + ex.Message);
}
}
return DTB;
}
catch (Exception eX)
{
RecordLine("ERROR GetAttachmentFiles : " + eX.Message);
return null;
}
}
public Attachment AttachmentFile(int mode, string fileNameString, int fileID, DataRow DRA)
{
// mode.ToString(ConfigurationSettings.AppSettings["MODE"]);
try
{
switch (mode)
{
case 1: /*from Database*/
if (DRA != null)
{
Attachment messageAttachment;
int fileDataSize = int.Parse(DRA["FileSize"].ToString());
string fileType = DRA["FileType"].ToString();
string fileName = DRA["FileName"].ToString();
byte[] fileBuffer = (DRA["FileData"]) as byte[];
MemoryStream ms = new MemoryStream(fileBuffer);
RecordLine("DEBUG 2 - " + fileName + " " + fileType + " " + fileDataSize.ToString() + " " + ms.Length.ToString() + " buffer size:" + fileBuffer.Length.ToString());
messageAttachment = new Attachment(ms, fileName, fileType);
return messageAttachment;
}
break;
case 2: /*from Local Machin */
{
Attachment messageAttachment;
try
{
fileNameString = String.Format("{0}\\{1}", ConfigurationSettings.AppSettings["SOURCE_FILE"],
fileNameString);
messageAttachment = new Attachment(fileNameString);
RecordLine("DEBUG 2.1 - " + messageAttachment.Name);
return messageAttachment;
}
catch (Exception ex)
{
RecordLine("FILE TO ATTACH ERR : " + ex.Message);
}
}
break;
default:
return null;
break;
}
return null;
}
catch (Exception eX)
{
RecordLine("ERROR AttachmentFile : " + eX.Message);
return null;
}
}
I had add this code and it is worked:
foreach (DataRow DRA in DTBA.Rows)
{
message.Attachments.Add(AttachmentFile(2, DRA["FILENAME"].ToString().Trim(), 0, null));
RecordLine("DEBUG 3.1 - " + message.Attachments.Count.ToString());
}
I have written some code which deals with C# reflections and selenium to automate the build process of a URL.
But I am unable to catch the exception. What I did is , I exported into .html format from selenium IDE. and parsed and it automatically calls the function related to it from c# code.
but I am unable to catch it. I need help in this regard? Any guesses why it is unable to catch the exception..
I am using Visual Studio Microsoft Visual C# 2010 Express.
And the code is as follows.
using System;
using System.Text;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Selenium;
using System.Reflection;
using System.IO;
namespace SeleniumTests
{
public class Program
{
public ISelenium selenium;
public void SetupTest()
{
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "URL");
selenium.Start();
}
//[TearDown]
public void TeardownTest()
{
try
{
selenium.Stop();
}
catch (Exception)
{
}
}
public void myFun(string file)
{
bool flag = false;
string targetString = "", valueString = "", commandString = "";
string subString1, subString2;
HtmlAgilityPack.HtmlNode commandNode=null;
HtmlAgilityPack.HtmlNode targetNode=null;
HtmlAgilityPack.HtmlNode valueNode=null;
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(file);
doc.OptionCheckSyntax = true;
doc.OptionFixNestedTags = true;
doc.OptionAutoCloseOnEnd = true;
doc.OptionOutputAsXml = true;
doc.OptionDefaultStreamEncoding = Encoding.Default;
HtmlAgilityPack.HtmlNode table = doc.DocumentNode.SelectSingleNode("//table");
foreach (var row in table.SelectNodes("//tr"))
{
commandNode = row.SelectSingleNode("td[1]");
commandString = commandNode.InnerHtml.ToString();
subString1 = commandString.Substring(0, 1);
subString1 = subString1.ToUpper();
subString2 = commandString.Substring(1, commandString.Length - 1);
commandString = subString1 + subString2;
targetNode = row.SelectSingleNode("td[2]");
if (targetNode != null)
{
targetString = targetNode.InnerHtml.ToString();
if (targetString.Length == 0)
{
targetNode = null;
}
}
valueNode = row.SelectSingleNode("td[3]");
if (valueNode != null)
{
valueString = valueNode.InnerHtml.ToString();
if (valueString.Length == 0)
{
valueNode = null;
}
}
MethodInfo SeleniumMethod = typeof(ISelenium).GetMethod(commandString);
if (SeleniumMethod == null)
{
// Console.WriteLine(" \n NULL " + commandString);
continue;
}
if (targetNode == null && valueNode == null)
continue;
if (targetNode != null && valueNode != null)
{
String[] SeleniumArgs = new String[2];
SeleniumArgs[0] = targetNode.InnerHtml.ToString();
SeleniumArgs[1] = valueNode.InnerHtml.ToString();
try
{
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
catch (System.Reflection.TargetInvocationException)
{
}
catch (Selenium.SeleniumException se)
{
flag = true;
string lines = "\n Selenium Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
}
catch (Exception e)
{
flag = true;
string lines = "\n Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
}
}
else if (targetNode != null && valueNode == null)
{
String[] SeleniumArgs = new String[1];
SeleniumArgs[0] = targetNode.InnerHtml.ToString();
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
else if (valueNode != null)
{
String[] SeleniumArgs = new String[1];
SeleniumArgs[0] = valueNode.InnerHtml.ToString();
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
}// end of for
string line = "\n Script executed successfully ";
if (flag == false)
{
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(line);
writer.Flush();
writer.Close();
}
}
}
}
public class TestProgram
{
static void Main(string[] args)
{
try
{
Program p = new Program();
p.SetupTest();
string file = #"1.html";
p.myFun(file);
p.TeardownTest();
}
catch { }
}
}
}
If you are trying to catch the exception in your Main() method, you need to bubble your exceptions up in your myFun method. At the moment you are drowning any exceptions in your myFun method.
e.g.
try
{
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
catch (System.Reflection.TargetInvocationException)
{
throw; //make this bubble up to the calling method.
}
catch (Selenium.SeleniumException se)
{
flag = true;
string lines = "\n Selenium Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
throw se; //bubble up to calling method
}
//etc...