writing a logfile when backgroundWorker job completed - c#

I have c# application where it displays a message on messagebox after the query is run.At the sametime I want it to write a logfile. This is what i tried but no luck. My logfile was empty.
It had created a empty file.
private void backgroundWorker_Import_DoWork(object sender, DoWorkEventArgs e)
{
//Finally, loop through each row in the dataView and execute INSERT Statements against database
int recCount = 0;
successCount = 0;
failedCount = 0;
dv.RowFilter = "execute_bit IN ('1')";
using (MySqlConnection connectionMySql = new MySqlConnection(connectionStringMySql))
{
connectionMySql.Open();
MySqlCommand commandMySql = new MySqlCommand();
commandMySql.Connection = connectionMySql;
foreach (DataRowView rowView in dv)
{
recCount++;
backgroundWorker_Import.ReportProgress(recCount);
commandMySql.CommandText = rowView["sql"].ToString();
try
{
successCount = successCount + commandMySql.ExecuteNonQuery();
//WriteToLogFile("");
//WriteToLogFile("");
**WriteToLogFile(DateTime.Now.ToString() + ", " + recCount.ToString() + "," + successCount.ToString() + "," + failedCount.ToString());
}**
catch (Exception)
{
failedCount++;
}
}
}
}
private void backgroundWorker_Import_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string msg = "";
msg = msg + "Records successfully imported: " + successCount.ToString() + Environment.NewLine;
msg = msg + "Records that failed to import: " + failedCount.ToString() + Environment.NewLine + Environment.NewLine;
msg = msg + "Records excluded from import (20 minute grace-period): " + (tblVehicles.Rows.Count - successCount - failedCount).ToString();
progressBar1.Visible = false;
MessageBox.Show( msg, "Operation complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
**private void WriteToLogFile(string[] output)
{
StreamWriter sw = null;
FileStream fs = null;
string logfileFileName = System.IO.Path.Combine( "C:/luvi/logfile.txt");
fs = File.Open(logfileFileName, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
foreach (string line in output)
{
sw.WriteLine(line);
}
sw.Close();
sw = null;
}**

You could use File.WriteAllLines as shown in this topic.
Its' syntax is as follows:
public static void WriteAllLines(
string path,
string[] contents
)
In your case you would use it like so:
string logfileFileName = #"C:/luvi/logfile.txt";
File.WriteAllLines(logfileFileName, output);
Note: this overwrites the file, if you want to append them use File.AppendAllLines.
You need to actually call your method aswell, which may be a problem because I do not see that in your code. In the following changes I have replaced the string msg for an array, and added those (you could also use a list and call list.Add).
private void backgroundWorker_Import_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string[] msg = new string[] {};
msg[0] = "Records successfully imported: " + successCount.ToString();
msg[1] = "Records that failed to import: " + failedCount.ToString();
msg[2] = "Records excluded from import (20 minute grace-period): " + (tblVehicles.Rows.Count - successCount - failedCount).ToString();
// Write to log!
WriteToLogFile(msg);
// Show to messagebox.
string showmsg = msg[0] + Environment.NewLine + msg[1] + Environment.NewLine + msg[2];
progressBar1.Visible = false;
MessageBox.Show(showmsg, "Operation complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void WriteToLogFile(string[] output)
{
string logfileFileName = "C:/luvi/logfile.txt";
File.AppendAllLines(logfileFileName, output);
}

it seem problem with WriteToLogFile( string[] output) method. You are passing single string while it is expecting arrary of string. catch block is failing it silently.

Related

Reading encoded string from DataGridView in c#

I am having problems with reading Korean characters from datagridview. I read korean alphabets from csv and written them to datagridview. My method is as follows:
int encoder = 949;
public void DisplayPCM()
{
StreamReader sr;
Encoding korean = Encoding.GetEncoding(encoder);
string selectedDirectory = projectPath + "\\Spec";
string filePath = selectedDirectory + "\\" + functionfile;
pcmpath = new StringBuilder(filePath);
if (Directory.Exists(selectedDirectory))
{
if (File.Exists(filePath))
{
try
{
sr = new StreamReader(filePath, korean);
int lineCount = 0;
StringBuilder readLine = new StringBuilder(sr.ReadLine());
while (readLine.ToString() != null && readLine.ToString() != "")
{
string[] substr = readLine.ToString().Split(',');
if (lineCount >= 1)
{
dPCM.Rows[lineCount - 1].Cells[0].Value = substr[0];
dPCM.Rows[lineCount - 1].Cells[1].Value = substr[1];
dPCM.Rows[lineCount - 1].Cells[2].Value = substr[2];
dPCM.Rows[lineCount - 1].Cells[3].Value = substr[3];
}
readLine = new StringBuilder(sr.ReadLine());
lineCount++;
}
sr.Close();
}
catch
{
MessageBox.Show("Error in Part File \n" + filePath);
}
}
else
{
MessageBox.Show(filePath + "\n does not exist.");
}
}
else
{
}
}
Until this point, there are no problems. The characters in datagridview are displayed in korean alphabets.
Now i have to edit the text in datagridview and read back the text and save it in csv file and reload this csv file text to datagridview.
When I did this procedure, I get some chinese text. It looks like when reading the string from datagridview, there is a problem. For reading datagridview text and saving it in csv file, my steps are as follows:
private void Save_PCM()
{
DirectoryInfo di;
StreamWriter sw = null;
int rowcount = 0;
StringBuilder Newnum, NewName, Newlower, Newupper;
try
{
Encoding korean = Encoding.GetEncoding(encoder);
string selectedDirectory = projectPath + "\\Spec";
string filePath = selectedDirectory + "\\" + functionfile;
pcmpath = new StringBuilder(filePath);
sw = new StreamWriter(pcmpath.ToString());
sw.WriteLine("NO,NAME,Lower SPEC,Upper SPEC");
while (dPCM.Rows[rowcount].Cells[0].Value != null)
{
Newnum = new StringBuilder(dPCM.Rows[rowcount].Cells[0].Value.ToString());
NewName = new StringBuilder(dPCM.Rows[rowcount].Cells[1].Value.ToString());
Newlower = new StringBuilder(dPCM.Rows[rowcount].Cells[2].Value.ToString());
Newupper = new StringBuilder(dPCM.Rows[rowcount].Cells[3].Value.ToString());
if (Newnum == null || NewName == null || Newlower == null || Newupper == null)
break;
sw.WriteLine(Newnum + "," + NewName + "," + Newlower + "," + Newupper);
rowcount++;
}
sw.Close();
}
catch (IOException e)
{
MessageBox.Show("Project name error" + Environment.NewLine + e.Message);
}
catch (NullReferenceException e)
{
MessageBox.Show("Enter all values in PCM" + Environment.NewLine + e.Message);
}
finally
{
if (sw != null)
sw.Close();
}
}
I think that I have to read datagridview cell values by including some encoding methods but I am clueless.
How can I read the text encoded in korean language from datagridview. Thanks in advance.
Now it looks like it works. I thought that the problem was in reading the encoded text from datagridview but the problem was in writing the encoded text to csv file. I made changes in function to read the data into .csv file. I declared a filestream path and added the filestream path and encoding to the streamwriter.
private void Save_PCM()
{
DirectoryInfo di;
FileStream stream = null;
StreamWriter sw = null;
int rowcount = 0;
StringBuilder Newnum, NewName, Newlower, Newupper;
try
{
Encoding korean = Encoding.GetEncoding(encoder);
string selectedDirectory = projectPath + "\\Spec";
string filePath = selectedDirectory + "\\" + functionfile;
pcmpath = new StringBuilder(filePath);
stream = new FileStream(pcmpath.ToString(), FileMode.Create); // overwrite existing file
sw = new StreamWriter(stream, korean);
sw.WriteLine("NO,NAME,Lower SPEC,Upper SPEC");
while (dPCM.Rows[rowcount].Cells[0].Value != null)
{
Newnum = new StringBuilder(dPCM.Rows[rowcount].Cells[0].Value.ToString());
byte[] bb = korean.GetBytes(dPCM.Rows[rowcount].Cells[1].Value.ToString());
NewName = new StringBuilder(Encoding.Default.GetString(bb));
Newlower = new StringBuilder(dPCM.Rows[rowcount].Cells[2].Value.ToString());
Newupper = new StringBuilder(dPCM.Rows[rowcount].Cells[3].Value.ToString());
if (Newnum == null || NewName == null || Newlower == null || Newupper == null)
break;
sw.WriteLine(Newnum + "," + NewName + "," + Newlower + "," + Newupper);
rowcount++;
}
sw.Close();
}
catch (IOException e)
{
MessageBox.Show("Project name error" + Environment.NewLine + e.Message);
}
catch (NullReferenceException e)
{
MessageBox.Show("Enter all values in PCM" + Environment.NewLine + e.Message);
}
finally
{
if (sw != null)
sw.Close();
}
}

Windows Service Stuck on "Starting"

I've just created and installed my first Windows Service. When I start the service is never changes it's status to "Started". The status stays "Starting" but the service is doing it's job. I thought that perhaps the way I'm interacting with the OnStart method. I simply get the OnStart method to call another method that executes fine. Here is a sample:
protected override void OnStart(string[] args)
{
try {
Logger("Start");
}
catch (Exception ex)
{
string filePath2 = #"C:/ProgramData/Error.txt";
using (StreamWriter writer = new StreamWriter(filePath2, true))
{
writer.WriteLine(DateTime.Now + Environment.NewLine + "Message: " + ex.ToString() + Environment.NewLine + "Stack Trace: " + ex.StackTrace);
}
}
}
What would I need to change to get the client to register that the service has started and is running. PS, the service is doing what it's meant to do.
Thanks in advance for any and all help!
EDIT
This is what Logger does:
public void Logger(string state)
{
try
{
{
Random a = new Random(Environment.TickCount);
//unique name PhoneSystem.ApplicationName = "TestApi";//any name
PhoneSystem.ApplicationName = PhoneSystem.ApplicationName + a.Next().ToString();
}
#region phone system initialization(init db server)
String filePath = #"C:/ProgramData/3CXLogger/3CXPhoneSystem.ini";
if (!File.Exists(filePath))
{
//this code expects 3CXPhoneSystem.ini in current directory.
//it can be taken from the installation folder (find it in Program Files/3CXPhone System/instance1/bin for in premiss installation)
//or this application can be run with current directory set to location of 3CXPhoneSystem.ini
//v14 (cloud and in premiss) installation has changed folder structure.
//3CXPhoneSystem.ini which contains connectio information is located in
//<Program Files>/3CX Phone System/instanceN/Bin folder.
//in premiss instance files are located in <Program Files>/3CX Phone System/instance1/Bin
throw new Exception("Cannot find 3CXPhoneSystem.ini");
}
String value = _3cxLogger.Utilities.GetKeyValue("ConfService", "ConfPort", filePath);
Int32 port = 0;
if (!String.IsNullOrEmpty(value))
{
Int32.TryParse(value.Trim(), out port);
PhoneSystem.CfgServerPort = port;
}
value = _3cxLogger.Utilities.GetKeyValue("ConfService", "confUser", filePath);
if (!String.IsNullOrEmpty(value))
PhoneSystem.CfgServerUser = value;
value = _3cxLogger.Utilities.GetKeyValue("ConfService", "confPass", filePath);
if (!String.IsNullOrEmpty(value))
PhoneSystem.CfgServerPassword = value;
#endregion
DN[] ps = PhoneSystem.Root.GetDN(); //Access PhoneSystem.Root to initialize ObjectModel
//_3cxLogger.SampleStarter.StartSample(args);
}
catch (Exception ex)
{
string filePath2 = #"C:\ProgramData\3CXLogger\Error.txt";
using (StreamWriter writer = new StreamWriter(filePath2, true))
{
writer.WriteLine(DateTime.Now + Environment.NewLine + "Message: " + ex.ToString() + Environment.NewLine + "Stack Trace: " + ex.StackTrace);
}
//Console.WriteLine(ex.ToString());
}
string constring = "Data Source = LEWCOMP1\\COMPLIANCE; Initial Catalog = 3CXCallStats; Integrated Security = True";
while (state == "Start")
{
Thread.Sleep(5000);
int count = 0;
foreach (DN dn in PhoneSystem.Root.GetDN())
{
ActiveConnection[] a = dn.GetActiveConnections();
foreach (ActiveConnection ac in a)
{
try
{
if (ac.Status == ConnectionStatus.Connected)
{
count = count + 1;
}
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Source);
string filePath2 = #"C:\ProgramData\3CXLogger\Error.txt";
using (StreamWriter writer = new StreamWriter(filePath2, true))
{
writer.WriteLine(DateTime.Now + Environment.NewLine + "Message: " + ex.ToString() + Environment.NewLine + "Stack Trace: " + ex.StackTrace);
}
}
}
}
count = count / 2;
string update = "UPDATE callsCounter SET Counter = '" + count + "' WHERE ID='1';";
string insert = "INSERT Interval_Counter (Date_Time, Count) VALUES ('" + DateTime.Now + "','" + count + "')";
SqlConnection myCon = new SqlConnection(constring);
SqlCommand updateCMD = new SqlCommand(update, myCon);
SqlCommand insertCMD = new SqlCommand(insert, myCon);
SqlDataReader myReaderUpdate;
SqlDataReader myReaderInsert;
myCon.Open();
myReaderUpdate = updateCMD.ExecuteReader();
myReaderUpdate.Read();
myCon.Close();
myCon.Open();
myReaderInsert = insertCMD.ExecuteReader();
myReaderInsert.Read();
myCon.Close();
}
}
Additionaly, I checked the event logs and there are events for the service has successfully started. Odd.
Thanks for all the help!
I created a new class and started a new thread that targeted the method.
protected override void OnStart(string[] args)
{
Log oLog = new Log();
Thread t = new Thread(new ThreadStart(oLog.Logger));
t.Start();
}

Putting certain lines of a textfile into an editable listbox

So I want to put certain lines into a text box, say I use the "Search Function" to search transaction ID, it would look through the transactions.txt file and find the transaction ID and Read the 6 lines under it which show the transactions Details, once found this would then go to a the listbox which then you could edit the transaction.
I was wondering would you use loops and arrays to do this, and could someone show me how, Thank you!
Heres my current code:
//Creates a textfile with details of the transaction
public void CreateFile()
{
StreamWriter outputFile;
outputFile = File.AppendText("Transactions.txt");
outputFile.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
outputFile.WriteLine("Initial Amount" + " " +AmountLabel.Text);
outputFile.WriteLine("Date Invested" +" " +DateLabel.Text);
outputFile.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
outputFile.WriteLine("Rate Chosen" + " " + RateLabel.Text);
outputFile.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
outputFile.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
outputFile.Close();
MessageBox.Show("Transaction file for Transaction: " + TransactionIDLabel.Text + " " +"Was Created", "Transaction File");
}
//puts all transactions in listbox
//needs to be able to find certain transactions
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader("transactions.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
}
Try This:
string ID = "23";
bool idFound=false;
int count = 0;
foreach (var line in File.ReadLines("transactions.txt"))
{
if (idFound && count < 6)
{
listBox1.Items.Add(line);
count++;
}
if(line.Contains(ID))//if you wantto match exactly use if(line.Equals(ID))
{
idFound = true;
}
}

MSMQ System.Messaging high resource usage

I have make C# console application which uses timer which connects to MSMQ every 10 seconds get data insert into Oracle database. But the issue is that it log in and log off to domain and create high CPU also create security audit log very much which waste my resources.
My console application runs with task schedule. Code is below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.Xml;
using System.IO;
using System.Timers;
using Oracle.DataAccess.Client;
using System.Data;
namespace MSMQ_News
{
class Program
{
private static System.Timers.Timer aTimer;
static void Main(string[] args)
{
try
{
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(60000);//10000
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
//aTimer.Interval = 10000;
aTimer.Enabled = true;
aTimer.Start();
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
catch (Exception ex)
{
Log(" From Main -- " + ex.Message);
}
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Just in case someone wants to inherit your class and lock it as well ...
object _padlock = new object();
try
{
aTimer.Stop();
lock (_padlock)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
ProcessQueueMsgs();
}
}
catch (Exception ex)
{
Log(" From OnTimedEvent -- " + ex.Message);
}
finally
{
aTimer.Start();
}
}
private static void ProcessQueueMsgs()
{
try
{
while ((DateTime.Now.Hour >= 06)
&& (DateTime.Now.Hour <= 16))
{
DateTime dt = DateTime.Now;
ReceiveNewsDetail(dt);
ReceiveNewsHeader(dt);
}
CloseApp();
}
catch (Exception ex)
{
Log(" From ProcessQueueMsgs -- " + ex.Message);
}
}
static bool QueueExist(string QueueName)
{
try
{
if (MessageQueue.Exists(QueueName))
return true;
else
return false;
}
catch (Exception ex)
{
Log(" From QueueExist -- " + ex.Message);
return false;
}
}
private static void ReceiveNewsHeader(DateTime dt)
{
try
{
MessageQueue mqNewsHeader = null;
string value = "", _tmp = "";
_tmp = "<newsHeader></newsHeader> ";
/*if (QueueExist(#".\q_ws_ampnewsheaderrep"))*/
mqNewsHeader = new MessageQueue(#".\q_ws_ampnewsheaderrep");
int MsgCount = GetMessageCount(mqNewsHeader, #".\q_ws_ampnewsheaderrep");
for (int i = 0; i < MsgCount; i++)
{
Message Msg = mqNewsHeader.Receive();
Msg.Formatter = new ActiveXMessageFormatter();
//need to do this to avoid ??? for arabic characters
using (StreamReader strdr = new StreamReader(Msg.BodyStream, System.Text.Encoding.Default))
{
value = strdr.ReadToEnd();
}
value = value.Replace("\0", String.Empty);
if (value != _tmp)
{
LoadNewsHeader(value, dt);
}
}
}
catch (Exception ex)
{
Log("From ReceiveNewsHeader -- " + ex.Message);
}
}
private static void ReceiveNewsDetail(DateTime dt)
{
try
{
MessageQueue mqNewsDetails = null;
string value = "", _tmp = "";
_tmp = "<news></news> ";
/*if (QueueExist(#".\q_ws_ampnewsrep"))*/
mqNewsDetails = new MessageQueue(#".\q_ws_ampnewsrep");
int MsgCount = GetMessageCount(mqNewsDetails, #".\q_ws_ampnewsrep");
for (int i = 0; i < MsgCount; i++)
{
Message Msg = mqNewsDetails.Receive();
Msg.Formatter = new ActiveXMessageFormatter();
//need to do this to avoid ??? for arabic characters
using (StreamReader strdr = new StreamReader(Msg.BodyStream, System.Text.Encoding.Default))
{
value = strdr.ReadToEnd();
}
value = value.Replace("\0", String.Empty);
if (value != _tmp)
{
LoadNewsDetail(value, dt);
}
}
}
catch (Exception ex)
{
Log("From ReceiveNewsDetail -- " + ex.Message);
}
}
private static void LoadNewsHeader(string text , DateTime dt)
{
try
{
//text = ReplaceSpecialCharacters(text);
//text = Clean(text);
//XmlDocument _xmlDoc = new XmlDocument();
//_xmlDoc.LoadXml(text);
//string fileName = "NewsHeader.xml";
text = text.Replace("<arabicFields>", "<arabicFields>\n\t\t");
//createXMLFile(fileName, text);
XmlDocument _xmlDoc = LoadXMLDoc(text);
string SQL = "";
XmlNodeList newsHeaderList = _xmlDoc.SelectNodes("newsHeader/newsHeaderRep");
if (newsHeaderList.Count > 0)
{
OracleParameter pTRUNCATE = new OracleParameter("P_TABLE_NAME", OracleDbType.Varchar2);
pTRUNCATE.Value = "COMPANIES_NEWS";
DatabaseOperation(CommandType.StoredProcedure, "TRUNCATE_TABLE", pTRUNCATE);
}
foreach (XmlNode news in newsHeaderList)
{
XmlNodeList newsIdList = news.SelectNodes("newsId");
SQL = "Insert into COMPANIES_NEWS(NewsID, NewsID_SEQNO, NEWSSTATUS, LANGUAGE_CD, SEC_CD, RELEASEDATE, RELEASETIME, TITLE, STG_TIME) Values(";
foreach (XmlNode newsId in newsIdList)
{
SQL += "'" + newsId["id"].InnerText + "',";
SQL += "" + newsId["seqNo"].InnerText + ",";
}
SQL += "'" + news["newsStatus"].InnerText + "',";
XmlNodeList newsItemList = news.SelectNodes("newsItem");
foreach (XmlNode newsItem in newsItemList)
{
SQL += "'" + newsItem["languageId"].InnerText + "',";
if (newsItem["reSecCode"] != null)
SQL += "'" + newsItem["reSecCode"].InnerText + "',";
else
SQL += "' ',";
XmlNodeList releaseTimeList = newsItem.SelectNodes("releaseTime");
foreach (XmlNode releaseTime in releaseTimeList)
{
SQL += "TO_DATE('" + releaseTime["date"].InnerText + "','YYYYMMDD'),";
SQL += "" + releaseTime["time"].InnerText + ",";
}
}
XmlNodeList arabicFieldsList = news.SelectNodes("arabicFields");
foreach (XmlNode arabicFields in arabicFieldsList)
{
SQL += "'" + RevertSpecialCharacters(arabicFields["title_AR"].InnerText) + "',";
}
SQL += "TO_DATE('" + dt.ToString() + "','MM/DD/YYYY HH12:MI:SS PM'))";
DatabaseOperation(CommandType.Text, SQL, null);
Console.WriteLine("Header : " + DateTime.Now.ToString());
}
if (SQL != "") //RecordCount("Select Count(*) from COMPANIES_NEWS_DETAILS") > 0
{
OracleParameter pREFRESH = new OracleParameter("P_TABLE_NAMEs", OracleDbType.Varchar2);
pREFRESH.Value = "COMPANIES_NEWS";
DatabaseOperation(CommandType.StoredProcedure, "REFRESH_VW_ALL", pREFRESH);
}
}
catch (Exception ex)
{
Log("From LoadNewsHeader -- " + ex.Message);
}
}
private static void LoadNewsDetail(string text, DateTime dt)
{
try
{
//string fileName = "NewsDetail.xml";
text = text.Replace("<arabicFields>", "<arabicFields>\n\t\t");
//text = createXMLFile(fileName);
//text = text.Replace("<arabicFields>", "<arabicFields>\n\t\t");
XmlDocument _xmlDoc = LoadXMLDoc(text);
string SQL = "";
XmlNodeList newsList = _xmlDoc.SelectNodes("news/newsRep");
if (newsList.Count > 0)
{
OracleParameter pTRUNCATE = new OracleParameter("P_TABLE_NAME", OracleDbType.Varchar2);
pTRUNCATE.Value = "COMPANIES_NEWS_DETAILS";
DatabaseOperation(CommandType.StoredProcedure, "TRUNCATE_TABLE", pTRUNCATE);
}
foreach (XmlNode news in newsList)
{
XmlNodeList newsIdList = news.SelectNodes("newsId");
SQL = "Insert into Companies_news_details(NewsID_ID, NewsID_SEQNO, NewsText_1,NewsText_2,STG_TIME) Values(";
foreach (XmlNode newsId in newsIdList)
{
SQL += "" + newsId["id"].InnerText + ",";
SQL += "" + newsId["seqNo"].InnerText + ",";
}
XmlNodeList arabicFieldsList = news.SelectNodes("arabicFields");
foreach (XmlNode arabicFields in arabicFieldsList)
{
// Log(" Before Arabic Text Data -- :" + arabicFields["newsText_AR"].InnerText);
if (arabicFields["newsText_AR"].InnerText.Length > 4000)
{
SQL += "'" + RevertSpecialCharacters(arabicFields["newsText_AR"].InnerText.Substring(0, 3999)).Replace("\n",Environment.NewLine) + "',";
SQL += "'" + RevertSpecialCharacters(arabicFields["newsText_AR"].InnerText.Substring(3999, arabicFields["newsText_AR"].InnerText.Length)).Replace("\n", Environment.NewLine) + "',";
SQL += "TO_DATE('" + dt.ToString() + "','MM/DD/YYYY HH12:MI:SS PM')";
}
else
{
SQL += "'" + RevertSpecialCharacters(arabicFields["newsText_AR"].InnerText).Replace("\n", Environment.NewLine) + "','',";
SQL += "TO_DATE('" + dt.ToString() + "','MM/DD/YYYY HH12:MI:SS PM')";
}
SQL += ")";
DatabaseOperation(CommandType.Text, SQL, null);
Console.WriteLine("Detail : " + DateTime.Now.ToString());
}
}
if (SQL != "") //RecordCount("Select Count(*) from COMPANIES_NEWS_DETAILS") > 0
{
OracleParameter pREFRESH = new OracleParameter("P_TABLE_NAMEs", OracleDbType.Varchar2);
pREFRESH.Value = "COMPANIES_NEWS_DETAILS";
DatabaseOperation(CommandType.StoredProcedure, "REFRESH_VW_ALL", pREFRESH);
}
}
catch (Exception ex)
{
Log("From LoadNewsDetail -- " + ex.Message);
}
}
private static void CloseApp()
{
System.Environment.Exit(0);
}
protected static int GetMessageCount(MessageQueue q, string queueName)
{
var _messageQueue = new MessageQueue(queueName, QueueAccessMode.Peek);
_messageQueue.Refresh(); //done to get the correct count as sometimes it sends 0
var x = _messageQueue.GetMessageEnumerator2();
int iCount = 0;
while (x.MoveNext())
{
iCount++;
}
return iCount;
}
private static void DatabaseOperation(CommandType cmdType, string SQL, OracleParameter param)
{
string oracleConnectionString = System.Configuration.ConfigurationSettings.AppSettings["OracleConnectionString"];
using (OracleConnection con = new OracleConnection())
{
con.ConnectionString = oracleConnectionString;
con.Open();
OracleCommand command = con.CreateCommand();
command.CommandType = cmdType;
command.CommandText = SQL;
if (param != null)
command.Parameters.Add(param);
command.ExecuteNonQuery();
command.Dispose();
con.Close();
}
}
private static String RevertSpecialCharacters(string pValue)
{
string _retVal = String.Empty;
_retVal = pValue.Replace("'", "''");
return _retVal;
}
public static void Log(string Message)
{
// Create a writer and open the file:
StreamWriter log;
//C:\Software\MSMQ_New_News_Fix
if (!File.Exists(#"C:\MSMQ_New_News_Fix\log.txt"))
{
log = new StreamWriter(#"C:\MSMQ_New_News_Fix\log.txt");
}
else
{
log = File.AppendText(#"C:\MSMQ_New_News_Fix\log.txt");
}
// Write to the file:
log.WriteLine(DateTime.Now.ToString() + " : " + Message);
// Close the stream:
log.Close();
}
public static XmlDocument LoadXMLDoc(string xmlText)
{
XmlDocument doc = new XmlDocument();
try
{
string xmlToLoad = ParseXMLFile(xmlText);
doc.LoadXml(xmlToLoad);
}
catch (Exception ex)
{
Log("From LoadXMLDoc -- " + ex.Message);
}
return doc;
}
private static string ParseXMLFile(string xmlText)
{
StringBuilder formatedXML = new StringBuilder();
try
{
StringReader xmlReader = new StringReader(xmlText);
while (xmlReader.Peek() >= 0)
formatedXML.Append(ReplaceSpecialChars(xmlReader.ReadLine()) + "\n");
}
catch (Exception ex)
{
Log("From ParseXMLFile -- " + ex.Message);
}
return formatedXML.ToString();
}
private static string ReplaceSpecialChars(string xmlData)
{
try
{
//if (xmlData.Contains("objectRef")) return "<objectRef></objectRef>";
int grtrPosAt = xmlData.IndexOf(">");
int closePosAt = xmlData.IndexOf("</");
int lenthToReplace = 0;
if (grtrPosAt > closePosAt) return xmlData;
lenthToReplace = (closePosAt <= 0 && grtrPosAt <= 0) ? xmlData.Length : (closePosAt - grtrPosAt) - 1;
//get the string between xml element. e.g. <ContactName>Hanna Moos</ContactName>,
//you will get 'Hanna Moos'
string data = xmlData.Substring(grtrPosAt + 1, lenthToReplace);
string formattedData = data.Replace("&", "&").Replace("<", "<")
.Replace(">", ">").Replace("'", "&apos;");
if (lenthToReplace > 0) xmlData = xmlData.Replace(data, formattedData);
return xmlData;
}
catch (Exception ex)
{
Log("From ReplaceSpecialChars -- " + ex.Message);
return "";
}
}
}
}
How can i solve above issue
Why not host your queue reader process in a windows service. This will continually poll the queue each 10 seconds.
Then use the windows scheduler to start/stop the service at relevant times to create your service window.
This means you won't need to do anything complicated in your scheduled task, and you won't be loading and unloading all the time.
Well from logic you are very correct that I should make windows service not timer service and Task schedule.
But my question was why It is login / log out frequently, which waste the resource of my Domain server. After intense investigation, I found that calling QueueExits is resource critical. Another thing what I found is that when you connect MSMQ queue you are login to share resource, which will login to Domain. As my code was running every 10-20 seconds it was wasting my Domain server resources.
For resolution, I make my MessageQueue object globally in following way
private static MessageQueue mqNewsHeader = new MessageQueue(#".\q_ws_ampnewsheaderrep");
private static MessageQueue mqNewsDetails = new MessageQueue(#".\q_ws_ampnewsrep");
So it will create Once in the life of the Application and we will log in and log out only once. Then I will pass this object to the function as parameter. I see also that my MessageQueue count function was also resource critical, So I change it to following
protected static int GetMessageCount(MessageQueue q)
{
//var _messageQueue = new MessageQueue(queueName, QueueAccessMode.Peek);
//_messageQueue.Refresh(); //done to get the correct count as sometimes it sends 0
// var x = _messageQueue.GetMessageEnumerator2();
int iCount = q.GetAllMessages().Count();
// while (x.MoveNext())
// {
// iCount++;
// }
return iCount;
}
Hope this clear my answer and will help others also.

windows application can not write to log.txt

This is main program.cs
LogError.WriteError("Application started: " + DateTime.Now + Environment.NewLine);
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new CrawlerApp());
}
catch (Exception e)
{
LogError.WriteError(e);
}
LogError.WriteError("Application closed: " + DateTime.Now + Environment.NewLine);
and this is LogError class
public static class LogError
{
public static void WriteError(Exception e)
{
WriteError("Message: " + e.Message + Environment.NewLine + "Stack trace: " + e.StackTrace);
}
public static void WriteError(string error)
{
try
{
StreamWriter sw = File.AppendText("log.txt");
sw.WriteLine(DateTime.Now + Environment.NewLine);
sw.WriteLine(error + Environment.NewLine);
sw.WriteLine(Environment.NewLine);
sw.Close();
}
catch (Exception)
{
//
}
}
}
When i publish application and run it log.txt file is never created. If i run application from bin/debug folder then works. Why when i publish app logging not working. I am using win 2003 OS.
It could be an UnauthorizedAccessException.
Rather than guess at it you might want to change your catch to log to the event log rather than just swallowing it
File.AppendText only works if the file already exists: http://msdn.microsoft.com/en-us/library/system.io.file.appendtext.aspx. This link also has this sample code:
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("This");
sw.WriteLine("is Extra");
sw.WriteLine("Text");
}
you could use this code too, it works whether the file exits or not. As a plus it creates the log file based on the current DateTime in YYYYMMDD format
private static void doLog(String message)
{
//getting current date
String dateStr = "";
int day, month, year;
year = System.DateTime.Now.Year;
month = System.DateTime.Now.Month;
day = System.DateTime.Now.Day;
dateStr += year.ToString() + "";
if (month < 10) dateStr += "0";
dateStr += month.ToString() + "";
if (day < 10) dateStr += "0";
dateStr += day.ToString() + "";
//writting the message
string logFile = Environment.CurrentDirectory + #"/LOG_" + dateStr + #".txt";
System.IO.StreamWriter sw = new System.IO.StreamWriter(logFile, true);
sw.WriteLine(System.DateTime.Now.ToString() + "\t" + message);
sw.Close();
}
Your log-writing code is probably throwing an exception. Try removing the try/catch in WriteError to see what exception is being thrown.

Categories

Resources