PDA

View Full Version : [SHARE] CSMC CSharp Micro Compiler by HD %)


humordwarf
21.07.2007, 13:24
CSMC CSharp Micro Compiler by HD

{eng}
All power of CSharp in microcompiler! =)
NOT need to install Visual Studio or any SDK, you only need .NET framework 2.0 on your PC.

Script example:

class Minimal
{
static void Main(string[] args)
{
System.Console.WriteLine("Hello, World!");
}
}


Now type csmc Minimal.csp and get ready-to-use executable.

Everything is compatible with C#-language from Microsoft.
Only difference: no IDE and little bit another way to link modules.

New addition is expanded #pragma-directives:
#pragma include somefile.cs -- add somefile.cs into project
#pragma library somefile.dll -- add reference to somefile.dll into project
#pragma output somepath\somefile -- override output file path\name
#pragma target dll|exe -- kind of target file (exe или dll)

Example:

#pragma target dll
#pragma include CmdLine.cs

only two lines, but it tells to compiler that we need DLL with
CmdLine (usual C# public class)

and feature of this = we can decide in your sources how to link that
class, dynamic or static:

dynamic:

#pragma library CmdLine.dll
using System;
using HD;
public class Application
{
public static void Main(string[] args)
{
CmdLine cmd = new CmdLine(args);
....

static:

#pragma include CmdLine.cs
using System;
using HD;
public class Application
{
public static void Main(string[] args)
{
CmdLine cmd = new CmdLine(args);
.....

See difference? =)
Well... Look at examples, get some C#-book into hands and go =)
{/eng}

{rus}
Вся энергия СиШарпа в микрокомиляторе! =)
НЕ требует установленной Вижл Студии и всяких SDK,
необходима только установленная .NET framework 2.0.

Пример скрипта:

class Minimal
{
static void Main(string[] args)
{
System.Console.WriteLine("Hello, World!");
}
}

После создания скрипта достаточно набрать в командной
строке csmc Minimal.csp и вы получите работоспособный exe-файл.

Все полностью совместимо с языком C# от Майкрософта, разница лишь в том,
что нет IDE и немного изменен принцип линкования.

Нововведение состоит в небольном расширении набора #pragma-директив:
#pragma include somefile.cs -- добавляет somefile.cs в список компилируемых файлов
#pragma library somefile.dll -- добавляет ссылку на сборку somefile.dll
#pragma output somepath\somefile -- принудительно указывает имя файла-результата компилятора
#pragma target dll|exe -- указывает компилятору что собирать (exe или dll)

например:

#pragma target dll
#pragma include CmdLine.cs

всего две строчки в файле, но эти две строчки говорят компилятору собрать dll,
в которую входит содержимое CmdLine.cs (обыкновенного C# паблик-класса)

вся фишка в том, что в исходнике мы можем указать, каким образом использовать класс
CmdLine, загружая из DLL или компилируя вместе с основной программой:

Первый вариант:

#pragma library CmdLine.dll
using System;
using HD;
public class Application
{
public static void Main(string[] args)
{
CmdLine cmd = new CmdLine(args);
....

Второй вариант:

#pragma include CmdLine.cs
using System;
using HD;
public class Application
{
public static void Main(string[] args)
{
CmdLine cmd = new CmdLine(args);
.....

Заметили разницу? =)
В общем смотрите примеры, берите в руки книжку по C# и вперед, писать скрипты/программы =)

{/rus}

Вложения из исходного сообщения (сами файлы в копии отсутствуют):
csmc100.zip — 20273 байт

hr
21.07.2007, 13:55
"good wokr men, kip it up" ;)

ps: http://bash.org.ru/quote/288846

humordwarf
21.07.2007, 18:31
{eng}
these few lines of code = full multithreaded 100% working telnet server %)
implemented login/password with delays thing, and command handler

for now server understands only one command "BYE", but u can easily implenent any thing u want to do remotely. e.g. reboot, kill/restart processes, cpu load, etc, etc..
{/eng}

{rus}
эти несколько строк кода = полный многопоточный 100% рабочий телнет сервер %)
сделан запрос логин/пароль с задержками и обработчик команд

пока сервер понимает только одну команду "BYE", но вы можете с легкостью добавить любые новые штуки, которые вы хотели бы осуществлять удаленно... как то рестарты, работа с процессами, статистика процессора/системы и т.д. и т.п.
{/rus}

compile.bat

csmc TelnetApp.csp


TelnetServer.csp

#pragma include TelnetServer.cs

using System;
using HD;

class TelnetApp
{
const int TelnetPort = 23;

static void Main(string[] args)
{
Console.WriteLine("Sample Telnet Server by HD");
TelnetServer s = new TelnetServer(TelnetPort);
s.Start();
}
}


TelnetServer.cs

#pragma library System.dll

using System;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace HD
{
public class TelnetServerGlobals
{
public const string allowedLogin = "admin";
public const string allowedPassword = "12345";

public const int maxClients = 2;
public static int numClients = 0;
}
public class TelnetServerThread
{
private TcpClient cli;
private StreamReader sr;
private StreamWriter sw;
private string login;
private string password;
private bool loginok;

public bool CommandHandler(string cmd)
{

if (cmd=="BYE")
{
sw.Write("Bye!");
sw.Flush();
return false; //close socket
}

sw.WriteLine(cmd+" -> Unknown Command!");
sw.Flush();

return true; //continue
}

public TelnetServerThread(TcpClient _cli, StreamReader _sr, StreamWriter _sw)
{
cli = _cli;
sr = _sr;
sw = _sw;
}

public void Run()
{
Interlocked.Increment(ref TelnetServerGlobals.numClients);
Console.WriteLine("Client Connected");
login = "";
password = "";
loginok = false;

try
{
sw.WriteLine("Welcome to Pentagon security gateway.");
sw.Flush();

while (cli.Connected)
{
string cmd;

if (!loginok)
{

if (login == "")
{
sw.Write("Login: ");
sw.Flush();
login = sr.ReadLine();
Thread.Sleep(1000);
continue;
}

if (password == "")
{
sw.Write("Password: ");
sw.Flush();
password = sr.ReadLine();
Thread.Sleep(2000);
continue;
}

if (login != TelnetServerGlobals.allowedLogin || password != TelnetServerGlobals.allowedPassword)
{

sw.WriteLine("cya, hacker");
sw.Flush();
break;
}
else
{
loginok = true;
sw.WriteLine("Access Granted");
sw.Flush();
continue;
}

}

sw.Write(">");
sw.Flush();
cmd = sr.ReadLine();
cmd = cmd.Trim().ToUpper();


if (CommandHandler(cmd)==false) break;
}

cli.Close();
}
catch(Exception)
{
//catch "Disconnects"
//Console.WriteLine(e.Message);
}

Console.WriteLine("Client Disconnected");
Interlocked.Decrement(ref TelnetServerGlobals.numClients);
}

}

public class TelnetServer
{
private int port;

private void RunThread(TcpClient cli, StreamReader sr, StreamWriter sw)
{
TelnetServerThread c = new TelnetServerThread(cli,sr,sw);
Thread t = new Thread(new ThreadStart(c.Run));
t.Start();
}

public TelnetServer(int _port)
{
port = _port;
}

public void Start()
{
TcpListener server = new TcpListener(IPAddress.Any,port);
server.Start();
Console.WriteLine("Server Started");
while (true)
{
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
StreamReader _sr = new StreamReader(stream);
StreamWriter _sw = new StreamWriter(stream);
if (TelnetServerGlobals.numClients>=TelnetServerGlobals.maxClients)
{
_sw.WriteLine("Too many clients. Try again later.");
_sw.Flush();
client.Close();
}
else
{
RunThread(client,_sr,_sw);
}
}
}

}
}

[drzoom]
21.07.2007, 19:48
good job hd, как всегда:)