my problem is that i have a WCF Service and multip
le clients can connect/subscribe to that service and get all Random Data
trough Callback with the service...a Timer starts when a clients subscribed to the service, the thing is that every client then gets all not the same data but thats what i want to achieve...what am i doing wrong?
This is what happens when one client subscribed to the service:
public SubscribeResult Subscribe()
{
SubscribeResult retVal = new SubscribeResult();
try
{
retVal.ClientID = Guid.NewGuid().ToString();
clientID = retVal.ClientID;
ServiceCallback = OperationContext.Current.GetCallbackChannel<ITraceCallback>();
ti = new Timer();
ti.Elapsed += Ti_Elapsed;
ti.Interval = 1000;
ti.Enabled = true;
ti.Start();
retVal.Success = true;
SubscribeClientList.Add(new SubscribeItem {CLIENTID = clientID, SENT = true });
connectedClients += 1;
}
catch (Exception ex)
{
retVal.Success = false;
Console.WriteLine("Something went horribly wrong! \n" + ex.Message);
}
return retVal;
}
And this is what happens when the timer hits zero :
private void Ti_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
if (isSending == false)
{
isSending = true;
// generate message
CreateRandomString crs = new CreateRandomString();
string msg = crs.CreateString(rnd.Next(15, 25));
// increase entry
entry += 1;
// create timestamp of creation
DateTime creation = DateTime.Now;
// generate level
int muchwow = rnd.Next(1, 4);
string lvl = "undefined";
switch (muchwow)
{
case 1:
lvl = "Error";
break;
case 2:
lvl = "Warning";
break;
case 3:
lvl = "Information";
break;
}
bool sucess = ServiceCallback.Message(entry, creation, lvl, msg);
if (sucess == true)
{
CreateRandomString messagePreview = new CreateRandomString();
string prev = messagePreview.TruncString(msg, 20);
Console.WriteLine("[" + DateTime.Now + "] : [" + clientID + "] : " + "'" + prev + "' : " + "(" + lvl + ")");
sucess = false;
}
isSending = false;
}
Related
Have a utility I wrote that checks (among other things) the last time a set of servers was rebooted. This works great as long as the servers are all within my domain and the user launching the app have rights on the servers. Added a section where the user can specify alternative credentials, in our case specifically to deal with another domain. The credentials I am feeding into have domain admin rights on the destination domain, yet my code is getting an Access Denied (Unauthorized Access) error.
thanks!
private void btnLastReboot_Click(object sender, EventArgs e)
{
ConnectionOptions conOpts = new ConnectionOptions();
if (selectedList.Count > 0)
{
Cursor currentCursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
stripProgress.Visible = true;
stripProgress.Minimum = 0;
stripProgress.Maximum = selectedList.Count();
stripProgress.Step = 1;
stripProgress.Value = 0;
rtfOut.SelectionTabs = new int[] { 100, 200 };
rtfOut.Text = "";
var sq = new SelectQuery("Win32_OperatingSystem");
if (prefs.useCurrentUser == true)
{
// Setting all fields to NULL causes current user info to be used
conOpts.Username = null;
conOpts.Password = null;
conOpts.Authority = null;
}
else
{
conOpts.Username = prefs.userName;
conOpts.Password = prefs.password.ToString();
conOpts.Authority = "ntlmdomain:" + prefs.domain;
}
foreach (ServerList anEntry in selectedList)
{
stripProgress.Value++;
try
{
var mgmtScope = new ManagementScope("\\\\" + anEntry.ServerName + "\\root\\cimv2", conOpts);
mgmtScope.Connect();
var mgmtSearcher = new ManagementObjectSearcher(mgmtScope, sq);
foreach (var item in mgmtSearcher.Get())
{
var lastBoot = item.GetPropertyValue("LastBootUpTime").ToString();
DateTime lboot = ManagementDateTimeConverter.ToDateTime(lastBoot);
rtfOut.Text += anEntry.ServerName + "\t";
if(anEntry.ServerName.Length <= 9)
{
rtfOut.Text += "\t";
}
rtfOut.Text += lboot.ToLongDateString() + " (" + lboot.ToLongTimeString() + ")\r\n";
}
}
catch (Exception ex)
{
if (ex is UnauthorizedAccessException)
{
rtfOut.Text += anEntry.ServerName + "\t <Access Denied>\r\n";
}
else
{
rtfOut.Text += anEntry.ServerName + "\t <not responding>\r\n";
}
}
}
stripProgress.Visible = false;
Cursor.Current = currentCursor;
}
}
Had to sleep on it, but the answer finally hit me in the shower...
I store the password the user provides in a SecureString variable, but the ConnectionOptions' password field expects the value as a clear string. I was able to test this by temporarily hard coding a password in, which then worked. The final solution was to convert the SecureString to a clear string and then assign it to the ConnectionOption.
If anyone is curious, I used this bit to convert the password back:
string password = new System.Net.NetworkCredential(string.Empty, securePassword).Password;
The code uses the wmi component in semi-synchronous mode to monitor events on a remote computer.
Everything works correctly until the network connection between the client and the server is interrupted.
In this case the program remains frozen in the line:
ManagementBaseObject e = watcher.WaitForNextEvent ();
and the timeout does not work.
How can I manage the connection break correctly?
Thank you
static void Main(string[] args)
{
ConnectionOptions con1 = new ConnectionOptions();
con1.Username = networkUser;
con1.Password = networkPassword;
con1.Impersonation = ImpersonationLevel.Impersonate;
con1.EnablePrivileges = true;
con1.Authentication = AuthenticationLevel.PacketPrivacy;
ManagementPath mp1 = new ManagementPath(#"\\" + networkPath + #"\" + #"root\cimv2");
try
{
string queryString =
"SELECT * " +
"FROM __InstanceOperationEvent " +
"WITHIN 5 " +
"WHERE TargetInstance ISA 'Win32_Process' ";
WqlEventQuery wql = new WqlEventQuery(queryString);
ManagementScope Scope = new ManagementScope(mp1, con1);
Scope.Connect();
// create the watcher and start to listen
ManagementEventWatcher watcher = new ManagementEventWatcher();
watcher.Query = wql;
watcher.Scope = Scope;
watcher.Options.Timeout = TimeSpan.FromSeconds(5);
keepGoing = true;
int nError = 0;
while (keepGoing)
{
try
{
ManagementBaseObject e = watcher.WaitForNextEvent();
switch (e.ClassPath.ClassName)
{
case ("__InstanceDeletionEvent"):
{
keepGoing = false;
break;
}
default:
{
Console.WriteLine("Evento non gestito : " + e.ClassPath.ClassName);
break;
}
}
}
catch (System.Management.ManagementException e)
{
if (e.ErrorCode != ManagementStatus.Timedout)
throw;
}
}
watcher.Stop();
}
catch (Exception ex)
{
Console.WriteLine("Errore: " + ex.Message);
Console.ReadLine();
}
}
I answer myself.
Setting the watcher timeout to:
watcher.Options.Timeout = new TimeSpan (0, 0, 0, 0, 1);
I use the following code for reading new messages from Telegram chat:
public async Task GatherChatHistory(string channelName, string ch_id, string mid, int offset = 0, int minId = 0, int maxId = -1, int limit = 100)
{
Log.Info(Tag, "In GatherChatHistory Start");
TelegramClient client = CreateClient();
await InitializeAndAuthenticateClient(client);
int maximal = Convert.ToInt32(mid);
Log.Info(Tag, "In GatherChatHistory Before GetUserDialogAsync");
try
{
var dialogs = (TLDialogs)await client.GetUserDialogsAsync();
var chat = dialogs.chats.lists
.OfType<TLChat>()
.FirstOrDefault(c => c.title == channelName);
Log.Info(Tag, "In GatherChatHistory After GetUserDialogAsync " + (chat != null));
if (chat != null)
{
Log.Info(Tag, "Chat != null, " + channelName);
try
{
var tlAbsMessages =
await client.GetHistoryAsync(
new TLInputPeerChat { chat_id = chat.id }, offset,
minId, maxId, limit);
Log.Info(Tag, "After GetHistoryAsync");
var tlChannelMessages = (TLMessages)tlAbsMessages;
Log.Info(Tag, "GatherChatHistory Messages count = " + (tlChannelMessages.messages.lists.Count - 1));
for (var index = 0; index < tlChannelMessages.messages.lists.Count - 1; index++)
{
var tlAbsMessage = tlChannelMessages.messages.lists[index];
Log.Info(Tag, "Message Type = " + tlAbsMessage.GetType());
if (tlAbsMessage.GetType().ToString().Equals("TeleSharp.TL.TLMessageService"))
continue;
var message = (TLMessage)tlAbsMessage;
if (message.id == maximal)
{
Log.Info(Tag, "GatherChatHistory Chat_id = " + channelName + " maximal was reached");
break;
}
if (message.id <= maximal)
{
Log.Info(Tag, "GatherChatHistory Chat_id = " + channelName + " message.id = " + message.id + " maxid = " + maximal);
continue;
}
if (message.media == null)
{
Log.Info(Tag, "Message ID = " + message.id);
Log.Info(Tag, "Chat ID = " + chat.id);
Log.Info(Tag, "Content = " + message.message);
await AddNewMessageToDatabase(channelName, ch_id, message.message, null, message.from_id.GetValueOrDefault(), message.id);
}
else
{
switch (message.media.GetType().ToString())
{
case "TeleSharp.TL.TLMessageMediaPhoto":
var tLMessageMediaPhoto = (TLMessageMediaPhoto)message.media;
var photo = (TLPhoto)tLMessageMediaPhoto.photo;
var photoSize = photo.sizes.lists.OfType<TLPhotoSize>().Last();
TLFileLocation tf = (TLFileLocation)photoSize.location;
var resFile = await client.GetFile(new TLInputFileLocation
{
local_id = tf.local_id,
secret = tf.secret,
volume_id = tf.volume_id
}, 0);
using (var ms = new MemoryStream(resFile.bytes))
{
byte[] byteArr = ms.ToArray();
string base64image = Convert.ToBase64String(byteArr);
Log.Info(Tag, "Caption = " + tLMessageMediaPhoto.caption);
Log.Info(Tag, "Base64 Image = " + base64image);
await AddNewMessageToDatabase(channelName, ch_id, tLMessageMediaPhoto.caption, base64image, message.from_id.GetValueOrDefault(), message.id);
}
break;
case "TeleSharp.TL.TLMessageMediaDocument":
var tLMessageMediaDocument = (TLMessageMediaDocument)message.media;
break;
case "TeleSharp.TL.TLMessageMediaWebPage":
var tLMessageMediaWebPage = (TLMessageMediaWebPage)message.media;
string url = string.Empty;
if (tLMessageMediaWebPage.webpage.GetType().ToString() != "TeleSharp.TL.TLWebPageEmpty")
{
var webPage = (TLWebPage)tLMessageMediaWebPage.webpage;
url = webPage.url;
}
break;
}
}
}
}
catch (Exception e)
{
Logger.Error("Telegram Chat History exception: " + e.Message);
Log.Error(Tag, "Telegram Chat History exception: " + e.Message);
Log.Error(Tag, "Telegram Chat History StackTrace = " + e.ToString());
}
}
else
Log.Info(Tag, "Chat == null");
}
catch (Exception e)
{
Log.Error(Tag, "ReadUserAsync Error : " + e.Message);
}
}
I check chat for new messages one time per minute. I don't have any problems with text messages, all of them I read without any problem. Also I can read one photo, but only one per time. If in chat there are more than one photo or photo and text messages after reading photo TLSharp throws exception:
[MessagingService:TelegramBridge] Telegram Chat History exception: msg_seqno
too low (the server has already received a message with a lower msg_id but
with either a higher or an equal and odd seqno)
[MessagingService:TelegramBridge] Telegram Chat History StackTrace =
System.InvalidOperationException: msg_seqno too low (the server has already
received a message with a lower msg_id but with either a higher or an equal
and odd seqno)
[MessagingService:TelegramBridge] at
TLSharp.Core.Network.MtProtoSender.HandleBadMsgNotification (System.UInt64
messageId, System.Int32 sequence, System.IO.BinaryReader messageReader)
[0x0009f] in <24dee86ac15149c89ccf3cac229b439d>:0
[MessagingService:TelegramBridge] at
TLSharp.Core.Network.MtProtoSender.processMessage (System.UInt64 messageId,
System.Int32 sequence, System.IO.BinaryReader messageReader,
TeleSharp.TL.TLMethod request) [0x00182] in
<24dee86ac15149c89ccf3cac229b439d>:0
[MessagingService:TelegramBridge] at TLSharp.Core.Network.MtProtoSender+
<Receive>d__9.MoveNext () [0x000bb] in <24dee86ac15149c89ccf3cac229b439d>:0
Can anybody help me with this problem?
UPD
I localize the place of the error:
var resFile = await client.GetFile(new TLInputFileLocation
{
local_id = tf.local_id,
secret = tf.secret,
volume_id = tf.volume_id
}, 0);
but I still don't know what to do...
UPD
This is main function:
async Task<int> WriteMessagesFromChannels()
{
Log.Info(Tag, "In WriteMessagesFromChannels");
var url = "http://" + MainActivity.Host + ":" + MainActivity.Port + MainActivity.Url + "/groups?page=1&pageSize=10000";
Log.Info(Tag, "URL = " + url);
var json = FetchServerData(url);
if (json == null)
{
Log.Info(Tag, "In WriteMessagesFromChannels: JSON = NULL");
return -1;
}
var obj = JObject.Parse(json);
var groups = JsonConvert.DeserializeObject<TelegramChannel[]>(obj["data"]["items"].ToString());
Log.Info(Tag, "In WriteMessagesFromChannels: size = " + groups.Length);
if (groups != null)
{
foreach (var gr in groups)
{
Log.Info(Tag, "Group name = " + gr.name + ", monitor = " + gr.monitor);
if (gr.ischannel == true || gr.monitor == false)
continue;
string maxid = ReadMaxId(gr.id);
if (maxid == "")
continue;
Log.Info(Tag, "In WriteMessagesFromChannels: MAXID = " + maxid);
await ReadMessagesFromChat(gr.name, gr.id, maxid);
Thread.Sleep(3000);
}
Log.Info(Tag, "In WriteMesasagesFromChannels: CYCLE IS FINISHED");
}
else
{
Log.Info(Tag, "In WriteMessagesFromChannels: GROUPS = NULL");
}
return 1;
}
async Task<int> ReadMessagesFromChat(string name, string ch_id, string maxid)
{
Log.Info(Tag, "In ReadMessagesFromChat");
//await bridge.GetPhotoFromChannel(name);
await bridge.GatherChatHistory(name, ch_id, maxid);
return 1;
}
I am having a problem this is my code`using System;
namespace cm18b
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(40000);
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
string machineID = config.AppSettings.Settings["MachineID"].Value;
//MessageBox.Show(machineID);
double time = Convert.ToDouble(config.AppSettings.Settings["time"].Value);
System.Timers.Timer timer = new System.Timers.Timer(time);
timer.Elapsed += OnTimer;
timer.Enabled = true;
this.WindowState = FormWindowState.Minimized;
}
private void OnTimer(object source, ElapsedEventArgs e)
{
var timer = (System.Timers.Timer)source;
timer.Stop();
//MessageBox.Show("trying");
BuildTransactionXML();
timer.Start();
}
public bool SendFTP(string file_name)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
String source = config.AppSettings.Settings["sourcelocation"].Value + "/" + file_name; //Change to new file name
String ftpusername = config.AppSettings.Settings["ftpusername"].Value;
String ftppassword = config.AppSettings.Settings["ftppassword"].Value;
String ftpfullpath = config.AppSettings.Settings["ftpurl"].Value + "/" + file_name;
try
{
string filename = Path.GetFileName(source);
//string ftpfullpath = ftpurl;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
return true;
}
catch (WebException ex)
{
WriteLog(ex);
return false;
}
}
public void BuildTransactionXML()
{
string xmlString = "";
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
string transactioncounter = config.AppSettings.Settings["transactioncounter"].Value;
string BustaA = config.AppSettings.Settings["bagnumber"].Value;
string cm18string = ConfigurationManager.ConnectionStrings["CM18String"].ConnectionString;
SqlConnection con = null;
try
{
con = new SqlConnection(cm18string);
if (con.State != System.Data.ConnectionState.Open)
{
con.Open();
}
string currency = "";
string device = "";
string result = "";
string symbol = "";
string type = "";
string type1 = "";
string file_name = "";
string user = "";
string filesaved = "";
string date = "";
string time = "";
string cassette = "";
SqlCommand cmd = new SqlCommand("SELECT [IDP],[DateTimeOperazione],[Importo],[TipoOperazione],[Banconote_E500],[Banconote_E200],[Banconote_E100],[Banconote_E50],[Banconote_E20],[Banconote_E10],[Banconote_E5],[BustaA] FROM [DataBos].[dbo].[Operazioni] join [DataBos].[dbo].[Buste] on [DataBos].[dbo].[Operazioni].SessioneRef = [DataBos].[dbo].[Buste].SessioneRef where TipoOperazione IN ('161','3', '1') and IDP > #idp", con);
cmd.Parameters.Add("#idp", transactioncounter);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
string filecounter = config.AppSettings.Settings["filecounter"].Value;
switch (rd.GetInt32(3))
{
case 161:
type = "out";
type1 = "out";
break;
case 1:
type = "outb";
type1 = "outb";
break;
case 3:
type = "in";
type1 = "in";
config.AppSettings.Settings["bagnumber"].Value = rd.GetString(11);
config.Save(ConfigurationSaveMode.Modified);
BustaA= rd.GetString(11);
break;
default:
type = "";
break;
}
cassette = BustaA;
currency = "Euro";
symbol = "€";
date = rd.GetDateTime(1).ToString("M/DD/YYYY");
time = rd.GetDateTime(1).ToString();
device = config.AppSettings.Settings["MachineId"].Value;
file_name = device + "_" + type1 + ".xml";
xmlString = "";
xmlString = "<transaction><device>" + device + "</device><status>" + #type1 + "</status><currency><description>" + currency + "</description><symbol>" + symbol + "</symbol></currency><date_time><date>" + date + "</date><time>" + time + "</time></date_time><cassette>" + cassette + "</cassette><<filename>" + file_name + "</filename>";
file_name = device + "_" + type1 + "_" + filecounter + ".xml";
if (type == "in")
{
config.AppSettings.Settings["HasMoney"].Value = "True";
int ttype = 0;
int value = 0;
int quantity = 0;
for (int i =1 ; i<=7;i++)
{
ttype = 0;
value = 0;
quantity = 0;
switch(i)
{
case 1:
ttype = 500;
break;
case 2:
ttype = 200;
break;
case 3:
ttype = 100;
break;
case 4:
ttype = 50;
break;
case 5:
ttype = 20;
break;
case 6:
ttype = 10;
break;
case 7:
ttype = 5;
break;
}
quantity = rd.GetInt32(i+4);
value = quantity * ttype;
if(quantity !=0)
{
xmlString = xmlString + "<transactionline type = \"" + ttype.ToString("##########0.00").Replace(',', '.') + "\"><quantity>" + quantity.ToString() + "</quantity><value>" + value.ToString("##########0.00").Replace(',', '.') + "</value></transactionline>";
}
}
}
else if ((type == "out") || ((config.AppSettings.Settings["HasMoney"].Value == "True") && (type == "outb")))
{
type= "out";
config.AppSettings.Settings["HasMoney"].Value = "False";
SqlConnection con1 = new SqlConnection(cm18string);
if (con1.State != System.Data.ConnectionState.Open)
{
con1.Open();
}
SqlCommand cmd1 = new SqlCommand("SELECT SUM([Banconote_E500]),SUM([Banconote_E200]),SUM([Banconote_E100]),SUM([Banconote_E50]),SUM([Banconote_E20]),SUM([Banconote_E10]),SUM([Banconote_E5])),[BustaA] FROM [DataBos].[dbo].[Operazioni] join [DataBos].[dbo].[Buste] on [DataBos].[dbo].[Operazioni].SessioneRef = [DataBos].[dbo].[Buste].SessioneRef where TipoOperazione IN ('161','3', '1') and BustaA = #bag group by BustaA", con1);
cmd1.Parameters.Add("#bag",cassette);
SqlDataReader rd1 = cmd1.ExecuteReader();
rd1.Read();
long ttype = 0;
long value = 0;
long quantity = 0;
for (int i =1 ; i<=7;i++)
{
ttype = 0;
value = 0;
quantity = 0;
switch(i)
{
case 1:
ttype = 5;
break;
case 2:
ttype = 10;
break;
case 3:
ttype = 20;
break;
case 4:
ttype = 50;
break;
case 5:
ttype = 100;
break;
case 6:
ttype = 200;
break;
case 7:
ttype = 500;
break;
quantity = rd1.GetInt32(i - 1);
value = quantity * ttype;
if(quantity !=0)
{
// xmlString = xmlString + "<transactionline type = \"" + ttype.ToString("##########0.00").Replace(',', '.') + "\"><quantity>" + quantity.ToString() + "</quantity><value>" + value.ToString("##########0.00").Replace(',', '.') + "</value></transactionline>"; //Enable for CSExtra
xmlString = xmlString + "<transactionline type = \"" + ttype.ToString("##########0.00") + "\"><quantity>" + quantity.ToString() + "</quantity><value>" + value.ToString("##########0.00") + "</value></transactionline>";
}
}
rd1.Close();
con1.Close();
}
//else
//{
//}
xmlString = xmlString + "</transaction>";
string fout = config.AppSettings.Settings["destinationlocation"].Value;
System.IO.StreamWriter file = new System.IO.StreamWriter(fout + "\\"+ file_name);
file.WriteLine(xmlString);
file.Close();
if (SendFTP(file_name))
{
config.AppSettings.Settings["transactioncounter"].Value = rd.GetInt32(0).ToString();
transactioncounter = rd.GetInt32(0).ToString();
config.Save(ConfigurationSaveMode.Modified);
config.AppSettings.Settings["filecounter"].Value = Convert.ToInt32(config.AppSettings.Settings["filecounter"].Value) + 1 + "";
filecounter = config.AppSettings.Settings["filecounter"].Value;
config.Save(ConfigurationSaveMode.Modified);
WriteLog(file_name);
}
else
{
break;
}
}
rd.Close();
con.Close();
}}
catch (Exception e)
{
WriteLog(e);
}{
}}
public void WriteLog(string message)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
string logfilelocation = config.AppSettings.Settings["loglocation"].Value;
System.IO.StreamWriter file1 = new System.IO.StreamWriter(logfilelocation + "\\log.txt", true);
file1.WriteLine();
file1.WriteLine("Successfully completed");
file1.WriteLine(message);
file1.WriteLine("==================================================================================================");
file1.WriteLine("==================================================================================================");
file1.WriteLine();
file1.Close();
}
catch
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
MessageBox.Show("Please create folder: " + config.AppSettings.Settings["loglocation"].Value);
}
}
public void WriteLog(WebException ex)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
string logfilelocation = config.AppSettings.Settings["loglocation"].Value;
System.IO.StreamWriter file1 = new System.IO.StreamWriter(logfilelocation + "\\log.txt", true);
file1.WriteLine();
file1.WriteLine("FTP Error");
file1.WriteLine("Error : " + ex.ToString());
file1.WriteLine("FTP Response : " + ((FtpWebResponse)ex.Response).StatusDescription);
file1.WriteLine("FileCounter : " + config.AppSettings.Settings["filecounter"].Value);
file1.WriteLine("==================================================================================================");
file1.WriteLine("==================================================================================================");
file1.WriteLine();
file1.Close();
}
catch
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
MessageBox.Show("Please create folder: " + config.AppSettings.Settings["loglocation"].Value);
}
}
public void WriteLog(Exception ex)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
string logfilelocation = config.AppSettings.Settings["loglocation"].Value;
System.IO.StreamWriter file1 = new System.IO.StreamWriter(logfilelocation + "\\log.txt", true);
file1.WriteLine();
file1.WriteLine("XML File Error");
file1.WriteLine("Error : " + ex.ToString());
file1.WriteLine("FileCounter : " + config.AppSettings.Settings["filecounter"].Value);
file1.WriteLine("==================================================================================================");
file1.WriteLine("==================================================================================================");
file1.WriteLine();
file1.Close();
}
catch
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
MessageBox.Show("Please create folder: " + config.AppSettings.Settings["loglocation"].Value);
}
}
}
}
It is giving me the error at line quantity = rd.GetInt32(i+4)
I know the value is int 32 only from a database so why m i getting this error.?
`
It is probably because i+4 isn't a Int32 datatype. Trying printing the i+4 before and check what is the column type that matches in that position and fix your code accordingly.
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.