C# Managing threads in console application - c#

Good day everyone,
I need to say firstly, that I am not a C# developer in anyway, I have been tasked from my boss to "Make it work".
What I want is to have a thread that will spin off, not interrupt main(), call a function CcnDirSearch() and re perform this action after a certain amount of time.
My code currently runs in console about 1 time (sometimes 6 times) and then stops. I think the threads(or something like this) are ending before the function is completing.
Here is my code:
public int Run()
{
Task.Factory.StartNew(() => CcnDirFireAway());
...
...
//continues main();
>
public void CcnDirFireAway()
{
if (ScanDir != "")
{
Console.WriteLine("Starting Initial Scan on Directory: " + ScanDir + "\n\n\n");
TimerCallback tmCallback = CheckEffectExpiry;
Timer timer = new Timer(tmCallback, "test", 1000, 1000);
}
}
>
public void CheckEffectExpiry(object objectInfo)
{
//TODO put your code
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(DateTime.Now + " Starting Scan.....\n");
Console.ForegroundColor = ConsoleColor.White;
//Here is a call to my function that I want to call.
// I noticed that If I don't call it the programs continues to run harmoniously
Searcher.CcnDirSearch(ScanDir);
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(DateTime.Now + " Finished Scan.....\n");
Console.ForegroundColor = ConsoleColor.White;
}
>
Here is the code of the function I need to call off .
public static void CcnDirSearch(string sDir)
{
try
{
foreach (string file in Directory.EnumerateFiles(sDir, "*.*", SearchOption.AllDirectories))
{
using (var stream = File.OpenRead(file))
{
// Console.WriteLine(DateTime.Now + " Checking File : " + file);
bool Mcard = Searcher.CCNSearch(file, De.Thekid.INotify.Runner.MASTERCARD, false);
bool VCARD = Searcher.CCNSearch(file, De.Thekid.INotify.Runner.VISA, false);
bool ACARD = Searcher.CCNSearch(file, De.Thekid.INotify.Runner.AMEX, false);
if (Mcard)
{
Console.WriteLine(DateTime.Now + " MasterCard Number Found In File >> " + file);
//Inotifywatch.EventForward.UDPSend(512, RServer, ("<30>" + DateTime.Now + " MasterCard Number Found In File >> " + fullpath+ "\n"));
Logger.WriteEvent(DateTime.Now + " MasterCard Number Found In File >> " + file + "\n");
}
else if (VCARD)
{
Console.WriteLine(DateTime.Now + " Visa Card Number Found In File >> " + file);
//Inotifywatch.EventForward.UDPSend(512, RServer, ("<30>" + DateTime.Now + " Visa Card Number Found In File >> " + fullpath+ "\n"));
Logger.WriteEvent(DateTime.Now + " Visa Card Number Found In File >> " + file + "\n");
}
else if (ACARD)
{
Console.WriteLine(DateTime.Now + " AMEX Card Number Found In File >> " + file);
//Inotifywatch.EventForward.UDPSend(512, RServer, ("<30>" + DateTime.Now + " AMEX Card Number Found In File >> " + fullpath+ "\n"));
Logger.WriteEvent(DateTime.Now + " Amex Card Number Found In File >> " + file + "\n");
}
}
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
Console.Write("Finished the Search\n");
}

You could use a DispatcherTimer to call a function on a given time interval, then in that function create and start a new Thread in which you execute your function.
public static void Main(string[] args)
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(5000);;
timer.IsEnabled = true;
timer.Tick += OnTimerTick;
}
private void OnTimerTick(object sender, EventArgs e)
{
var thread = new Thread(new ThreadStart(()=>yourMethodToCall()));
thread.Start();
}

I want to Thanks everyone for all your help. I found a work around that worked for me.
As I said before , I am not a C# developer (I play one on T.V) so I am certain there are somethings where this code base can be improved .
If someone can write a better answer, I will happily accept it.
I just decided to launch the code differntly .
Timer x = new Timer(state => CheckEffectExpiry(1), null, 5000 /* When to start*/, 300000 /* when to retry */);
>
public void CheckEffectExpiry(object objectInfo)
{
//I hate C#'s way of accessing variables and such .
//So I am doing this...
Console.Write(DateTime.Now + " I was hit\n");
if (lockf == 1)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(DateTime.Now + " Starting Scan.....\n");
Console.ForegroundColor = ConsoleColor.White;
lockf = 0;
Searcher.CcnDirSearch(ScanDir);
lockf = 1;
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(DateTime.Now + " Finished Scan.....\n");
Console.ForegroundColor = ConsoleColor.White;
}
}

Related

C# out of memory with file

I'm getting a OutOfMemory exception when running the following code, it happens on the File.ReadLines line, it processes most files fine until it hits larger files.
It's consistantly using tons of memory and cpu during the whole process though.
The file it crashed on is only 156,000KB, which is 156mb
static void Main(string[] args)
{
Console.CursorVisible = false;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine();
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Connected to the Cassandra Database");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.White;
string filepath = #"C:\Users\admin\Desktop\wecrack lists";
DirectoryInfo directory = new DirectoryInfo(filepath);
int fileCount = 0;
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("cracking");
var collection = database.GetCollection<Password>("passwords");
foreach (var file in directory.GetFiles("*"))
{
fileCount++;
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Working through file: {" + file + "} {" + fileCount + "/" + directory.GetFiles("*").Count() + "}");
List<Password> entitys = new List<Password>();
foreach (string line in File.ReadLines(filepath + #"\" + file.ToString()))
{
entitys.Add(new Password { password = line });
}
collection.InsertManyAsync(entitys);
}
Console.WriteLine();
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Finished inserting records, press any key to get the count.");
Console.ReadKey(true);
while (true)
{
Console.ReadKey(true);
}
}
Try batching your updates. That way you won't have all that data in memory at the same time. It may also help you not totally lock up your database.
...
foreach (var file in directory.GetFiles("*"))
{
fileCount++;
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Working through file: {" + file + "} {" + fileCount + "/" + directory.GetFiles("*").Count() + "}");
System.IO.StreamReader file = new System.IO.StreamReader(filepath + #"\" + file.ToString());
while(!file.EndOfStream)
{
int passwordBatchCount = 0;
List<Password> entitysBatch = new List<Password>();
while ((string line = file.ReadLine()) != null && passwordBatchCount < BATCH_SIZE)
{
entitysBatch.Add(new Password { password = line });
passwordBatchCount++;
}
collection.InsertManyAsync(entitysBatch);
}
file.Close();
}
}
...

C# system.timers.timer weird behavior

I am trying to implement Bully Coordinator election algorithm. In this algorithm, Coordinator sends the alive message every 10 seconds and all the processes wait for at least 14 seconds to receive alive, if they don't receive the message within that time, they will initiate dead coordinator election.
The problem is AliveTimer (Timer3_Count) is increasing exponentially and active processes are also affecting it. I don't know why it is behaving weirdly.
When the initial coordinator is sending the Alive message then counter works perfectly but after dead coordinator election, it behaves weirdly.
else if (Received_Text.Contains("Alive:"))
{
SetText(Received_Text + "\n");
Coordinator_Alive = true;
Timer3_Counter = 0;
if (Alive_Count == 0)
{
Alive_Count++;
AliveTimer.Interval = (1 * 1000);
AliveTimer.Enabled = true;
AliveTimer.Elapsed += new System.Timers.ElapsedEventHandler(AliveTimer_Elapsed);
AliveTimer.Start();
}
}
The elapsed function is here
I think there is something wrong with my program, I tried everything.
private void AliveTimer_Elapsed(object sender, EventArgs e)
{
Timer3_Counter++;
SetTimer(Timer3_Counter.ToString());
Random rnd = new Random();
int rand_time = rnd.Next(14, 18);
if (Timer3_Counter == 14)
{
AliveTimer.Stop();
Timer3_Counter = 0;
Alive_Count = 0;
if (Coordinator_Alive == false)
{
byte[] buffer = Encoding.ASCII.GetBytes("Dead Coordinator Election: " + txName.Text);
_clientSocket.Send(buffer);
Timer4_Counter = 0;
DeadTimer.Interval = (1 * 1000);
DeadTimer.Elapsed += new System.Timers.ElapsedEventHandler(DeadTimer_Elapsed);
DeadTimer.Enabled = true;
DeadTimer.Start();
}
}
if (Coordinator_Alive == true)
Coordinator_Alive = false;
}
and the dead Coordinator election code is here
else if (Received_Text.Contains("Dead Coordinator Election:"))
{
SetCPID("");
Coordinator_Alive = false;
Alive_Count = 0;
Timer3_Counter = 0;
AliveTimer.Stop();
AliveTimer.Enabled = false;
string output = Regex.Match(Received_Text, #"\d+").Value;
SetText("Dead Coordinator Election Received from Process ID: " + output + "\n");
if (Convert.ToInt32(txName.Text) > Convert.ToInt32(output))
{
byte[] buffer = Encoding.ASCII.GetBytes("Greater Process No: " + txName.Text + " found than " + output + "\n");
_clientSocket.Send(buffer);
SetText("Our Process No: " + txName.Text + " is Greater than " + output + "\n");
Lower_Count++;
byte[] buffer1 = Encoding.ASCII.GetBytes("Dead Coordinator Election: " + txName.Text);
_clientSocket.Send(buffer1);
}
else
{
byte[] Txt_Send = Encoding.ASCII.GetBytes("Our Process No: " + txName.Text + " is less than " + output);
_clientSocket.Send(Txt_Send);
Greater_Count++;
}
}
The full code can be found here
Bully Algorithm
Note: I am using passive server just to broadcast messages from each process
I don't know what causes the problem, but I think you will be able to figure the cause quickly if you log start and stop all all methods and analyse the output.
This would help establish if:
1. As #Idle_Mind suggested, that you are adding more and more handlers
2. The time taken to execute each method creeps up
and more...
I don't know how you app is built but you can even start with Console.WriteLine or Debug.WriteLine.

Display Output in a text file

I have taken the input code through file and i have to generate data according to it and output it's result in a text file as well..
My Output Code is below..
public void Generator()
{
/// ....... Code
public void DisplayTOKENS()
{
using (StreamWriter writer =
new StreamWriter("C:\\Users\\saeed\\Documents\\Outputt.txt"))
{
for (int i = 0; i < j;i++ )
{
tok[i].Display_Token();
} }
}
// and in other structur named TOKEN
public void Display_Token()
{ /*
using (StreamWriter writer =
new StreamWriter("C:\\Users\\saeed\\Documents\\Outputt.txt"))
{
writer.Write("( " + this.Class_Part + " , ");
writer.Write(this.Value_Part + " , ");
writer.Write(this.Line_no + " )");
writer.WriteLine();
}*/
Console.Write("( " + this.Class_Part + " , ");
Console.Write(this.Value_Part + " , ");
Console.Write(this.Line_no + " )");
Console.WriteLine();
}
When i try to directly work in Display_Token then it just simply show the last line in file.. i want to display the complete array in the file. waiting for some positive response !!
That StreamWriter constructor overwrites the existing file. So, each token effectively deletes whatever was written earlier then writes its content. That is why you only see the last token's content in the file.
Use the overload with the "append" argument and pass true so that the existing file is not deleted.
You have to check if file exists and than do "append" operation instead of "overwrite".
// in DisplayTOKENS()
string fileName = "C:\\Users\\saeed\\Documents\\Outputt.txt";
if (System.IO.File.Exists(fileName))
System.IO.File.Delete(fileName);
for (int i = 0; i < j; i++)
{
tok[i].Display_Token(fileName);
}
// in Display_Token(string fileName)
System.IO.File.AppendAllText(fileName, "( " + this.Class_Part + " , " + this.Value_Part + " , " + this.Line_no + " )");

Windows Update API Memory Leak in Code

I am developing an application in C# to aid in a process that my company uses to configure new PCs before adding them to our domain, for offices all around the country. I am currently at a phase where I need to automate Windows Updates without any feedback from the user.
I have all of the Windows Update code put together in a console application. But I noticed when there are a LOT of updates (60 to 100+) the TrustedInstaller process ends up using over 1.5GB of RAM (after about 1hr+ during the install process), although the installation of the updates eventually does finish (2-4 hours later) I feel like 1.5GB of physical memory is just too much (even though this will be the only productive process running at the time).
In the interest in ensuring my code runs optimally would someone mind taking a look for me? I am very new to the Windows Update API(wuapi.dll) and there is very little documentation on the internet.
Here is the snippet of code (at the very bottom of my "program" class) that initiates and runs the installation of downloaded updates:
using WUApiLib
Console.WriteLine(Environment.NewLine + Environment.NewLine + "Installing Updates...");
IUpdateInstaller installer = uSession.CreateUpdateInstaller();
installer.Updates = updatesToInstall;
IInstallationResult installationRes = installer.Install();
List<object> successUpdates = new List<object>();
Console.Clear();
for (int i = 0; i < updatesToInstall.Count; i++)
{
if (installationRes.GetUpdateResult(i).HResult == 0)
{
Console.WriteLine("Installed: " + updatesToInstall[i].Title);
successUpdates.Add(i);
}
else
{
Console.WriteLine("Failed: " + updatesToInstall[i].Title);
}
}
Console.WriteLine(Environment.NewLine + Environment.NewLine +
"{0} out of {1} updates installed successfully!",successUpdates.Count() ,updatesToInstall.Count);
And below is my entire code for searching, downloading, and installing the updates (Console.Readkey() methods are in there simply for testing):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WUApiLib;
using System.Management;
namespace WUConsole
{
class Program
{
static void Main()
{
Console.WriteLine(Environment.NewLine + Environment.NewLine +
"Checking for Windows Updates...");
try
{
UpdateSession uSession = new UpdateSession();
IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
ISearchResult uResult = uSearcher.Search("IsInstalled=0 and Type='Software' and BrowseOnly=0");
Console.Clear();
Console.Write("Available Updates:" + Environment.NewLine + Environment.NewLine);
foreach (IUpdate update in uResult.Updates)
{
Console.WriteLine("-" + update.Title);
}
if (uResult.Updates.Count == 0)
{
Console.Clear();
Console.WriteLine(Environment.NewLine + Environment.NewLine + "Windows is up to date!");
Console.ReadKey();
Environment.Exit(0);
}
int updateCount = uResult.Updates.Count;
if (updateCount == 1)
{
Console.WriteLine(Environment.NewLine + Environment.NewLine +
"Finished searching for updates. {0} update found.", updateCount);
}
else
{
Console.WriteLine(Environment.NewLine + Environment.NewLine +
"Finished searching for updates. {0} updates found.", updateCount);
}
Console.ReadKey();
Console.Clear();
if (updateCount == 1)
{
Console.WriteLine(Environment.NewLine + Environment.NewLine +
"Downloading {0} Windows Update...", updateCount);
}
else
{
Console.WriteLine(Environment.NewLine + Environment.NewLine +
"Downloading {0} Windows Updates...", updateCount);
}
UpdateDownloader downloader = uSession.CreateUpdateDownloader();
downloader.Updates = uResult.Updates;
downloader.Download();
Console.Clear();
Console.WriteLine(Environment.NewLine + Environment.NewLine + "Updates Downloaded Successfully!");
UpdateCollection updatesToInstall = new UpdateCollection();
foreach(IUpdate update in uResult.Updates)
{
if (update.IsDownloaded)
update.AcceptEula();
updatesToInstall.Add(update);
}
Console.Clear();
Console.WriteLine(Environment.NewLine + Environment.NewLine + "Installing Updates...");
IUpdateInstaller installer = uSession.CreateUpdateInstaller();
installer.Updates = updatesToInstall;
IInstallationResult installationRes = installer.Install();
List<object> successUpdates = new List<object>();
Console.Clear();
for (int i = 0; i < updatesToInstall.Count; i++)
{
if (installationRes.GetUpdateResult(i).HResult == 0)
{
Console.WriteLine("Installed: " + updatesToInstall[i].Title);
successUpdates.Add(i);
}
else
{
Console.WriteLine("Failed: " + updatesToInstall[i].Title);
}
}
Console.WriteLine(Environment.NewLine + Environment.NewLine +
"{0} out of {1} updates installed successfully!",successUpdates.Count() ,updatesToInstall.Count);
Console.ReadKey();
Console.WriteLine(Environment.NewLine + Environment.NewLine + "1");
Console.ReadKey();
System.Diagnostics.Process.Start("shutdown", "/r /t 0");
}
catch (Exception e)
{
Console.Clear();
Console.WriteLine(Environment.NewLine + Environment.NewLine + "Windows Update failed: " + e.Message);
Console.ReadKey();
}
}
}
}
Any feedback/ pointers on this would be greatly appreciated, as I know there is not much documentation out there.
Thanks so much!

'C:\MPIHello\bin\Debug' is not recognized as an internal or external command, operable program or batch file

using System;
using MPI;
class MPIHello
{
static void Main(string[] args)
{
using (new MPI.Environment(ref args))
{
Intracommunicator comm = Communicator.world;
if (comm.Rank == 0)
{
//Send its rank to the next neighbor
comm.Send(comm.Rank, 1, 0);
//Receive message
int msg = comm.Receive<int>(comm.Size, 0);
Console.WriteLine("I am MPI process " + comm.Rank + " of " + comm.Size + ", on my left is " + msg);
}
else
{
//Receive message
int msg = comm.Receive<int>(comm.Rank - 1, 0);
Console.WriteLine("I am MPI process " + comm.Rank + " of " + comm.Size + ", on my left is " + msg);
//Send message to next neighbor
comm.Send(comm.Rank, (comm.Rank + 1) % comm.Size, 0);
}
}
}
}
This is the C# coding that I have done, but when I want to run it in the Command Prompt, this error comes out 'C:\MPIHello\bin\Debug' is not recognized as an internal or external command, operable program or batch file... May I know what is the problem?
Yeah, it is a directory. Usually, the program is inside this directory. Can you give more info?

Categories

Resources