I'm brand new to registry queries, so bear with my ignorance.
I'm having difficult time figuring out why the number of values coming back from .GetValueNames() does not match .ValueCount. The ValueCount returns 7, but the list created by GetValueNames lists 25 values.
static void Main()
{
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(#"..mypath");
string[] nameList = regKey.GetSubKeyNames();
string parentKey = "xxx";
// Create a list of strings to put registry key values into
List<string> oRegNameList = new List<string>();
string[] oSubKeyList = new string[]{};
if (nameList.Count() == 0)
{
MessageBox.Show("No registry key was found for that");
}
else
{
foreach (string keyname in regKey.GetSubKeyNames())
{
try
{
using (RegistryKey key = regKey.OpenSubKey(keyname))
{
if (keyname.Contains(parentKey))
MessageBox.Show("Registry key found : " + key.Name + " contains " + key.ValueCount + " values");
{
oRegNameList.Add(key.Name);
oSubKeyList = key.GetValueNames();
}
}
}
catch (System.Security.SecurityException)
{
}
}
}
int keyVal = 1;
foreach (string oSubKeyName in oSubKeyList)
{
MessageBox.Show("Key " + keyVal + " = " + oSubKeyName);
keyVal++;
}
I have 2 methods. 1 - is validation and 2 - is uploading if validation; how to cancel uploading?
1 - CheckValidationByMEAS_TYPE(lotInfo.LotDataTable, MEAS_TYPE, lotInfo);
int skipRows = 0;
foreach (DataRow item in lotTable.Rows)
{
string filename = Convert.ToString(item["Filename"]);
if (filename == string.Empty || filename == "NA")
{
continue;
}
String[] data = filename.Split('_');
string measType = Convert.ToString(data[2]);
bool rowIsNA = true;
for (int j = 1; j <= 11; j++) // From I to S in AVG WorkSheet
{
string paramValue = Convert.ToString(item[7 + j]);
if (rowIsNA == true && paramValue != "NA")
{
rowIsNA = false;
}
}
if (rowIsNA && (MEAS_TYPE.ToUpper() == measType.ToUpper() || MEAS_TYPE.ToUpper() == "ALL"))
{
skipRows++;
}
}
string message = string.Empty;
string errMsg = string.Empty;
if (skipRows > 1)
{
MessageBox.Show("Measure different rowbar or adjacent slider. " + skipRows + " sliders have no data in MATLAB", "AFM Host Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
2 - public static bool SendData(LotInfo lotInfo, List<string> submitMessage)
string message = string.Empty;
string errMsg = string.Empty;
DataTable MQDataTable;
try
{
//this is method 1 CheckValidationByMEAS_TYPE(lotInfo.LotDataTable, MEAS_TYPE, lotInfo);
}
catch (Exception exception)
{
message = "Job: " + lotInfo.SubmissionID + " FAILED to convert data for MQ submission.";
submitMessage.Add(exception.Message);
Globals.Logger.Error(exception.Message);
return false;
}
try
{
foreach (DataRow row in MQDataTable.Rows)
{
PDBAXLib.PdbClass PDB = new PDBAXLib.PdbClass();
PDB.init(AppConfig.GetString("MQConfiguration", "MQ_ADDRESS"), "1", AppConfig.GetString("MQConfiguration", "MQ_Connection_File"));
while (PDB.reupload()) ;
PDB.format("Detail");
foreach (DataColumn col in MQDataTable.Columns)
{
if (!string.IsNullOrEmpty(row[col].ToString()))
PDB.field(col.ColumnName, row[col].ToString());
else if (row[col].ToString().Equals(" "))
PDB.field(col.ColumnName, row[col].ToString());
}
PDB.formatEnd("Detail");
PDB.transmit(null);
}
MessageBox.Show("Job " + lotInfo.SubmissionID + " uploaded successfully.", "AFM SA Host", MessageBoxButtons.OK, MessageBoxIcon.Information);
message = "Job " + lotInfo.SubmissionID + " - Data uploaded successfully. " + DateTime.Now;
submitMessage.Add(message);
}
catch (Exception exception)
{
message = "Job " + lotInfo.SubmissionID + " FAILED to upload data.";
submitMessage.Add(message);
submitMessage.Add(exception.Message);
Globals.Logger.Error(exception.Message);
}
return true;
This is my problem,
if (skiprows > 1) prompt message will appear and upload the data.
I want if (skiprows > 1) prompt message and will not upload.
Thank you.
This is just one way
bool CheckValidationByMEAS_TYPE(....)
{
. . . .
if (skipRows > 1)
{
MessageBox.Show(....);
return false;
}
}
. . . . . . . .
try
{
if (!CheckValidationByMEAS_TYPE(lotInfo.LotDataTable, MEAS_TYPE, lotInfo)
return;
}
catch (Exception exception)
{
. . . . .
}
I just want to log important things to a logfile just like a .txt.
I created a class ErrorHandling for this. I read error codes from CSV file and add the Text to Console / GUI. Now is the problem, i want to write to the error file from different UserControls, but the console is in the MainWindow. How can i just add the text to my output console from my Class?
This is my ErrorHandling class.
public class ErrorHandling
{
public static Action WriteErrorLog;
private static object writeLock = new object();
public enum errorState
{
INFO, WARNING, CRIT
}
public string getErrorString(int ErrorCode)
{
var errorString = string.Empty;
var reader = new StreamReader(File.OpenRead(#"errorCodes.csv"));
List<string> Codes = new List<string>();
List<string> Error = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
Codes.Add(values[0]);
Error.Add(values[3]);
}
var index = Codes.FindIndex(p => p == ErrorCode.ToString());
if (index == -1)
return "Unbekannter Fehler aufgetreten!";
else
return Error[index] + " (" + Codes[index] + ")";
}
public void addToLogFile(errorState error, int errorCode = 0, string errorText = null)
{
var errorTextResult = error.ToString();
if (errorCode == 0 && errorText == null)
{
return;
}
else if (errorCode != 0 && errorText != null)
{
errorTextResult += " - " + DateTime.Now.ToString();
errorTextResult += " : " + getErrorString(errorCode) + "\n";
errorTextResult += errorText;
}
else if (errorCode != 0 && errorText == null)
{
errorTextResult += " - " + DateTime.Now.ToString();
errorTextResult += " : " + getErrorString(errorCode);
}
else if ( errorCode == 0 && errorText != null)
{
errorTextResult += " - " + DateTime.Now.ToString() + " : ";
errorTextResult += errorText;
}
ThreadPool.QueueUserWorkItem(writeToLogFile, errorTextResult);
}
#region LogDatei schreiben
public static void writeToLogFile(object text)
{
try
{
if (!File.Exists(Properties.Settings.Default.LogFilePath))
{
using(var writer = File.AppendText(Properties.Settings.Default.LogFilePath))
writer.WriteLine(Properties.Settings.Default.LogFilePath, "LatikeManager Logfile " + DateTime.Now.ToString());
}
using (var writer = File.AppendText(Properties.Settings.Default.LogFilePath))
writer.WriteLine(Properties.Settings.Default.LogFilePath, text + "\n");
WriteErrorLog();
}
catch (Exception ex)
{
MessageBox.Show("Fehler beim schreiben der Log Datei : \n" + text + "\n" + ex.ToString());
}
}
#endregion
}
When i just add text from another UserControl, the Action does not fire because it is a new instance from ErrorHandling.
I just found an working resolution.
I am now using the trace method.
Just added this code to my App.conf
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="myTrace" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\LogFile\mytrace.log"></add>
</listeners>
</trace>
</system.diagnostics>
And then used
public static void writeToLogFile(object text)
{
Trace.Write(string.Format("{0}\r\n",text));
}
this Code in my ErrorHandling method. This worked great for me.
When trying to open a Linear Programming problem from text with Gurobi+C# it throws the error: 10012 Unable to open file "Maximize" for input.
Maximise is the first word of the text and when using
foreach (string s in args)
{
Console.WriteLine(s);
}
i get the correct output from the text file. Please help!
using System;
using Gurobi;
class lp_cs
{
static void Main(string[] args)
{
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
foreach (string s in args)
{
Console.WriteLine(s);
}
if (args.Length < 1)
{
Console.Out.WriteLine("Please Wait..");
return;
}
try
{
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
model.Optimize();
int optimstatus = model.Get(GRB.IntAttr.Status);
if (optimstatus == GRB.Status.INF_OR_UNBD)
{
model.GetEnv().Set(GRB.IntParam.Presolve, 0);
model.Optimize();
optimstatus = model.Get(GRB.IntAttr.Status);
}
if (optimstatus == GRB.Status.OPTIMAL)
{
double objval = model.Get(GRB.DoubleAttr.ObjVal);
Console.WriteLine("Optimal objective: " + objval);
}
else if (optimstatus == GRB.Status.INFEASIBLE)
{
Console.WriteLine("Model is infeasible");
model.ComputeIIS();
model.Write("model.ilp");
}
else if (optimstatus == GRB.Status.UNBOUNDED)
{
Console.WriteLine("Model is unbounded");
}
else
{
Console.WriteLine("Optimization was stopped with status = "
+ optimstatus);
}
model.Dispose();
env.Dispose();
}
catch (GRBException e)
{
Console.WriteLine("Hibakód: " + e.ErrorCode + ". " + e.Message);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
With
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
you are overwriting the args parameter of your main() method with an array of all lines of the input file. That's why in
GRBModel model = new GRBModel(env, args[0]);
args[0] contains a string with the first line of your LP file instead of the filename.
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.