I am calling following method inside thread. inside method i have written logs which writes some variable values in notepad file.
Problem : Sometime last log of method do not log anything. ie last line not exucuting sometime. i am not able to understand problem. please guide me if there are issue somewhere.
This is web application hosted in iis server.
Function :
public bool ResetEmployeeAssignedCoursesByRole()
{
bool bReturn = false;
DbTransactionHelper dbTransactionHelper = new DbTransactionHelper();
dbTransactionHelper.BeginTransaction();
try
{
// this line execuete fine
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Started " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
StringBuilder sbQueryEmployeeCourse = new StringBuilder();
sbQueryEmployeeCourse.Append(" set #roleID = " + roleID + "; ");
sbQueryEmployeeCourse.Append(" set #courseID = " + courseID + "; ");
sbQueryEmployeeCourse.Append(" set #inActiveReason = " + inActiveReason + "; ");
sbQueryEmployeeCourse.Append(" set #lastRecordUpdateSource = " + lastRecordUpdateSource + "; ");
sbQueryEmployeeCourse.Append(" call sp_Reset_EmpAssignedCoursesByRole (#roleID, #courseID, #inActiveReason, #lastRecordUpdateSource); ");
DataTable dtEmployeeCourse = dbTransactionHelper.GetDataTable(BusinessUtility.GetString(sbQueryEmployeeCourse), CommandType.Text, null
);
dbTransactionHelper.CommitTransaction();
bReturn = true;
// this line not execuete sometime.
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
}
catch (Exception ex)
{
ErrorLog.createRoleLog("Add Role ID " + BusinessUtility.GetString(roleID));
dbTransactionHelper.RollBackTransaction();
ErrorLog.createRoleLog("Add Course ID " + BusinessUtility.GetString(courseID));
ErrorLog.createRoleLog(ex.ToString());
}
return bReturn;
}
Calls method like below :
Thread t = new Thread(ResetEmployeeAssignedCoursesByRole);
t.Start();
FUNCTION createRoleLog :
public static void createRoleLog(string errorMessage, int empHdrID = 0)
{
try
{
//string path = BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogsDiractory")) + "Log" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
string path = BusinessUtility.GetString(ErrorLog.ErrorLogPath) + "RoleLog" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
if (BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogError")).ToString().ToUpper() == "TRUE")
{
if (!File.Exists(path))
{
StreamWriter sw = File.CreateText(path);
sw.Close();
}
//using (System.IO.StreamWriter sw = System.IO.File.AppendText(path))
//{
// sw.WriteLine("-------- " + DateTime.Now + " --------");
// sw.WriteLine(errorMessage);
// sw.WriteLine("------------------------");
// sw.Close();
//}
if (!IsFileLocked(new FileInfo(path)))
{
using (FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (System.IO.StreamWriter sw = new StreamWriter(stream))
{
if (empHdrID != 0)
{
sw.WriteLine("-------- [empHdrID: " + empHdrID + "] " + DateTime.Now + " --------");
}
else
{
sw.WriteLine("-------- " + DateTime.Now + " --------");
}
sw.WriteLine(errorMessage);
sw.WriteLine("------------------------");
sw.Close();
}
}
}
else
{
}
}
}
catch (Exception ex)
{
//throw ex;
}
}
Last line of function which not execution sometime is :
** this line not execuete sometime.**
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
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();
}
I'm having some trouble finding a way to get the results from updates/inserts/deletes/table creates...
I would like to get it like you see in the SSMS (SQL Server Management Studio) message tab (guess the tool is done_in_proc).
At the moment, I can get the exceptions, and I can capture the prints done in the SQL script.
I already tried ExecuteScalar, ExecuteReader, ExecuteWithResults and got nothing.
Thanks,
Code:
public void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
foreach (SqlError err in e.Errors)
{
richTextBoxDeployCopy.AppendText("Info : "+err.Message + Environment.NewLine);
}
}
public void ExecSQLScript(string Instance, string Database, string SQLScript, string Username, string Password)
{
if (Application2Deploy == "DUMMY")
{
server = "Server";
}
else
{
server = Instance;
} string sqlConnectionString = #"User ID=" + Username + "; Password = " + Password + ";Persist Security Info=False;Initial Catalog=" + Database + ";Data Source=" + server + "\\" + Instance;
FileInfo file = new FileInfo(SQLScript);
string script = file.OpenText().ReadToEnd();
conn = new SqlConnection(sqlConnectionString);
conn.FireInfoMessageEventOnUserErrors = true;
Server SQLserver = new Server(new ServerConnection(conn));
if (checkBoxDeployCopyTestingScript.Checked)
{
richTextBoxDeployCopy.AppendText("Test: Running SQL Script......" + Environment.NewLine);
LogFile(DateTime.Now + "Test: Running SQL Script......", LogPath);
}
else
{
try
{
SQLserver.ConnectionContext.Connect();
SQLserver.ConnectionContext.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMessage);
SQLserver.ConnectionContext.BeginTransaction();
SQLserver.ConnectionContext.ExecuteNonQuery(script);
Error = false;
}
catch (Exception SQLEx)
{
Error = true;
richTextBoxDeployCopy.AppendText("Error executing SQL Script." + Environment.NewLine);
LogFile(DateTime.Now + "Error executing SQL Script", LogPath);
richTextBoxDeployCopy.AppendText("Exception: " + SQLEx.InnerException.Message + Environment.NewLine);
LogFile(DateTime.Now + "Exception: " + SQLEx.InnerException.Message, LogPath);
try
{
SQLserver.ConnectionContext.RollBackTransaction();
}
catch (Exception ex2)
{
richTextBoxDeployCopy.AppendText("Error executing rollback." + Environment.NewLine);
richTextBoxDeployCopy.AppendText("Exception: " + ex2.Message + Environment.NewLine);
}
}
if (Error == false)
{
SQLserver.ConnectionContext.CommitTransaction();
CopyExit("End");
file.OpenText().Close();
file.OpenText().Dispose();
SQLserver.ConnectionContext.SqlConnectionObject.Close();
//SQLserver.ConnectionContext.ForceDisconnected();
}
else
{
CopyExit("Abort");
file.OpenText().Close();
file.OpenText().Dispose();
SQLserver.ConnectionContext.SqlConnectionObject.Close();
//SQLserver.ConnectionContext.ForceDisconnected();
}
}
}
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("'", "'");
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.
I have created a Site Monitoring Utility, that sends an HTTP and PING request to a site, checks the database to make sure it's up and ready to take requests, and checks a service that the website needs.
The problem is, the utility will randomly lose connection to the server for hours at a time, with no reason why.
I have run WireShark multiple times on the server to see if there is something network related, but I keep coming up with nothing. WireShark says no packets or anything is getting dropped.
Has anybody else ever run into anything like that?
I can't post the code for the service, as it contains sensitive information in it. I don't think it's my code, but I'm having a hard time figuring out what it could be!
Here is my Code:
private void HttpRequest()
{
foreach(string urlToTest in urls)
{
bool Success = false;
HttpWebResponse URLRes = null;
HttpWebRequest URLReq = null;
bool Timed = false;
StringBuilder Message = null;
HttpStatusCode code = HttpStatusCode.Unused;
string codeDescript = string.Empty;
for (int i = 0; i < HTTPThreshold; i++)
{
try
{
WriteToOwnEventLog("Sending HTTP Request to " + urlToTest, "Http Request", true);
URLReq = (HttpWebRequest) WebRequest.Create(urlToTest);
URLReq.Timeout = 300000;
URLReq.Proxy = null;
URLReq.ServicePoint.ConnectionLeaseTimeout = 300000;
URLReq.ServicePoint.MaxIdleTime = 300000;
URLReq.AllowAutoRedirect = true;
URLReq.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
using(URLRes = (HttpWebResponse) URLReq.GetResponse())
{
if (URLReq.HaveResponse)
{
if (URLRes.StatusCode == HttpStatusCode.OK || URLRes.StatusCode == HttpStatusCode.Continue)
{
Success = true;
Timed = false;
break;
}
}
}
}
catch (Exception ex)
{
if (URLRes != null && URLRes.StatusCode != null)
code = URLRes.StatusCode;
if (URLRes != null && URLRes.StatusDescription != null)
codeDescript = URLRes.StatusDescription;
if (ex.Message == "The operation has timed out")
{
Timed = true;
}
else
{
LogError(ex);
if (i + 1 == HTTPThreshold)
{
Message = new StringBuilder("Message: " + ex.Message + "<br/>");
if (ex.InnerException != null)
Message.Append("Inner Exception: " + ex.InnerException + "<br/>");
if (ex.Source != null)
Message.Append("Source: " + ex.Source + "<br/>");
if (ex.StackTrace != null)
Message.Append("Stack Trace" + ex.StackTrace + "<br/>");
}
}
}
finally
{
if (URLReq != null)
{
URLReq.Abort();
URLReq = null;
}
if (URLRes != null)
{
URLRes.Close();
URLRes = null;
}
GC.Collect();
}
}
if (Success)
{
WriteToOwnEventLog("HTTP Request returned Successful", "Http Request", true);
}
else
{
if (!Timed && code != HttpStatusCode.Unused && !string.IsNullOrEmpty(codeDescript) && Message == null)
EmailError("Site '" + urlToTest + "' HttpRequest returned with a status of " + code.ToString() + ". \n Description: \n " + codeDescript);
else if (!Timed && code != HttpStatusCode.Unused && !string.IsNullOrEmpty(codeDescript) && Message != null)
EmailError("Site '" + urlToTest + "' errored with an exception. HttpRequest returned with a status of " + code.ToString() + ". \n Description: \n " + codeDescript + Message.ToString());
else if (!Timed && code == HttpStatusCode.Unused && string.IsNullOrEmpty(codeDescript) && Message == null)
EmailError("Site '" + urlToTest + "' HttpRequest returned with Error. No information to display");
else if (!Timed && code == HttpStatusCode.Unused && string.IsNullOrEmpty(codeDescript) && Message != null)
EmailError("Site '" + urlToTest + "' HTTPRequest errored with an exception.<br/>" + Message.ToString());
else if (Timed)
EmailError("Site '" + urlToTest + "' HTTPRequest Timed Out");
WriteToOwnEventLog("HTTP Request failed, Email Sent", "Http Request", true);
}
}
WriteToOwnEventLog("<--------------------------------------------------------------------------------------------->", "Http Request", false);
}
private void PingUrl()
{
foreach(string urlToTest in urls)
{
bool Success = false;
PingReply reply = null;
StringBuilder Message = null;
IPStatus status = IPStatus.Unknown;
for (int i = 0; i < PingThreshold; i++)
{
Ping ping = null;
try
{
ping = new Ping();
WriteToOwnEventLog("Ping sent to " + urlToTest, "Ping", true);
string urlToTest1 = urlToTest.Substring(urlToTest.IndexOf(":") + 3);
if (urlToTest1.Contains('/'))
{
urlToTest1 = urlToTest1.Substring(0, urlToTest1.IndexOf('/'));
}
reply = ping.Send(urlToTest1);
status = reply.Status;
if (reply.Status == IPStatus.Success)
{
Success = true;
break;
}
}
catch (Exception ex)
{
LogError(ex);
if (i + 1 == PingThreshold)
{
Message = new StringBuilder("Message: " + ex.Message + "<br/>");
if (ex.InnerException != null)
Message.Append("Inner Exception: " + ex.InnerException + "<br/>");
if (ex.Source != null)
Message.Append("Source: " + ex.Source + "<br/>");
if (ex.StackTrace != null)
Message.Append("Stack Trace" + ex.StackTrace + "<br/>");
}
}
finally
{
if (ping != null)
{
ping.Dispose();
ping = null;
}
if (reply != null)
{
reply = null;
}
GC.Collect();
}
}
if (Success)
{
WriteToOwnEventLog("Ping Received Successfully", "Ping", true);
}
else
{
if (status != IPStatus.Unknown && Message != null)
EmailError("Ping Failed. Returned with a status of " + reply.Status.ToString() + " for site '" + urlToTest + "'. Exception:" + Message);
else if (status != IPStatus.Unknown && Message == null)
EmailError("Ping Failed. Returned with a status of " + reply.Status.ToString() + " for site '" + urlToTest + "'.");
else if (status == IPStatus.Unknown && Message != null)
EmailError("Ping failed with an exception. <br/>" + Message.ToString());
else if (status == null && Message == null)
EmailError("Ping failed. No information available");
WriteToOwnEventLog("Ping Failed. Email sent", "Ping", true);
}
}
WriteToOwnEventLog("<--------------------------------------------------------------------------------------------->", "Ping", false);
}
private void CheckDatabase()
{
foreach(string database in databases)
{
bool Success = false;
StringBuilder Message = null;
string dbName = "";
string dbServer = "";
for (int i = 0; i < DatabaseThreshold; i++)
{
SqlConnection conn = null;
try
{
using(conn = new SqlConnection(database))
{
dbName = conn.Database;
dbServer = conn.DataSource;
WriteToOwnEventLog("Opening Connection to SQL Database " + dbName + " On " + dbServer, "Database", true);
conn.Open();
Success = true;
conn.Close();
break;
}
}
catch (Exception ex)
{
LogError(ex);
if (i + 1 == DatabaseThreshold)
{
Message = new StringBuilder("Message: " + ex.Message + "<br/>");
if (ex.InnerException != null)
Message.Append("Inner Exception: " + ex.InnerException + "<br/>");
if (ex.Source != null)
Message.Append("Source: " + ex.Source + "<br/>");
if (ex.StackTrace != null)
Message.Append("Stack Trace" + ex.StackTrace + "<br/>");
}
}
finally
{
if (conn != null)
{
conn.Close();
conn.Dispose();
}
GC.Collect();
}
}
if (Success)
{
WriteToOwnEventLog("SQL Database Connection Successful To " + dbName + " on " + dbServer, "Database", true);
}
else
{
if (Message != null)
{
EmailError("Cannot connect to SQL Database " + dbName + " on " + dbServer + "<br/>" + Message.ToString());
WriteToOwnEventLog("SQL Database Connection Failed for database " + dbName + " on " + dbServer + ", Email Sent<br>" + Message.ToString(), "Database", true);
}
else
{
EmailError("Cannot connect to SQL Database " + dbName + " on " + dbServer + ", No information available");
WriteToOwnEventLog("SQL Database Connection Failed for database " + dbName + " on " + dbServer + ", Email Sent, No information available", "Database", true);
}
}
}
WriteToOwnEventLog("<--------------------------------------------------------------------------------------------->", "Database", false);
}