Unable to catch the exception from selenium in C# - c#

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...

Related

SGML formating Issue

I have an requirement to read the SGML file and replace if the symbol like comma(,) or full stop (.) then I need to change the symbols and save with the same SGML file itself but I am facing the format issue after replacing the content.
Below is my code and my final output would be store with the same .sgm format.
The below code is working but after replacing the values the output format is differs. Can you suggest for this scenario
Main method:
string resultValue = HTMLToEntity(ReplaceSGML(sbContent.ToString()));
StringReader sr = new StringReader(resultValue.ToString());
SgmlReader reader = new SgmlReader();
reader.WhitespaceHandling = WhitespaceHandling.All;
reader.CaseFolding = Sgml.CaseFolding.ToLower;
reader.InputStream = sr;
StringWriter sw = new StringWriter();
XmlTextWriter w = new XmlTextWriter(sw);
w.Formatting = System.Xml.Formatting.Indented;
w.WriteStartDocument();
reader.Read();
while (!reader.EOF)
{
w.WriteNode(reader, true);
}
//File.WriteAllText(#"C:\Output\test.sgm", );
w.Flush();
w.Close();
Method : ReplaceSGML
private static string ReplaceSGML(string html)
{
XmlDocument xml = new XmlDocument();
xml.Load(_xmlEnglishPath);
XmlNodeList resources = xml.SelectNodes("root/data");
_htmlEnglishDictonaries = new Dictionary<string, string>();
_htmlEnglishDictonaries.Add(";", "{After1Space}"); // replacing semicolon into {After1space}
_htmlEnglishDictonaries.Add(":", "{Before1Space}"); // replacing colon into {Before1Space}
_htmlEnglishDictonaries.Add(".", "{Before1Space}"); // replacing . into {Before1Space}
string line = string.Empty;
StringReader reader = new StringReader(html);
while (reader.Peek() > -1)
{
line = reader.ReadLine();
foreach (var events in _htmlEnglishDictonaries)
{
if (line.Contains(events.Key))
{
// Rule should be implement
// <!-- Replacetext 1.{After1Space}, 2.{Before1Space}, 3.{NoSpace}, 4. {After1LetterCaps} -->
int idx;
if (events.Value.ToLower().Trim() == "{after1space}")
{
idx = line.IndexOf(events.Key) + events.Key.Length;
if (line[idx].ToString() != " ")
{
line = line.Replace(events.Key, events.Key + " ");
}
}
if (events.Value.ToLower().Trim() == "{before1space}")
{
idx = line.IndexOf(events.Key);
if (line[idx].ToString() != " ")
{
line = line.Replace(events.Key, " " + events.Key);
}
}
if (events.Value.ToLower().Trim() == "{before1space},{after1space}")
{
idx = line.IndexOf(events.Key);
if (line[idx].ToString() != " ")
{
line = line.Replace(events.Key, " " + events.Key + " ");
}
}
if (events.Value.ToLower().Trim() == "{nospace}")
{
idx = line.IndexOf(events.Key);
if (line[idx].ToString() != " ")
{
line = line.Replace(events.Key, " " + events.Key);
}
}
if (events.Value.ToLower().Trim() == "{after1lettercaps}")
{
idx = line.IndexOf(events.Key) + events.Key.Length;
if (line[idx].ToString() != " ")
{
if (line[idx + 1].ToString() != " ")
{
line = line.Replace(events.Key, " " + events.Key + line[idx + 1].ToString().ToUpper());
}
else
{
line = line.Replace(events.Key, " " + events.Key);
}
}
}
}
}
}
return line.ToString();
}
Thanks in advance

System.Net.WebException while downloading file

