I have started a new Console application in .net framework renamed it as ConsoleSpeechProgram and executed but
it is showing me
Exception thrown: 'System.IO.FileNotFoundException' in Microsoft.Speech.dll
Below link I am using for Speech to Text using Microsoft.Speech
https://msdn.microsoft.com/en-us/magazine/dn857362.aspx?f=255&MSPPError=-2147217396
using System;
using Microsoft.Speech.Recognition;
using Microsoft.Speech.Synthesis;
using System.Globalization;
namespace ConsoleSpeech
{
class ConsoleSpeechProgram
{
static SpeechSynthesizer ss = new SpeechSynthesizer();
static SpeechRecognitionEngine sre;
static bool done = false;
static bool speechOn = true;
static void Main(string[] args)
{
try
{
ss.SetOutputToDefaultAudioDevice();
Console.WriteLine("\n(Speaking: I am awake)");
ss.Speak("I am awake");
CultureInfo ci = new CultureInfo("en-us");
sre = new SpeechRecognitionEngine(ci);
sre.SetInputToDefaultAudioDevice();
sre.SpeechRecognized += sre_SpeechRecognized;
Choices ch_StartStopCommands = new Choices();
ch_StartStopCommands.Add("speech on");
ch_StartStopCommands.Add("speech off");
ch_StartStopCommands.Add("klatu barada nikto");
GrammarBuilder gb_StartStop = new GrammarBuilder();
gb_StartStop.Append(ch_StartStopCommands);
Grammar g_StartStop = new Grammar(gb_StartStop);
Choices ch_Numbers = new Choices();
ch_Numbers.Add("1");
ch_Numbers.Add("2");
ch_Numbers.Add("3");
ch_Numbers.Add("4");
GrammarBuilder gb_WhatIsXplusY = new GrammarBuilder();
gb_WhatIsXplusY.Append("What is");
gb_WhatIsXplusY.Append(ch_Numbers);
gb_WhatIsXplusY.Append("plus");
gb_WhatIsXplusY.Append(ch_Numbers);
Grammar g_WhatIsXplusY = new Grammar(gb_WhatIsXplusY);
sre.LoadGrammarAsync(g_StartStop);
sre.LoadGrammarAsync(g_WhatIsXplusY);
sre.RecognizeAsync(RecognizeMode.Multiple);
while (done == false) {; }
Console.WriteLine("\nHit <enter> to close shell\n");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
} // Main
static void sre_SpeechRecognized(object sender,
SpeechRecognizedEventArgs e)
{
string txt = e.Result.Text;
float confidence = e.Result.Confidence;
Console.WriteLine("\nRecognized: " + txt);
if (confidence < 0.60) return;
if (txt.IndexOf("speech on") >= 0)
{
Console.WriteLine("Speech is now ON");
speechOn = true;
}
if (txt.IndexOf("speech off") >= 0)
{
Console.WriteLine("Speech is now OFF");
speechOn = false;
}
if (speechOn == false) return;
if (txt.IndexOf("klatu") >= 0 && txt.IndexOf("barada") >= 0)
{
((SpeechRecognitionEngine)sender).RecognizeAsyncCancel();
done = true;
Console.WriteLine("(Speaking: Farewell)");
ss.Speak("Farewell");
}
if (txt.IndexOf("What") >= 0 && txt.IndexOf("plus") >= 0)
{
string[] words = txt.Split(' ');
int num1 = int.Parse(words[2]);
int num2 = int.Parse(words[4]);
int sum = num1 + num2;
Console.WriteLine("(Speaking: " + words[2] + " plus " +
words[4] + " equals " + sum + ")");
ss.SpeakAsync(words[2] + " plus " + words[4] +
" equals " + sum);
}
} // sre_SpeechRecognized
} // Program
} // ns
Related
so I have a lot of commands for my voice assistant that I programmed with visual studio (2019) c# System.Speech and now I want to add a command that deactivates the speech recognition until I say activate speech recognition.
I tried looking through the internet but I haven't found anything yet and I don't know a method myself that would be worth trying. Just deactivating every other command seperatly would be way to much effort.
Does anyone know how to do this or has an idea?
Thx for helping, phantomica
According to your description,when the shutdown command appears, you want to deactivate
speech recognition for every command except for activate speech recognition.
You can follow the steps below to achieve your requirements:
Set a global static variable speechOn, the default value is true.
Try to convert each recognized speech into text and store it in a variable. Then use this variable to compare with "speech on" and "speech off".
Determine the Boolean value of speechOn through the second step. If false, use return; to end the recognition method. If true, continue the recognition method.
My test code is as follows, it was successfully tested.
using System;
using System.Globalization;
using System.Speech.Recognition;
using System.Speech.Synthesis;
namespace ConsoleSpeech
{
class ConsoleSpeechProgram
{
static SpeechSynthesizer ss = new SpeechSynthesizer();
static SpeechRecognitionEngine sre;
static bool done = false;
static bool speechOn = true;
static void Main(string[] args)
{
try
{
ss.SetOutputToDefaultAudioDevice();
Console.WriteLine("\n(Speaking: I am awake)");
ss.Speak("I am awake");
CultureInfo ci = new CultureInfo("en-us");
sre = new SpeechRecognitionEngine(ci);
sre.SetInputToDefaultAudioDevice();
sre.SpeechRecognized += sre_SpeechRecognized;
Choices ch_StartStopCommands = new Choices();
ch_StartStopCommands.Add("speech on");
ch_StartStopCommands.Add("speech off");
ch_StartStopCommands.Add("klatu barada nikto");
GrammarBuilder gb_StartStop = new GrammarBuilder();
gb_StartStop.Append(ch_StartStopCommands);
Grammar g_StartStop = new Grammar(gb_StartStop);
Choices ch_Numbers = new Choices();
ch_Numbers.Add("1");
ch_Numbers.Add("2");
ch_Numbers.Add("3");
ch_Numbers.Add("4");
GrammarBuilder gb_WhatIsXplusY = new GrammarBuilder();
gb_WhatIsXplusY.Append("What is");
gb_WhatIsXplusY.Append(ch_Numbers);
gb_WhatIsXplusY.Append("plus");
gb_WhatIsXplusY.Append(ch_Numbers);
Grammar g_WhatIsXplusY = new Grammar(gb_WhatIsXplusY);
sre.LoadGrammarAsync(g_StartStop);
sre.LoadGrammarAsync(g_WhatIsXplusY);
sre.RecognizeAsync(RecognizeMode.Multiple);
while (done == false) {; }
Console.WriteLine("\nHit <enter> to close shell\n");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
} // Main
static void sre_SpeechRecognized(object sender,
SpeechRecognizedEventArgs e)
{
string txt = e.Result.Text;
float confidence = e.Result.Confidence;
Console.WriteLine("\nRecognized: " + txt);
if (confidence < 0.60) return;
if (txt.IndexOf("speech on") >= 0)
{
Console.WriteLine("Speech is now ON");
speechOn = true;
}
if (txt.IndexOf("speech off") >= 0)
{
Console.WriteLine("Speech is now OFF");
speechOn = false;
}
if (speechOn == false) return;
if (txt.IndexOf("klatu") >= 0 && txt.IndexOf("barada") >= 0)
{
((SpeechRecognitionEngine)sender).RecognizeAsyncCancel();
done = true;
Console.WriteLine("(Speaking: Farewell)");
ss.Speak("Farewell");
}
if (txt.IndexOf("What") >= 0 && txt.IndexOf("plus") >= 0)
{
string[] words = txt.Split(' ');
int num1 = int.Parse(words[2]);
int num2 = int.Parse(words[4]);
int sum = num1 + num2;
Console.WriteLine("(Speaking: " + words[2] + " plus " +
words[4] + " equals " + sum + ")");
ss.SpeakAsync(words[2] + " plus " + words[4] +
" equals " + sum);
}
} // sre_SpeechRecognized
} // Program
} // ns
Voice Recognition : Speech Recognition with .NET Desktop Applications
I am trying to make a server that will accept clients, and will communicate with them until they say "exit".
the problem is, after 5-8 clients, the server decides that he don't want to accept any more clients, and when a client is connected.. I simply don't see a "client connected : 123.242.123.13:92313" in the console.
anyone knows the problem?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace GatherServer
{
class Program
{
public static int connections = 0, team1 = 0, team2 = 0, playing = 12;
public static string lbleader = "";
public static bool isleader = false;
static TcpListener myList = new TcpListener(IPAddress.Any, 7846);
static void Listeners()
{
string charname = "";
bool inque = false;
Socket socketForClient = myList.AcceptSocket();
if(socketForClient.Connected)
{
Console.WriteLine("Client Connected: " + socketForClient.RemoteEndPoint);
NetworkStream networkStream = new NetworkStream(socketForClient);
StreamWriter streamWriter = new StreamWriter(networkStream);
StreamReader streamReader = new StreamReader(networkStream);
while (true)
{
string newString = streamReader.ReadLine();
if (newString.Contains("#") && inque == false)
{
if (newString.Contains("Leader"))
{
newString = newString.Replace("Leader","");
if (!isleader)
{
isleader = true;
lbleader = newString;
charname = lbleader;
Console.WriteLine(lbleader + " is the gather leader");
}
}
inque = true;
charname = newString;
connections++;
Console.WriteLine("connections: " + connections + " | from: "+charname);
}
if (newString == "exit")
{
if (charname == lbleader)
{
isleader = false;
Console.WriteLine(lbleader + " Left, there is not active leader");
}
else
Console.WriteLine(charname + " has left the game: "+socketForClient.RemoteEndPoint);
if (inque == true)
connections--;
break;
}
else
{
streamWriter.WriteLine(connections.ToString());
streamWriter.Flush();
if (connections == 12)
{
if (!isleader)
{
lbleader = charname;
Console.WriteLine(lbleader + " is the gather leader");
isleader = true;
}
Random rnd = new Random();
int team = rnd.Next(1, 3); // creates a number between 1 and 2
if(team == 1)
{
if (team1 < 6)
{
team1++;
Console.WriteLine(newString + " " + socketForClient.RemoteEndPoint + " assigned to Team 1");
streamWriter.WriteLine("team1"+lbleader);
streamWriter.Flush();
inque = false;
playing--;
break;
}
else
{
Console.WriteLine(newString + " " + socketForClient.RemoteEndPoint + " assigned to Team 2");
team2++;
streamWriter.WriteLine("team2" + lbleader);
streamWriter.Flush();
inque = false;
playing--;
break;
}
}
if(team == 2)
{
if (team2 < 6)
{
Console.WriteLine(newString + " " + socketForClient.RemoteEndPoint + " assigned to Team 2");
team2++;
streamWriter.WriteLine("team2" + lbleader);
streamWriter.Flush();
inque = false;
playing--;
break;
}
else
{
Console.WriteLine(newString + " " + socketForClient.RemoteEndPoint + " assigned to Team 1");
team1++;
streamWriter.WriteLine("team1" + lbleader);
streamWriter.Flush();
inque = false;
playing--;
break;
}
}
}
}
}
if (playing == 0)
{
connections = playing;
playing = 12;
lbleader = null;
isleader = false;
}
Console.WriteLine("playing:" + playing);
Console.WriteLine("connections: " + connections);
inque = false;
streamWriter.Close();
streamReader.Close();
networkStream.Close();
socketForClient.Close();
}
}
static void Main(string[] args)
{
myList.Start();
Console.WriteLine("Sever is up and running...");
for(int i=0; i<1000;i++)
{
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
}
}
}
}
Basically, what I want to do is to give each client a thread of its own. but after 5-8 connections, the server Socket socketForClient = myList.AcceptSocket(); not working, I think its because I am running out of threads.. but I have no clue why, there should be 1000 threads open when only 5 to 8 connections are made.
please help!
Found out what was the problem, I was highlighting some stuff in the server console, which caused the server to pause.
I have a C# console application which reads a folder for every 15 seconds using timer. It works fine,but it pauses after nearly 8 minutes and stops reading folder. Is there any reason for that?
using System;
sing System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Data;
using System.Data.OracleClient;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace FolderFileReader
{
class Program
{
static void Main()
{
if (SingleInstance.SingleApplication.Run() == false)
{
return;
}
Thread thread1 = new Thread(new ThreadStart(startNewBusiness));
thread1.Start();
Thread thread2 = new Thread(new ThreadStart(startEndorsement));
thread2.Start();
Thread thread3 = new Thread(new ThreadStart(startRenewal));
thread3.Start();
Thread thread4 = new Thread(new ThreadStart(startCancellation));
thread4.Start();
Console.ReadLine();
}
private static void startNewBusiness()
{
Timer t = new Timer(ProcessNewBusinessFolder, null, 0, 5000);
}
private static void startEndorsement()
{
Timer t2 = new Timer(ProcessEndorsementFolder, null, 0, 5000);
}
private static void startRenewal()
{
Timer t3 = new Timer(ProcessRenewalFolder, null, 0, 5000);
}
private static void startCancellation()
{
Timer t4 = new Timer(ProcessCancellationFolder, null, 0, 5000);
}
private static void ProcessNewBusinessFolder(Object o)
{
Console.Clear();
Console.WriteLine("Do not close this console (New Business).... ");
DirectoryInfo d = new DirectoryInfo(#"E:\HNBGI\SCN_DOCS\NEW\");
DirectoryInfo dest = new DirectoryInfo(#"E:\HNBGI\QUEUED_SCN_DOCS\NEW\");
if (!d.Exists)
{
return;
}
FileInfo[] Files = d.GetFiles("*.pdf");
string quotationNo = "";
string branchCode = "";
foreach (FileInfo file in Files)
{
quotationNo = file.Name;
DirectoryInfo newDir = null;
if (!Directory.Exists(dest.FullName + quotationNo.ToUpper()))
{
// newDir = Directory.CreateDirectory(dest.FullName + quotationNo.ToUpper() + "\\");
System.IO.Directory.CreateDirectory(dest.FullName + quotationNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
if (quotationNo.Length > 10)
{
branchCode = quotationNo.Substring(2, 3);
}
Console.WriteLine(quotationNo + " - " + branchCode);
try
{
File.Move(file.FullName, dest.FullName + quotationNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper() + "\\" + file.Name.ToUpper());
InsertNewBusiness(quotationNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper(), branchCode, "N");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Console.ReadKey();
GC.Collect();
}
private static void ProcessEndorsementFolder(Object o)
{
Console.Clear();
Console.WriteLine("Do not close this console (Endorsement).... ");
DirectoryInfo d = new DirectoryInfo(#"E:\HNBGI\SCN_DOCS\ENDORSEMENT\");
DirectoryInfo dest = new DirectoryInfo(#"E:\HNBGI\QUEUED_SCN_DOCS\ENDORSEMENT\");
if (!d.Exists)
{
return;
}
FileInfo[] Files = d.GetFiles("*.pdf");
string jobNo = "";
string branchCode = "";
foreach (FileInfo file in Files)
{
jobNo = file.Name;
DirectoryInfo newDir = null;
if (!Directory.Exists(dest.FullName + jobNo.ToUpper()))
{
System.IO.Directory.CreateDirectory(dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
Console.WriteLine(jobNo + " - " + branchCode);
try
{
File.Move(file.FullName, dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper() + "\\" + file.Name.ToUpper());
UpdateEndorsement(jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Console.ReadKey();
// Force a garbage collection to occur for this demo.
GC.Collect();
}
private static void ProcessRenewalFolder(Object o)
{
Console.Clear();
Console.WriteLine("Do not close this console (Renewal).... ");
DirectoryInfo d = new DirectoryInfo(#"E:\HNBGI\SCN_DOCS\RENEWAL\");
DirectoryInfo dest = new DirectoryInfo(#"E:\HNBGI\QUEUED_SCN_DOCS\RENEWAL\");
if (!d.Exists)
{
return;
}
FileInfo[] Files = d.GetFiles("*.pdf");
string jobNo = "";
string branchCode = "";
foreach (FileInfo file in Files)
{
jobNo = file.Name;
DirectoryInfo newDir = null;
if (!Directory.Exists(dest.FullName + jobNo.ToUpper()))
{
System.IO.Directory.CreateDirectory(dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
Console.WriteLine(jobNo + " - " + branchCode);
try
{
File.Move(file.FullName, dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper() + "\\" + file.Name.ToUpper());
UpdateRenewal(jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Console.ReadKey();
// Force a garbage collection to occur for this demo.
GC.Collect();
}
private static void ProcessCancellationFolder(Object o)
{
Console.Clear();
Console.WriteLine("Do not close this console (Cancellation).... ");
DirectoryInfo d = new DirectoryInfo(#"E:\HNBGI\SCN_DOCS\CANCELLATION\");
DirectoryInfo dest = new DirectoryInfo(#"E:\HNBGI\QUEUED_SCN_DOCS\CANCELLATION\");
if (!d.Exists)
{
return;
}
FileInfo[] Files = d.GetFiles("*.pdf");
string jobNo = "";
string branchCode = "";
foreach (FileInfo file in Files)
{
jobNo = file.Name;
DirectoryInfo newDir = null;
if (!Directory.Exists(dest.FullName + jobNo.ToUpper()))
{
// newDir = Directory.CreateDirectory(dest.FullName + quotationNo.ToUpper() + "\\");
System.IO.Directory.CreateDirectory(dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
string outputFileWithPath = "";
outputFileWithPath = dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper() + "\\" + file.Name.ToUpper();
Console.WriteLine(jobNo + " - " + branchCode);
try
{
File.Move(file.FullName, outputFileWithPath);
UpdateCancellation(jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Console.ReadKey();
GC.Collect();
}
public static void InsertNewBusiness(string quotationNo, string branchCode, string JobType)
{
\\Code to put Database Entry
}
public static void UpdateEndorsement(string jobNo)
{
\\Code to put Database Entry
}
public static void UpdateRenewal(string jobNo)
{
\\Code to put Database Entry
}
public static void UpdateCancellation(string jobNo)
{
\\Code to put Database Entry
}
}
}
Can anyone guess the issue?
Seems timers are collected by GC. Try to declare timers in outer scope.
private static Timer t;
private static Timer t2;
...and so on.
I am using visual studio 2010 professional on windows 7 (32 bit) to connect to RFID reader LRU3000 and i encounterd this exception
Method not found: 'IntPtr
System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(!!0)
kindly download the sample from the following link.
I searched the web much but i failed to know what is wrong.
Thanks In advance
NotificationSample.zip
and this is the code of the sample
this is the code of the sample :
the exception occurs at the line of code :
try
{
reader.StartAsyncTask(FedmTaskOption.ID_NOTIFICATION, this, taskOpt);
}
catch (FeReaderDriverException ex)
{
MessageBox.Show(ex.ToString());
}
public partial class NotificationSample : Form,FedmTaskListener
{
FedmIscReader reader;
FedmTaskOption taskOpt;
long count=1;
//declaration from delegatetyp
public delegate void DelegateDisplayRecSets(int recSets,
byte[] type,
string[] serialNumber,
string[] dataBlock,
string[] date,
string[] time,
byte[] antennaNr,
Dictionary<byte, FedmIscRssiItem>[] dicRSSI,
byte[] input,
byte[] state,
string ip);
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new NotificationSample());
}
//Constructor
public NotificationSample()
{
InitializeComponent();
try
{
reader = new FedmIscReader();
reader.SetTableSize(FedmIscReaderConst.BRM_TABLE, 255); // max 255 tag with each notification
taskOpt = new FedmTaskOption();
}
catch(FedmException ex)
{
MessageBox.Show(ex.ToString());
return;
}
}
//Actualy Time propertie
private string Time
{
get
{
DateTime d;
d = DateTime.Now;
string t;
// Get the Date
if (d.Month.ToString().Trim().Length == 1)
{
t = "0" + d.Month.ToString().Trim() + "/";
}
else
{
t = d.Month.ToString().Trim() + "/";
}
if (d.Day.ToString().Trim().Length == 1)
{
t += "0" + d.Day.ToString().Trim() + "/";
}
else
{
t += d.Day.ToString().Trim() + "/";
}
t += d.Year.ToString().Trim() + " ";
// Get the time
if (d.Hour.ToString().Trim().Length == 1)
{
t += "0" + d.Hour.ToString().Trim() + ":";
}
else
{
t += d.Hour.ToString().Trim() + ":";
}
if (d.Minute.ToString().Trim().Length == 1)
{
t += "0" + d.Minute.ToString().Trim() + ":";
}
else
{
t += d.Minute.ToString().Trim() + ":";
}
if (d.Second.ToString().Trim().Length == 1)
{
t += "0" + d.Second.ToString().Trim() + ".";
}
else
{
t += d.Second.ToString().Trim() + ".";
}
if (d.Millisecond.ToString().Trim().Length == 1)
{
t += "00" + d.Millisecond.ToString().Trim() + ".";
}
else if (d.Millisecond.ToString().Trim().Length == 2)
{
t += "0" + d.Millisecond.ToString().Trim() + ".";
}
else
{
t += d.Millisecond.ToString().Trim() + ".";
}
return t;
}
}
/*****************************Methods from interface FedmTaskListener*******************/
public void OnNewNotification(int iError,string IP,uint PortNr)
{
int i;
FedmBrmTableItem[] brmItems;
brmItems = (FedmBrmTableItem[])reader.GetTable(FedmIscReaderConst.BRM_TABLE);
//declaration from delegateobject
DelegateDisplayRecSets DisplayRecSetMethod = new DelegateDisplayRecSets(DisplayRecSets);
object[] obj = new object[11];
IAsyncResult result;
if(brmItems == null)
{
return;
}
string[] serialnumber = new string[brmItems.Length];
string[] dataBlock = new string[brmItems.Length];
string[] date = new string[brmItems.Length];
string[] time = new string[brmItems.Length];
byte[] type = new byte[brmItems.Length];
byte[] antennaNr = new byte[brmItems.Length];
byte[] input = new byte[brmItems.Length];
byte[] state = new byte[brmItems.Length];
byte[] dbsize = new byte[brmItems.Length];
Dictionary<byte, FedmIscRssiItem>[] dicRSSI = new Dictionary<byte, FedmIscRssiItem>[brmItems.Length];
long dbn;
byte dbadr;
string db;
for (i = 0; i < brmItems.Length; i++)
{ // serial number
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_SNR))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_SNR, out serialnumber[i]);
}
// data blocks
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_RxDB))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_DBN, out dbn);
brmItems[i].GetData(FedmIscReaderConst.DATA_DB_ADR, out dbadr);
int j;
for (j = dbadr; j < dbn; j++)
{
brmItems[i].GetData(FedmIscReaderConst.DATA_RxDB, j, out db);
dataBlock[i] = dataBlock[i] + db + "\r\n"+"\t\t";
}
}
// Transponder Type
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TRTYPE))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_TRTYPE, out type[i]);
}
// Date
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_DATE))
{
date[i] = brmItems[i].GetReaderTime().GetDate();
}
// Time
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER))
{
time[i] = brmItems[i].GetReaderTime().GetTime();
}
// Antenna number
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_NR))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_ANT_NR, out antennaNr[i]);
}
// RSSI value
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_RSSI))
{
dicRSSI[i] = brmItems[i].GetRSSI();
}
else
{
dicRSSI[i] = new Dictionary<byte, FedmIscRssiItem>();
}
// Input
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_INPUT))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_INPUT, out input[i]);
brmItems[i].GetData(FedmIscReaderConst.DATA_STATE, out state[i]);
}
}
obj[0] = brmItems.Length;
obj[1] = type;
obj[2] = serialnumber;
obj[3] = dataBlock;
obj[4] = date;
obj[5] = time;
obj[6] = antennaNr;
obj[7] = dicRSSI;
obj[8] = input;
obj[9] = state;
obj[10] = IP;
result = (IAsyncResult)Invoke(DisplayRecSetMethod, obj);
}
public void OnNewApduResponse(int iError)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewQueueResponse(int iError)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewSAMResponse(int iError, byte[] responseData)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewReaderDiagnostic(int iError,string IP,uint PortNr)
{
}
public int OnNewMaxAccessEvent(int iError, string maxEvent, string ip, uint portNr)
{
throw new Exception("The method or operation is not implemented.");
}
public int OnNewMaxKeepAliveEvent(int iError, uint uiErrorFlags, uint TableSize, uint uiTableLength, string ip, uint portNr)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewTag(int iError)
{
}
public void onNewPeopleCounterEvent(uint counter1, uint counter2, uint counter3, uint counter4, string ip, uint portNr, uint busAddress)
{
throw new Exception("The method or operation is not implemented.");
}
/************************************ENDE***********************************************/
/******************************************************Asynchrone method*****************************************************************************************************/
public void DisplayRecSets( int recSets,
byte[] type,
string[] serialNumber,
string[] dataBlock,
string[] date,
string[] time,
byte[] antennaNr,
Dictionary<byte, FedmIscRssiItem>[] dicRSSI,
byte[] input,
byte[] state,
string ip)
{
Dictionary<byte, FedmIscRssiItem> RSSIval;
FedmIscRssiItem RSSIitem;
int i;
bool bcheck;
byte antNo;
string dr;
string tr = "";
FedmBrmTableItem[] brmItems;
brmItems = (FedmBrmTableItem[])reader.GetTable(FedmIscReaderConst.BRM_TABLE);
tr += "-----------------------------------------------------------------" + "\r\n";
tr += "DATE/TIME: " + Time.ToString() + "\r\n";
tr += "-----------------------------------------------------------------" + "\r\n";
count = 1;
for (i = 0; i < recSets; i++)
{
tr += (count).ToString().Trim() + "." + " TRANSPONDER" + "\r\n";
count = count + 1;
if (type[i] >= 0)
{
//just the two last bit
dr = "0x" + FeHexConvert.IntegerToHexString(type[i]).Substring(FeHexConvert.IntegerToHexString(type[i]).Length - 2, 2);
tr += "TR-TYPE:" + "\t" + dr.ToString() + "\r\n";
}
// Output SeriaNo.
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_SNR))
{
if (serialNumber[i] != null)
{
tr += "SNR:" + "\t\t" + serialNumber[i].ToString() + "\r\n";
}
}
// Output Data Blocks
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_RxDB))
{
if (dataBlock[i] != null)
{
tr += "DB:" + "\t\t" + dataBlock[i].ToString() + "\r\n";
}
}
// Output Date
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER) || brmItems[i].IsDataValid(FedmIscReaderConst.DATA_DATE))
{
if (date[i] != null)
{
tr += "DATE:" + "\t\t" + date[i].ToString() + "\r\n";
}
}
// Output Time
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER))
{
if (time[i] != null)
{
tr += "TIME:" + "\t\t" + time[i].ToString() + "\r\n";
}
}
// It is possible either to output the ANT_NR or the RSSI value (this is also important for the reader config!)
// Output ANT_NR
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_NR))
{
tr += "ANT. NR:"+"\t\t" + (antennaNr[i].ToString()).Trim() + "\r\n";
}
// It is possible either to output the ANT_NR or the RSSI value (this is also important for the reader config!)
// Output RSSI
if (dicRSSI.Length > 0)
{
if (dicRSSI[i] != null)
{
RSSIval = dicRSSI[i];
for(antNo = 1; antNo<FedmBrmTableItem.TABLE_MAX_ANTENNA; antNo++)
{
bcheck = RSSIval.TryGetValue(antNo, out RSSIitem);
if (!bcheck)
continue;
tr += "RSSI of AntNr. " + "\t" + antNo.ToString() + " is " + "-" + RSSIitem.RSSI.ToString() + "dBm" + "\r\n";
}
}
}
// Output INPUT
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_INPUT))
{
tr += "INPUT:" + "\t\t" + (input[i].ToString()).Trim() + "\r\n";
tr += "STATE:" + "\t\t" + (state[i].ToString()).Trim() + "\r\n";
}
// Output IP where notification data comes from
tr += "FROM:" + "\t\t" + ip + "\r\n";
tr += "" + "\r\n";
tr += "" + "\r\n";
}
this.textBoxData.AppendText(tr);
tr = "";
}
/**********************************************************ENDE***************************************************************************************************************/
/**************************************************Buttons**********************************************/
private void buttonListen_Click(object sender, EventArgs e)
{
if(this.buttonListen.Text == "Listen")
{
this.buttonListen.Text = "Cancel";
taskOpt.IPPort = Convert.ToInt16(this.textBoxPortNr.Text);
if(this.checkBoxAkn.Checked)
{
taskOpt.NotifyWithAck = 1;
}
else
{
taskOpt.NotifyWithAck = 0;
}
//Start from intern Thread
try
{
reader.StartAsyncTask(FedmTaskOption.ID_NOTIFICATION, this, taskOpt);
}
catch (FeReaderDriverException ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
this.buttonListen.Text = "Listen";
//End from intern thread
int val;
reader.ResetTable(FedmIscReaderConst.BRM_TABLE);
val=reader.CancelAsyncTask();
//case Deadlocks ->-4084
if (val < 0)
{
reader.CancelAsyncTask();
}
}
}
private void buttonClear_Click(object sender, EventArgs e)
{
this.textBoxData.Clear();
count = 1;
}
/***********************************************************Ende******************************************/
private void NotificationSample_FormClosing(object sender, FormClosingEventArgs e)
{
reader.CancelAsyncTask();
Application.Exit();
}
}
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.