Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MSMQ系统。消息传递资源使用率高_C#_Scheduled Tasks_Msmq - Fatal编程技术网

C# MSMQ系统。消息传递资源使用率高

C# MSMQ系统。消息传递资源使用率高,c#,scheduled-tasks,msmq,C#,Scheduled Tasks,Msmq,我制作了一个C#控制台应用程序,它使用定时器每10秒连接一次MSMQ,将数据插入Oracle数据库。但问题是,它登录和注销到域,并创建高CPU,还创建了安全审计日志,这非常浪费我的资源 我的控制台应用程序按照任务计划运行。代码如下 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Messaging; using System.Xml; using

我制作了一个C#控制台应用程序,它使用定时器每10秒连接一次MSMQ,将数据插入Oracle数据库。但问题是,它登录和注销到域,并创建高CPU,还创建了安全审计日志,这非常浪费我的资源

我的控制台应用程序按照任务计划运行。代码如下

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("&", "&amp;").Replace("<", "&lt;")
                                       .Replace(">", "&gt;").Replace("'", "&apos;");
            if (lenthToReplace > 0) xmlData = xmlData.Replace(data, formattedData);
            return xmlData;
        }
        catch (Exception ex)
        {
            Log("From ReplaceSpecialChars -- " + ex.Message);
            return "";
        }
    }

}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用系统消息传递;
使用System.Xml;
使用System.IO;
使用系统计时器;
使用Oracle.DataAccess.Client;
使用系统数据;
名称空间MSMQ_新闻
{
班级计划
{
专用静态系统定时器定时器定时器;
静态void Main(字符串[]参数)
{
尝试
{
//创建一个间隔为10秒的计时器。
aTimer=新系统.定时器.定时器(60000);//10000
//连接计时器的已用事件。
aTimer.Appead+=新的ElapsedEventHandler(OnTimedEvent);
//将间隔设置为2秒(2000毫秒)。
//a时间间隔=10000;
aTimer.Enabled=true;
aTimer.Start();
Console.WriteLine(“按Enter键退出程序”);
Console.ReadLine();
}
捕获(例外情况除外)
{
日志(“从主--”+ex.Message);
}
}
私有静态void OnTimedEvent(对象源,ElapsedEventArgs e)
{
//万一有人想继承你的类并将其锁定。。。
对象_挂锁=新对象();
尝试
{
停止();
锁(挂锁)
{
WriteLine(“在{0}时引发了经过的事件”,例如SignalTime);
ProcessQueueMsgs();
}
}
捕获(例外情况除外)
{
日志(“来自OnTimedEvent--”+ex.Message);
}
最后
{
aTimer.Start();
}
}
私有静态void ProcessQueueMsgs()
{
尝试
{
而((DateTime.Now.Hour>=06)
&&(DateTime.Now.Hour 0)
{
OracleParameter pTRUNCATE=新的OracleParameter(“P_TABLE_NAME”,OracleDbType.Varchar2);
pTRUNCATE.Value=“公司新闻”;
数据库操作(CommandType.StoredProcess,“TRUNCATE_TABLE”,pTRUNCATE);
}
foreach(新闻标题列表中的XmlNode新闻)
{
XmlNodeList newsIdList=news.SelectNodes(“newId”);
SQL=“插入公司新闻(NewsID、NewsID、NEWSSTATUS、LANGUAGE\u CD、SEC\u CD、RELEASEDATE、RELEASETIME、TITLE、STG\u TIME)值(”;
foreach(newsIdList中的XmlNode newsId)
{
SQL+=“'”+newsId[“id”]。InnerText+“,”;
SQL+=“”+newsId[“seqNo”]。InnerText+,”;
}
SQL+=“'”+新闻[“新闻状态”]。InnerText+“,”;
XmlNodeList newsItemList=news.SelectNodes(“newsItem”);
foreach(newsItemList中的XmlNode newsItem)
{
SQL+=“'”+新闻项[“languageId”]。InnerText+“,”;
如果(新闻项[“重新编码”]!=null)
SQL+=“'”+新闻项[“重新编码”]。InnerText+“,”;
其他的
SQL+=“''”;
XmlNodeList releaseTimeList=新闻项。选择节点(“releaseTime”);
foreach(releaseTimeList中的XmlNode releaseTime)
{
SQL+=“TO_DATE(““+releaseTime[“DATE”]。InnerText+”,“YYYYMMDD”),”;
SQL+=“”+releaseTime[“time”]。InnerText+,”;
}
}
XmlNodeList arabicFieldsList=news.SelectNodes(“arabicFields”);
foreach(arabicFields列表中的XmlNode arabicFields)
{
SQL++=“'”+还原特殊字符(arabicFields[“title_AR”].InnerText)+“',”;
}
SQL++=“截止日期(“+dt.ToString()+”,“MM/DD/YYYY HH12:MI:SS PM”)”;
数据库操作(CommandType.Text、SQL、null);
WriteLine(“头:“+DateTime.Now.ToString());
}
如果(SQL!=“”)//RecordCount(“从公司信息中选择计数(*))>0
{
OracleParameter pREFRESH=新的OracleParameter(“P_TABLE_NAMEs”,OracleDbType.Varchar2);
pREFRESH.Value=“公司新闻”;
数据库操作(CommandType.StoredProcess,“刷新所有”,预刷新);
}
}
捕获(例外情况除外)
{
日志(“来自LoadNewsHeader--”+ex.Message);
}
}
私有静态void LoadNewsDetail(字符串文本,DateTime dt)
{
尝试
{
//字符串fileName=“newsdeail.xml”;
text=text.Replace(“,”\n\t\t”);
//text=createXMLFile(文件名);
//text=text.Replace(“,”\n\t\t”);
XmlDocument _xmlDoc=LoadXMLDoc(文本);
字符串SQL=“”;
XmlNodeList newsList=_xmlDoc.SelectNodes(“新闻/新闻报道”);
如果(newsList.Count>0)
{
OracleParameter pTRUNCATE=新的OracleParameter(“P_TABLE_NAME”,OracleDbType.Varchar2);
pTRUNCATE.Value=“公司新闻详情”;
数据库操作(CommandType.StoredProcess,“TRUNCATE_TABLE”,pTRUNCATE);
}
foreach(新闻列表中的XmlNode新闻)
{
XmlNodeList newsIdList=news.SelectNodes(“newId”);
SQL=“插入公司新闻详细信息(新闻ID、新闻ID、新闻序号、新闻文本1、新闻文本2、STG时间)值(”;
foreach(newsIdList中的XmlNode newsId)
{
SQL+=“”+newsId[“id”]。InnerText+,”;
private static MessageQueue mqNewsHeader = new MessageQueue(@".\q_ws_ampnewsheaderrep");
private static MessageQueue mqNewsDetails = new MessageQueue(@".\q_ws_ampnewsrep");
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;
    }