I have a list of mp3 which I am downloading. After some files are downloaded, not all of them - around 5-7, I get WebException. I did a stacktrace and this is the result.
Exception thrown: 'System.Net.WebException' in System.dll
Debug message: The operation has timed out
InnerEx: at System.Net.HttpWebRequest.GetResponse()
at iBlock.Main._InetGetHTMLSearch(String sArtist) in C:\Users\...\Main.cs:line 590
My _InetGetHTMLSearch looks like this
private void _InetGetHTMLSearch(string sArtist)
{
aLinks.Clear();
if (AudioDumpQuery == string.Empty)
{
//return string.Empty;
}
string[] sStringArray;
string sResearchURL = "http://www.audiodump.biz/music.html?" + AudioDumpQuery + sArtist.Replace(" ", "+");
string aRet;
HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(sResearchURL);
webReq.UserAgent = "Mozilla / 5.0(Macintosh; Intel Mac OS X 10_9_3) AppleWebKit / 537.75.14(KHTML, like Gecko) Version / 7.0.3 Safari / 7046A194A";
webReq.Referer = "http://www.audiodump.com/";
webReq.Timeout = 5000;
try
{
webReq.CookieContainer = new CookieContainer();
webReq.Method = "GET";
using (WebResponse response = webReq.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
aRet = reader.ReadToEnd();
//Console.WriteLine(aRet);
string[] aTable = _StringBetween(aRet, "<BR><table", "table><BR>", RegexOptions.Singleline);
if (aTable != null)
{
string[] aInfos = _StringBetween(aTable[0], ". <a href=\"", "<a href=\"");
if (aInfos != null)
{
for (int i = 0; i < aInfos.Length; i++)
{
//do some magic here
}
}
else
{
//debug
}
}
else
{
//debug 2
}
}
response.Dispose();
}
}
catch (Exception ex)
{
Console.WriteLine("Debug message: " + ex.Message + "InnerEx: " + ex.StackTrace);
aLinks.Clear();
return;
//throw exception
}
}
what this method does is simple. A simple search of the sArtist given at audiodump.com
I have a timer which runs very fast, every 10ms.
private void MainTimer_Tick(object sender, EventArgs e)
{
_DoDownload(DoubleDimList[i][y], ref mp3ToPlay);
if (muted) Mute(0);
if (Downloading)
{
StatusLabel.Text = "Downloading: " + DoubleDimList[i][y];
}
}
Now this timer handles the download in the background in a Global scope.
The _DoDownload methos which basically starts the entire process looks like this
private void _DoDownload(string dArtist, ref string dPath)
{
if (!Contain && skip <= 3 && !Downloading)
{
try
{
_InetGetHTMLSearch(dArtist);
if (aLinks.Count < 1)
{
//skip and return
Console.WriteLine("Skipping: " + dArtist);
IniWriteValue(_playlists[i], "Track " + y, dArtist + " -iBlockSkip");
y++;
return;
}
string path = mp3Path + "\\" + dArtist + ".mp3";
if (DownloadOne(aLinks[0], path, false))
{
hTimmer.Start();
Downloading = true;
}
}
catch (Exception Ex)
{
MessageBox.Show("Download start error: " + Ex.Message);
}
}
else if (Downloading)
{
try {
int actualBytes = strm.Read(barr, 0, arrSize);
fs.Write(barr, 0, actualBytes);
bytesCounter += actualBytes;
double percent = 0d;
if (fileLength > 0)
percent =
100.0d * bytesCounter /
(preloadedLength + fileLength);
label1.Text = Math.Round(percent) + "%";
if (Math.Round(percent) >= 100)
{
string path = mp3Path + "\\" + dArtist + ".mp3";
label1.Text = "";
dPath = path;
aLinks.Clear();
hTimmer.Stop();
hTimmer.Reset();
fs.Flush();
fs.Close();
lastArtistName = "N/A";
Downloading = false;
y++;
if (y >= DoubleDimList[i].Count)
{
i++;
}
}
if (Math.Round(percent) <= 1)
{
if (hTimmer.ElapsedMilliseconds >= 3000)
{
string path = mp3Path + "\\" + dArtist + ".mp3";
hTimmer.Stop();
hTimmer.Reset();
fs.Flush();
fs.Close();
System.IO.File.Delete(path);
Contain = false;
skip += 1;
Downloading = false;
}
} }
catch(Exception Ex)
{
MessageBox.Show("Downloading error: " + Ex.Message);
}
}
}
Now once the exception is thrown it messes up the entire project. As you see in the last method, if _InetGetHTMLSearch doesn't update the search(returns nothing) I am skipping and moving to next search. However the exception will be thrown in every next search. I tried setting new cookies in every search but still didn't work.
Any solutions how to avoid this issue?
P.S. I have to say that if I change the timer's Interval to 500ms it will download more mp3 before the exception is thrown but not all of them.
Edit: The issue here is obvious. The request timesout but even if I set it to Timeout.Infinite it will hand there forever

Can't read active directory users from IIS, but can read in debugging mode

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.

XMLNodeList null reference even after checking the next innertext value in advance

I am trying to get the value from the next item, for example, if the next item is null, or doesnt exist, it will proceed to printing. The main problem i am having lies only at this part
Main Question :
try
{
numCheck = productList[j+1]["Number"].InnerText;
}
catch (Exception ex)
{
numCheck = string.Empty;
}
if (numCheck != null)
{
try
{
mainNumber = Data.getFullItemDetail(productList[j + 1]["Number"].InnerText);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I did a check before i tried if else just to make sure the value exist, however, even after it detects that it has a value, this line will throw an error NullReference
mainNumber = Data.getFullItemDetail(productList[j + 1]["Number"].InnerText);
FULL Code just in case:
XmlDocument xml = new XmlDocument();
xml.LoadXml(productItems);
XmlNodeList productList = xml.SelectNodes("/Products/Product");
for (int j = 0; j < productList.Count; j++)
{
itemCount++;
int i = j + 1;
string item = productList[j]["Number"].InnerText;
number = Data.getFullItemDetail(item);
try
{
#region mainItem
if (number == 0)
{
itemCount++;
itemName = productList[j]["Name"].InnerText;
try
{
numCheck = productList[i]["Number"].InnerText;
}
catch (Exception ex)
{
numCheck = string.Empty;
}
if (numCheck != null)
{
try
{
mainNumber = Data.getFullItemDetail(productList[i]["Number"].InnerText);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (mainNumber == 0)
{
foreach (string condimentItem in condiment)
{
condimentText += condimentItem.ToString() + "\n";
}
string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n";
//print here, because the next item is another main item.
};
try
{
p.Print();
}
catch (Exception ex)
{
throw new Exception("Exception Occured While Printing", ex);
}
}
else
{
MessageBox.Show("Error");
}
}
else
{
foreach (string condimentItem in condiment)
{
condimentText += condimentItem.ToString() + "\n";
}
string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n";
}
}
#endregion
#region CondimentItem
else if (number == 4)
{
condiment.Add(productList[j]["Name"].InnerText);
try
{
numCheck = productList[i]["Number"].InnerText;
}
catch (Exception ex)
{
numCheck = string.Empty;
}
//Check next item.
if (numCheck == null)
{
foreach (string condimentItem in condiment)
{
condimentText += condimentItem.ToString() + "\n";
}
string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n";
//print here, because the next item is another main item.
}
else
{
mainNumber = Data.getFullItemDetail(productList[i]["Number"].InnerText);
if (mainNumber == 0)
{
foreach (string condimentItem in condiment)
{
condimentText += condimentItem.ToString() + "\n";
}
string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n";
//print here, because the next item is another main item.
}
}
}
#endregion
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Edited : Data.getFullItemDetail only returns 1 int value.
public static int getFullItemDetail(string number)
{
int num = Convert.ToInt32(number);
int numReturn;
using (SqlConnection conn = getConnectionSAP())
{
SqlCommand comm = new SqlCommand("select belongcond from ------ where number = " + num, conn);
conn.Open();
SqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
num = Convert.ToInt32(dr["-------"]);
}
comm.Clone();
comm.Dispose();
}
num = Convert.ToInt32(num.ToString().Substring(0, 1));
return num;
}
productList[j+1]["Number"] is null, so at the second line an exception is thrown (because you can't call null.InnerText), caught and then you set numCheck = string.Empty.
The next line you test for if (numCheck != null), which is true, because you just set it to string.Empty in the exception handler. You then call InnerText on productList[j+1]["Number"] again, which throws a NullReferenceException again.
Set breakpoints, walk through your code, inspect your variables, just as explained in What is a NullReferenceException and how do I fix it?.
Just change your if (numCheck != null) to if (productList[j+1]["Number"] != null).

how to save exception in txt file?

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;

Categories