Skip to content
MPGHThe Dark Arts
/
RegisterLog in
Forum
Community
What's NewLatest posts across the boardTrendingHottest threads right nowSubscribedThreads you follow
Discussion
GeneralIntroductionsEntertainmentDebate FortFlaming & Rage
Board
News & AnnouncementsMPGH TimesSuggestions & HelpGiveaways
More Sections
Art & Graphic DesignProgrammingHackingCryptocurrency
Hacks & Cheats
Games
ValorantCS2 / CS:GOCall of Duty / WarzoneFortniteApex LegendsEscape From Tarkov
+14 moreLeague of LegendsGTA VMinecraftRustROTMGBattlefieldTroveBattleOnCombat ArmsCrossFireBlackshotRuneScapeDayZDead by Daylight
Resources
Game Hacking TutorialsReverse EngineeringGeneral Game HackingAnti-CheatConsole Game Hacking
Tools
Game Hacking ToolsTrainers & CheatsHack/Release NewsNew
Submit a release →Share your cheat, tool, or config with the community.
AINEW
AI Tools
General & DiscussionPrompt EngineeringLLM JailbreaksHotAI Agents & AutomationLocal / Open Models
AI × Gaming
AI Aimbots & VisionML Anti-CheatGame Bots & Automation
Create
AI Coding / Vibe CodingAI Art & MediaAI Voice & TTS
The AI frontier →Where game hacking meets modern machine learning. Jump in.
Marketplace
Buy & Sell
SellingBuyingTradingUser Services
Trust & Safety
Middleman LoungeMarketplace TalkVouch Copy Profiles
Money
Cryptocurrency TalkCurrency ExchangeWork & Job Offers
Start selling →List accounts, services, and goods. Use the middleman to trade safe.
MPGH The Dark Arts

A community for offensive security research, reverse engineering, and AI.

Community

ForumMarketplaceSearch

Account

RegisterLog in

Legal

Privacy PolicyForum RulesHelp & FAQ
© 2026 MPGH · All rights reserved.Built by the community, for the community. For educational purposes onlyContent is shared for security research and education — we don't condone illegal use. You're responsible for complying with applicable laws. Use at your own risk.
Home › Forum › Programming › C# Programming › [Collection]Snippets Vault[C#]

[Collection]Snippets Vault[C#]

Posts 1–15 of 22 · Page 1 of 2
NextGen1
NextGen1
[Collection]Snippets Vault[C#]
Use this format for submitting snippets

It may be used later to parse the snippets to a application (like the one in the VB Section)

If you're going to post a snippet in this thread then you should be posting it in the following format:

Snippet Name: ____________________
Keywords: ____,____,____ ...
Description(Optional): _______________________
Code:
Code:
Your Code Here...
This is to be used for any small bit of code you would like to share.


#1 · 15y ago
SPittn_Blood
SPittn_Blood
Big List :D
Snippet Name: Age Calculation
Keywords: age,years,old
Description: Gets the users age according to input.
Code:

Code:
public static  int GetAge(DateTime birthdate)
	{
	DateTime now = DateTime.Today;
	int years = now.Year - birthdate.Year;
	return years;
	}
Using The Code:

Code:
GetAge(Convert.ToDateTime(txtBoxBirthDate.Text)).ToString

------------------------------------


Snippet Name: Generate GUID
Keywords: generate,unique,GUID
Description(Optional): Generates the 128bit unique identifier
Code:

Implements:
Code:
 using system;
Sub:
Code:
public string GenerateGUID()
{
return Guid.NewGuid().ToString());
}
Example:
Code:
String Guid_John = GenerateGUID();

------------------------------------


Snippet Name: Random Number
Keywords: random,number
Description(Optional): Retrieves a random number from the Min and max specified.
Code:

Implements:
Code:
 using system;
Sub:
Code:
private int RandomNumber(int minimum, int maximum)
{
Random random = new Random();
return random.Next(minimum, maximum);
}
Example Usage:
Code:
MessageBox.Show(RandomNumber(10, 20).ToString());

------------------------------------

Snippet Name: LOCAL IP Retrieval
Keywords: Ip,retrieve,local,Internet,Protocol
Description: Gets the user's local IP address.
Code:

Implements:
Code:
 using system.Net;
Sub:
Code:
public string GetLocalIp()
{
System.Net.IPAddress[] IP =System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName());
for (int n= 0; n < IP.Length; n++)
{
return IP[n].ToString();
}
}
Usage:
Code:
MessageBox.Show(GetLocalIP());
#2 · edited 15y ago · 15y ago
NextGen1
NextGen1
Snippet Name: Read Registry Key
Keywords: Registry,Read,C#,Key,Reg
Description(Optional): Reads a Registry Key

Code:
RegistryKey masterKey = Registry.LocalMachine.CreateSubKey 
   ("Key Here");
if (masterKey == null)
{
   MessageBox.Show("Master Key Does Not Exist, Null Error Returned:");
}
else
{
   MessageBox.Show("MyKey = {0}", masterKey.GetValue ("MyKey"));
}
masterKey.Close();


Snippet Name: Write Registry Key
Keywords: Registry,Write,C#,Key,Reg
Description(Optional): Writes a Registry Key

Code:
RegistryKey masterKey = Registry.LocalMachine.CreateSubKey
   ("Key Here");
if (masterKey == null)
{
   MessageBox.Show("Master Key Does Not Exist, Null Error Returned:");
}
else
{
   try
   {
      masterKey.SetValue ("MyKey", "MyValue");
   }
   catch (Exception ex)
   {
      MessageBox.Show(ex.Message);
   }
   finally
   { 
      masterKey.Close();
   }
}
#3 · edited 15y ago · 15y ago
Kuro Tenshi
Kuro Tenshi
Snippet Name: Email/Account Comparison + retrieve recovery question. (doesnt include Recovery Answer thats located in the AccountsAdd Table)
Keywords: SQL, Login, Email, recovery
Description(Optional): with usage of MySQL and Linq to SQL in C# a account compare program.
SQL database named FAQ
Table 1 will be named "AccountsAdd" contains atleast 1primairy key "AccountId" 3 text items "Account" & "Password" & "Email" 1 int "RecoveryQuestion".
Table 2 will be named "Recovery_Questions" this one will contain 1 primary key "Recovery_Questions" and 1 text "R_Question".

form has 2 texboxes + 1 button, tbEmail + tbRQ, bCheckMail
[php]
private void accCompare(object sender, EventArgs e)
{
List<String> accCompare = (from Qs in Faq.AccountAdds orderby Qs.AccountId select Qs.Account).ToList();
List<String> EMAILCompare = (from Qs in Faq.AccountAdds orderby Qs.AccountId select Qs.Email).ToList();

for (int i = 0; i < accCompare.Count; i++)
{
if (EMAILCompare[i].ToString() == tbEmail.Text)
{
List<string> ReQ = (from Qs in Faq.Recovery_Questions orderby Qs.R_QuestionId select Qs.R_Question).ToList();
List<int> ReQInt = (from Qs in Faq.AccountAdds orderby Qs.AccountId select Qs.RecoveryQuestion).ToList();

int i2 = ReQInt[i];
tbRQ.Text = ReQ[i2-1];
break;
}
}
}

private void bCheckMail_Click(object sender, EventArgs e)
{
accCompare(sender, e);
}
[/php]
#4 · edited 15y ago · 15y ago
SeptFicelle
SeptFicelle
Snippet Name: Find Text
Keywords: Search Document, Find
Description: This snippet will search one string for another.

Code:
public void Find(String textToSearch, String textToFind)
{
if (textToSearch.Contains(textToFind))
MessageBox.Show("Found " + textToFind + "!");

else
MessageBox.Show("Did not find " + textToFind + ".");
}
I think I'll make an application that will give these snippets a home; and I think I'll make a DLL that contains them all. With everyone's permission of course.
#5 · 15y ago
♪~ ᕕ(ᐛ)ᕗ
♪~ ᕕ(ᐛ)ᕗ
Snippet Name: Q1BasicBinaryFormatter
Keywords: Ecrypt, Decrypt, Binary, RSAKey
Description: Used to (d)ecrypt a segment of bytes.

Code:
/* Q1 is a networking library that I've started when I was on vacations. It's under development too. */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System****;
using System.Security.Cryptography;

namespace Q1
{
    /// <summary>
    /// Holds the common classes of the Q1 technology.
    /// </summary>
    public class RRR
    {
        /// <summary>
        /// Represents a Basic Binary Formatter.
        /// </summary>
        public class BasicQ1BinaryFormation
        {
            private RSAOAEPKeyExchangeFormatter fmt = new RSAOAEPKeyExchangeFormatter();

            private byte[] key;
            private int size;

            /// <summary>
            /// Initializes a new instace of a BasicQ1BinaryFormation class.
            /// </summary>
            public BasicQ1BinaryFormation()
            {
                fmt.SetKey(new RSACryptoServiceProvider());
                key = fmt.CreateKeyExchange(BitConverter.GetBytes(2012));
                size = key.Length;
            }

            /// <summary>
            /// Formats an array of bytes using the Q1BasicFormation method.
            /// </summary>
            /// <param name="orig">The array to format.</param>
            /// <returns></returns>
            public byte[] Patch(byte[] orig)
            {
                int pkey = 0;
                int tempKey = 0;
                for (int i = 0; i < size; i++)
                {
                    tempKey = key[i];
                    pkey += tempKey * key[i];
                }

                byte[] patch = new byte[orig.Length];

                for (int i = 0; i < orig.Length; i++)
                {
                    patch[i] = (byte)(orig[i] + pkey);
                }

                MemoryStream memsr = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(memsr);
                writer.Write(size);
                writer.Write(key);
                writer.Write(patch);
                byte[] lpPatch = memsr.ToArray();
                writer.Close();

                return lpPatch;
            }

            /// <summary>
            /// Deformats an array of bytes using the Q1BasicFormation method.
            /// </summary>
            /// <param name="patch">The array to deformat.</param>
            /// <returns></returns>
            public byte[] DePatch(byte[] patch)
            {
                int pkey = 0;
                int tempKey = 0;

                MemoryStream memsr = new MemoryStream(patch);
                BinaryReader reader = new BinaryReader(memsr);

                int s = reader.ReadInt32();
                byte[] lpKey = reader.ReadBytes(s);

                byte[] lpPatch = reader.ReadBytes((int)memsr.Length - (4 + s));

                for (int i = 0; i < size; i++)
                {
                    tempKey = lpKey[i];
                    pkey += tempKey * lpKey[i];
                }

                byte[] orig = new byte[lpPatch.Length];

                for (int i = 0; i < orig.Length; i++)
                {
                    orig[i] = (byte)(lpPatch[i] - pkey);
                }
                return orig;
            }
        }
    }
}
#6 · 13y ago
♪~ ᕕ(ᐛ)ᕗ
♪~ ᕕ(ᐛ)ᕗ
Let's get this shit back to life..
Snippet Name: Archive Manager
Keywords: Package, Archive, ZIP
Description: A group of functions used to create ZIP archives (directly pasted from a project of mine; GSC Compiler; and I didn't rename the functions).

Code:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System****.Packaging;
using System****;

public static class Packer
{


	public static void AddToArchive(Package zip, string fileToAdd)
	{
		string uriFileName = fileToAdd.Replace(" ", "_");

		string zipUri = string.Concat("/", System****.Path.GetFileName(uriFileName));

		Uri partUri = new Uri(zipUri, UriKind.Relative);
		string contentType = System.Net.Mime.MediaTypeNames.Application.Zip;
		PackagePart pkgPart = zip.CreatePart(partUri, contentType, CompressionOption.Maximum);
		byte[] bites = File.ReadAllBytes(fileToAdd);
		pkgPart.GetStream().Write(bites, 0, bites.Length);
		pkgPart.GetStream().Close();
	}


	public static void AddToIWD(Package zip, string fileToAdd)
	{
		string uriFileName = fileToAdd.Replace(" ", "_");

		string zipUri = "images\\" + Path.GetFileName(fileToAdd);

		Uri u = new Uri(zipUri, UriKind.Relative);
		Uri partUri = PackUriHelper.CreatePartUri(u);
		string contentType = System.Net.Mime.MediaTypeNames.Application.Zip;

		PackagePart pkgPart = zip.CreatePart(partUri, contentType, CompressionOption.Maximum);
		byte[] bites = File.ReadAllBytes(fileToAdd);
		Stream sc = pkgPart.GetStream();
		sc.Write(bites, 0, bites.Length);
		sc.Close();
		for (int i = 0; i <= zip.GetParts.Count() - 1; i++) {
			if (zip.GetParts()(i).Uri.ToString() == "/[Content_Types].xml") {
				zip.DeletePart(zip.GetParts()(i).Uri);
			}
		}
	}


	public static void AddFolder(Package zip, string fileToAdd, string folder)
	{
		string uriFileName = fileToAdd.Replace(" ", "_");

		string zipUri = folder + "\\" + Path.GetFileName(fileToAdd);

		Uri u = new Uri(zipUri, UriKind.Relative);
		Uri partUri = PackUriHelper.CreatePartUri(u);
		string contentType = System.Net.Mime.MediaTypeNames.Application.Zip;

		PackagePart pkgPart = zip.CreatePart(partUri, contentType, CompressionOption.Maximum);
		byte[] bites = File.ReadAllBytes(fileToAdd);
		Stream sc = pkgPart.GetStream();
		sc.Write(bites, 0, bites.Length);
		sc.Close();
		AddToArchive(zip, FileSystem.CurDir() + "\\Projects\\.gscproj");
		for (int i = 0; i <= zip.GetParts.Count() - 1; i++) {
			if (zip.GetParts()(i).Uri.ToString() == "/[Content_Types].xml") {
				zip.DeletePart(zip.GetParts()(i).Uri);
			}
		}
	}


	public static void AddFolderEx(Package zip, string fileToAdd, string folder)
	{
		string uriFileName = fileToAdd.Replace(" ", "_");

		string zipUri = folder + "\\" + Path.GetFileName(fileToAdd);

		Uri u = new Uri(zipUri, UriKind.Relative);
		Uri partUri = PackUriHelper.CreatePartUri(u);
		string contentType = System.Net.Mime.MediaTypeNames.Application.Zip;

		PackagePart pkgPart = zip.CreatePart(partUri, contentType, CompressionOption.Maximum);
		byte[] bites = File.ReadAllBytes(fileToAdd);
		Stream sc = pkgPart.GetStream();
		sc.Write(bites, 0, bites.Length);
		sc.Close();
		for (int i = 0; i <= zip.GetParts.Count() - 1; i++) {
			if (zip.GetParts()(i).Uri.ToString() == "/[Content_Types].xml") {
				zip.DeletePart(zip.GetParts()(i).Uri);
			}
		}
	}

}
#7 · 13y ago
♪~ ᕕ(ᐛ)ᕗ
♪~ ᕕ(ᐛ)ᕗ
Snippet Name: Files grouper
Keywords: File, group, creator
Description: Groups different files into one single (ecrypted) file.
NOTE: This does not compress the files, it just groups them. After the ecryption the file size might be even bigger than the sum of the files grouped.

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System****;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;

namespace GSC_Explorer.Package
{
    #region Q1

    public class RRR
    {
        /// <summary>
        /// Represents a Basic Binary Formatter.
        /// </summary>
        public class BasicQ1BinaryFormation
        {
            private RSAOAEPKeyExchangeFormatter fmt = new RSAOAEPKeyExchangeFormatter();

            private byte[] key;
            private int size;

            /// <summary>
            /// Initializes a new instace of a BasicQ1BinaryFormation class.
            /// </summary>
            public BasicQ1BinaryFormation()
            {
                fmt.SetKey(new RSACryptoServiceProvider());
                key = fmt.CreateKeyExchange(BitConverter.GetBytes(2012));
                size = key.Length;
            }

            /// <summary>
            /// Formats an array of bytes using the Q1BasicFormation method.
            /// </summary>
            /// <param name="orig">The array to format.</param>
            /// <returns></returns>
            public byte[] Patch(byte[] orig)
            {
                int pkey = 0;
                int tempKey = 0;
                for (int i = 0; i < size; i++)
                {
                    tempKey = key[i];
                    pkey += tempKey * key[i];
                }

                byte[] patch = new byte[orig.Length];

                for (int i = 0; i < orig.Length; i++)
                {
                    patch[i] = (byte)(orig[i] + pkey);
                }

                MemoryStream memsr = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(memsr);
                writer.Write(size);
                writer.Write(key);
                writer.Write(patch);
                byte[] lpPatch = memsr.ToArray();
                writer.Close();

                return lpPatch;
            }

            /// <summary>
            /// Deformats an array of bytes using the Q1BasicFormation method.
            /// </summary>
            /// <param name="patch">The array to deformat.</param>
            /// <returns></returns>
            public byte[] DePatch(byte[] patch)
            {
                int pkey = 0;
                int tempKey = 0;

                MemoryStream memsr = new MemoryStream(patch);
                BinaryReader reader = new BinaryReader(memsr);

                int s = reader.ReadInt32();
                byte[] lpKey = reader.ReadBytes(s);

                byte[] lpPatch = reader.ReadBytes((int)memsr.Length - (4 + s));

                for (int i = 0; i < size; i++)
                {
                    tempKey = lpKey[i];
                    pkey += tempKey * lpKey[i];
                }

                byte[] orig = new byte[lpPatch.Length];

                for (int i = 0; i < orig.Length; i++)
                {
                    orig[i] = (byte)(lpPatch[i] - pkey);
                }
                return orig;
            }
        }
    }

    #endregion

    #region FUCKME
    [Serializable]
    public enum PackagePartType
    {
        Doc,
        File,
        Picture
    }

    [Serializable]
    public enum PackageType
    {
        Docs,
        Files,
        Pictures
    }

    [Serializable]
    public class PackagePart
    {
        string name;
        byte[] buffer;
        PackagePartType type;

        public PackagePart(string n, byte[] b, PackagePartType t)
        {
            name = n;
            buffer = b;
            type = t;
        }

        public string Name { get { return name; } }
        public byte[] Buffer { get { return buffer; } }
        public PackagePartType Type { get { return type; } }
    }

    public class PackageBuilder
    {
        List<PackagePart> parts;
        string name, description;
        PackageType type;

        public PackageBuilder(string n, string d, PackageType t)
        {
            parts = new List<PackagePart>();
            name = n;
            description = d;
            type = t;
        }

        public void AddPackagePart(PackagePart part)
        {
            parts.Add(part);
        }

        public void RemovePackagePart(string packagePartName)
        {
            var pps = (from p in parts where p.Name == packagePartName orderby p.Name select p).ToArray();
            if (parts.Contains(pps[0]))
            {
                parts.Remove(pps[0]);
            }
        }

        public byte[] BuildPrecompiledFile()
        {
            MemoryStream memsr = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(memsr);

            // Pre-cache the buffer
            writer.Write(name);
            writer.Write(description);
            writer.Write(parts.Count);

            // Add the parts to the archive
            foreach (PackagePart p in parts)
            {
                byte[] bts = Common.PackClass(p);
                writer.Write(bts.Length);
                writer.Write(bts);
            }

            writer.Flush();

            RRR.BasicQ1BinaryFormation q1 = new RRR.BasicQ1BinaryFormation();

            return q1.Patch(memsr.ToArray());
        }

        public Package Build()
        {
            return new Package(type, BuildPrecompiledFile());
        }
    }

    public class Package
    {
        PackageType type;
        List<PackagePart> parts;
        public string name;
        public string description;

        public Package(PackageType t, byte[] preCompiledFile)
        {
            type = t;
            parts = new List<PackagePart>();

            RRR.BasicQ1BinaryFormation q1 = new RRR.BasicQ1BinaryFormation();
            byte[] preCompiledFile2 = q1.DePatch(preCompiledFile);

            MemoryStream memsr = new MemoryStream(preCompiledFile2);
            BinaryReader reader = new BinaryReader(memsr);

            name = reader.ReadString();

            description = reader.ReadString();

            int partscount = reader.ReadInt32();

            for (int i = 0; i < partscount; i++)
            {
                int bytesLen = reader.ReadInt32();
                byte[] bts = reader.ReadBytes(bytesLen);
                PackagePart p = (PackagePart)Common.UnpackClass(bts);
                parts.Add(p);
            }
        }

        public PackagePart[] GetDocumentations()
        {
            return (from docs in parts where docs.Type == PackagePartType.Doc orderby docs.Name select docs).ToArray();
        }

        public PackagePart[] GetPictures()
        {
            return (from pics in parts where pics.Type == PackagePartType.Picture orderby pics.Name select pics).ToArray();
        }

        public PackagePart[] GetFiles()
        {
            return (from files in parts where files.Type == PackagePartType.File orderby files.Name select files).ToArray();
        }
    }

    public static class Common
    {
        public static Dictionary<string, object> RequestsPending = new Dictionary<string, object>();

        public static byte[] PackClass(object c)
        {
            BinaryFormatter binFmt = new BinaryFormatter();
            MemoryStream memSr = new MemoryStream();
            binFmt.Serialize(memSr, c);
            return memSr.ToArray();
        }

        public static object UnpackClass(byte[] c)
        {
            BinaryFormatter binFmt = new BinaryFormatter();
            MemoryStream memSr = new MemoryStream(c);
            return binFmt.Deserialize(memSr);
        }

        public static byte[] StrToBytes(string s)
        {
            return Encoding.ASCII.GetBytes(s);
        }

        public static string BytesToString(byte[] b)
        {
            return Encoding.ASCII.GetString(b);
        }
    }
    #endregion
}
#8 · 13y ago
KE
Kenshin13
Snippet Name: Memory Helper
Keywords: Memory, Editing, Helper
Description: Allows easy access to memory for editing.

Code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Runtime.InteropServices;

namespace MemoryControl
{
    public class MemC
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool WriteProcessMemory(IntPtr hProcess, uint lpBaseAddress, byte[] lpBuffer, uint nSize, out int lpNumberOfBytesWritten);
        [DllImport("kernel32.dll")]
        public static extern int CloseHandle(IntPtr hObject);
        [DllImport("kernel32.dll")]
        public static extern IntPtr OpenProcess(uint dwDesiredAccess, int bInheritHandle, uint dwProcessId);
        [DllImport("kernel32.dll")]
        public static extern int ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, uint size, out IntPtr lpNumberOfBytesRead);
        [DllImport("kernel32.dll")]
        public static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
        [DllImport("kernel32")]
        public static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
        [DllImport("kernel32")]
        public static extern bool VirtualFree(IntPtr lpAddress, UInt32 dwSize, UInt32 dwFreeType);
        [DllImport("kernel32")]
        public static extern IntPtr CreateThread(UInt32 lpThreadAttributes, UInt32 dwStackSize, UInt32 lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId);
        [DllImport("kernel32")]
        public static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
        [DllImport("kernel32")]
        public static extern IntPtr GetModuleHandle(string moduleName);
        [DllImport("kernel32")]
        public static extern UInt32 GetProcAddress(IntPtr hModule, string procName);
        [DllImport("kernel32")]
        public static extern UInt32 LoadLibrary(string lpFileName);
        [DllImport("kernel32")]
        public static extern UInt32 GetLastError();
        [StructLayout(LayoutKind.Sequential)]
        internal struct PROCESSOR_INFO
        {
            public UInt32 dwMax;
            public UInt32 id0;
            public UInt32 id1;
            public UInt32 id2;

            public UInt32 dwStandard;
            public UInt32 dwFeature;

            // If AMD
            public UInt32 dwExt;
        }
 
        public enum AccessProcessTypes
        {
            PROCESS_CREATE_PROCESS = 0x80,
            PROCESS_CREATE_THREAD = 2,
            PROCESS_DUP_HANDLE = 0x40,
            PROCESS_QUERY_INFORMATION = 0x400,
            PROCESS_SET_INFORMATION = 0x200,
            PROCESS_SET_QUOTA = 0x100,
            PROCESS_SET_SESSIONID = 4,
            PROCESS_TERMINATE = 1,
            PROCESS_VM_OPERATION = 8,
            PROCESS_VM_READ = 0x10,
            PROCESS_VM_WRITE = 0x20
        }

        public enum VirtualProtectAccess
        {
            PAGE_EXECUTE = 0x10,
            PAGE_EXECUTE_READ = 0x20,
            PAGE_EXECUTE_READWRITE = 0x40,
            PAGE_EXECUTE_WRITECOPY = 0x80,
            PAGE_NOACCESS = 0x01,
            PAGE_READONLY = 0x02,
            PAGE_READWRITE = 0x04,
            PAGE_WRITECOPY = 0x08,
            PAGE_GUARD = 0x100,
            PAGE_NOCACHE = 0x200,
            PAGE_WRITECOMBINE = 0x400
        }

        public enum VirtualProtectSize
        {
            INT = sizeof(int),
            FLOAT = sizeof(float),
            DOUBLE = sizeof(double),
            CHAR = sizeof(char)
        }

        public static IntPtr cProcessHandle;

        public static  void cOpenProcess(string ProcessX)
        {
            var ApplicationXYZ = Process.GetProcessesByName(ProcessX)[0];
            AccessProcessTypes toAccess = AccessProcessTypes.PROCESS_VM_WRITE | AccessProcessTypes.PROCESS_VM_READ |
                                          AccessProcessTypes.PROCESS_VM_OPERATION;
            cProcessHandle = OpenProcess((uint)toAccess, 1, (uint)ApplicationXYZ.Id);
        }

        public static  void cCloseProcess()
        {
            try
            {
                CloseHandle(cProcessHandle);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static  int getProcessID(string AppX)
        {
            var AppToID = Process.GetProcessesByName(AppX)[0];
            int ID = AppToID.Id; ;
            return ID;
        }

       private static unsafe void WriteThis(IntPtr Address, byte[] XBytesToWrite, int nSizeToWrite)
        {
            int writtenBytes;
            WriteProcessMemory(cProcessHandle, (uint)Address, XBytesToWrite, (uint)nSizeToWrite, out writtenBytes);
        }

        public static  void WriteXNOP(int desiredAddress, int noOfNOPsToWrite)
        {
            byte aNOP = 0x90;
            List<byte> nopList = new List<byte>();
            for (int i=0; i<noOfNOPsToWrite; i++)
                nopList.Add(aNOP);
            byte[] nopBuffer = nopList.ToArray();
            WriteThis((IntPtr) desiredAddress, nopBuffer, noOfNOPsToWrite);
        }

        public static  void WriteXInt(int desiredAddrsss, int valToWrite)
        {
            byte[] valueToWrite = BitConverter.GetBytes(valToWrite);
            WriteThis((IntPtr)desiredAddrsss, valueToWrite, valueToWrite.Length);
        }

        public static  void WriteXFloat(int desiredAddrsss, float valToWrite)
        {
            byte[] valueToWrite = BitConverter.GetBytes(valToWrite);
            WriteThis((IntPtr)desiredAddrsss, valueToWrite, valueToWrite.Length);
        }

        public static  void WriteXDouble(int desiredAddrsss, double valToWrite)
        {
            byte[] valueToWrite = BitConverter.GetBytes(valToWrite);
            WriteThis((IntPtr)desiredAddrsss, valueToWrite, valueToWrite.Length);
        }

        public static  void WriteXString(int desiredAddrsss, string valToWrite)
        {
            byte[] valueToWrite = Encoding.ASCII.GetBytes(valToWrite);
            WriteThis((IntPtr)desiredAddrsss, valueToWrite, valueToWrite.Length);
        }

        public static  void WriteXBytes(int desiredAddress, byte[] bytesToWrite)
        {
            WriteThis((IntPtr)desiredAddress, bytesToWrite, bytesToWrite.Length);
        }

        public static  byte[] readXBytes(int desiredAddress, int noOfBytesToRead)
        {
            byte[] buffer = new byte[noOfBytesToRead];
            IntPtr noOfBytesRead;
            ReadProcessMemory(cProcessHandle, (IntPtr) desiredAddress, buffer, (uint)noOfBytesToRead, out noOfBytesRead);
            return buffer;
        }

        public static  int readXInt(int desiredAddress)
        {
            byte[] buffer = new byte[0xFF];
            IntPtr noOfBytesRead;
            ReadProcessMemory(cProcessHandle, (IntPtr)desiredAddress, buffer, (uint) 4, out noOfBytesRead);
            return BitConverter.ToInt32(buffer, 0);
        }

        public static  float readXFloat(int desiredAddress)
        {
            byte[] buffer = new byte[0xFF];
            IntPtr noOfBytesRead;
            ReadProcessMemory(cProcessHandle, (IntPtr)desiredAddress, buffer, (uint)4, out noOfBytesRead);
            return BitConverter.ToSingle(buffer, 0);
        }

        public static  double readXDouble(int desiredAddress)
        {
            byte[] buffer = new byte[0xFF];
            IntPtr noOfBytesRead;
            ReadProcessMemory(cProcessHandle, (IntPtr)desiredAddress, buffer, (uint)4, out noOfBytesRead);
            return BitConverter.ToDouble(buffer, 0);
        }

        public static  string readXString(int desiredAddress, int sizeOfString)
        {
            byte[] buffer = new byte[sizeOfString];
            IntPtr noOfBytesRead;
            ReadProcessMemory(cProcessHandle, (IntPtr) desiredAddress, buffer, (uint) sizeOfString, out noOfBytesRead);
            return buffer.ToString();
        }
    }
}
#9 · 13y ago
AZ
azmazm
Snippet Name: WebRequest (Useful in automation)
Keywords: Request, Web Bot, Web ...
Code:
Code:
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****;
using System.Net;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();



        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            SubmitData();
        }

        private void SubmitData()
        {
            try
            {
                string dataSubmit = textBox1.Text;

                ASCIIEncoding encoding = new ASCIIEncoding();
                string postData = "" + dataSubmit;
                byte[] data = encoding.GetBytes(postData);

                WebRequest request = WebRequest.Create("link goes here");
                request.Method = "POST";
                reques*****ntentType = "application/x-www-form-urlencoded";
                reques*****ntentLength = data.Length;

                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();

                WebResponse response = request.GetResponse();
                stream = response.GetResponseStream();

                StreamReader sr = new StreamReader(stream);
                MessageBox.Show(sr.ReadToEnd());

                sr.Close();
                stream.Close();



            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        }
    }
#10 · 13y ago
sorpz
sorpz
Snippet Name: Is null or whitespace or empty
Keywords: string, null, empty, whitespace
Description: Totally useless :P but i hate writing this long if-clause every fuckin time
Code:
Code:
public static bool IsNullOrWhitespaceOrEmpty(this string str){
      return (String.IsNullOrEmpty(str) || String.IsNullOrWhiteSpace(str));
}
#11 · 13y ago
♪~ ᕕ(ᐛ)ᕗ
♪~ ᕕ(ᐛ)ᕗ
Snippet Name: Array chunk
Keywords: Array, chunks, split, assemble
Description: Splits an array into different chunks with the same size (expect for the last one).
Code:
    public class Chunk
    {
        public byte[] Data;
        public int Length;

        public static Chunk[] SplitData(byte[] data, int maximumLen)
        {
            int len = data.Length;
            int chCount = (int)Math****und((decimal)(len / maximumLen), MidpointRounding.ToEven) + 1;
            List<Chunk> chks = new List<Chunk>();

            byte[] data2 = data;

            int i = 0;
            do
            {
                if (data2.Length >= maximumLen)
                {
                    byte[] bts = new byte[maximumLen];
                    for (int k = 0; k < maximumLen; k++)
                    {
                        bts[k] = data2[k];
                    }
                    Chunk chk = new Chunk();
                    chk.Data = bts;
                    chk.Length = maximumLen;
                    chks.Add(chk);

                    byte[] tempData = new byte[data2.Length - maximumLen];
                    Array.Copy(data2, maximumLen, tempData, 0, data2.Length - maximumLen);
                    data2 = tempData;
                    Console.WriteLine("[CHUNKS]: Coppied data: " + maximumLen.ToString() + ", remaining: " + data2.Length.ToString());
                }
                else
                {
                    byte[] bts = new byte[data2.Length];
                    for (int k = 0; k < data2.Length; k++)
                    {
                        bts[k] = data2[k];
                    }
                    Chunk chk = new Chunk();
                    chk.Data = bts;
                    chk.Length = maximumLen;
                    chks.Add(chk);
                    Console.WriteLine("[CHUNKS]: Coppied data: " + data2.Length + ", remaining: " + 0.ToString());
                }
                
                i++;
            }
            while (i < chCount);
            return chks.ToArray();
        }

        public static byte[] AssembleChunks(Chunk[] chunks)
        {
            MemoryStream memsr = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(memsr);
            for (int i = 0; i < chunks.Length; i++)
            {
                writer.Write(chunks[i].Data);
            }
            writer.Flush();
            return memsr.ToArray();
        }
    }
#12 · 13y ago
wei.chen.testai
wei.chen.testai
BasicStatistics
Snippet Name: BasicStatistics
Keywords: Statistics
Description: Mean, Standard Deviation, Transpose Matrix

Code:
    class BasicStatistics
    {
        public double X_mean;
        public double X_std;

        public BasicStatistics() { }

        public BasicStatistics(double[] X)
        {
            X_mean = 0;
            X_std = 0;
            X_mean = mean(X);
            X_std = std(X);
        }

        private double mean(double[] X)
        {
            for (int i = 0; i < X.Length; i++) { X_mean += X[i]; }
            X_mean /= X.Length;
            return X_mean;
        }

        private double std(double[] X)
        {
            for (int i = 0; i < X.Length; i++) { X_std += Math.Pow(X[i] - X_mean, 2); }
            X_std /= (X.Length-1);
            X_std = Math.Sqrt(X_std);
            return X_std;
        }

        public double[][] TransposeMatrix(double[][] X)
        {
            double[] temp = X[0];
            double[][] Y = new double[temp.Length][];
            for (int i = 0; i < temp.Length; i++)
            {
                Y[i] = new double[X.GetLength(0)];
                for (int j = 0; j < X.GetLength(0); j++)
                    Y[i][j] = X[j][i];
            }
            return Y;
        }
    }
#13 · 13y ago
XZ
xZekaHD
Snippet Name: _Disabling the Windows 'X' Close button in a C# Form
Keywords: Disable,X Button,_Close
Description(Optional): Writing this code under "Initialize Component" will disable the close or 'X' Button at the top right of the windows form
Code:

Code:
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parms = base.CreateParams;
                parms.ClassStyle |= 0x200;
                return parms;
            }
        }
#14 · edited 12y ago · 12y ago
IM
Impulser
Not to dishearten the posts on this thread, but they need a lot of work and thought into what they are actually doing. For example here's a custom partitioner which provides the same behaviour as the previous post but it is a lot more efficient.

Code:
Snippet Name: RangePartitioner
Keywords: More, Efficient, Range, Partitioner, Generic

using System;
using System.Collections.Generic;
using System.Linq;

#define NonGenericPartition

namespace Impulser.SharpExamples
{
#if NonGenericPartition
    public class RangePartition<T> : List<T>
    {
        public RangePartition(T element, int size)
                : base(Enumerable.Repeat(element, size)) { }
#else
    public class RangePartition : List<int>
    {
        public RangePartition(int from, int size)
            : base(Enumerable.Range(from, size)) { }
#endif

        public static IEnumerable<IList<int>> CreatePartitionedRange(int from, int to, int cardinality)
        {
            var partitionSize = from > to
                                        ? from - to
                                        : to - from;
            while (--partitionSize > 0)
            {
                var partitionLen = Math.Min(to - from, cardinality);
                yield return new RangePartition<int>(from, partitionLen);
                from += partitionLen;
            }
        }

        public static IEnumerable<IList<TValue>> CreatePartitionedRepitiion<TValue>(int from, int to, int cardinality, TValue repeatValue)
        {
            var partitionSize = from > to
                                        ? from - to
                                        : to - from;
            while (--partitionSize > 0)
            {
                var partitionLen = Math.Min(to - from, cardinality);
                yield return new RangePartition<TValue>(repeatValue, partitionLen);
                from += partitionLen;
            }
        }
    }
}
#15 · edited 11y ago · 11y ago
Posts 1–15 of 22 · Page 1 of 2

Post a Reply

Similar Threads

  • Snippets VaultBy NextGen1 in Visual Basic Programming
    112Last post 7y ago
  • [Collection]Snippets Vault[PHP]By NextGen1 in PHP Programming
    13Last post 7y ago
  • [Collection]Snippets Vault[Assembly]By NextGen1 in Assembly
    5Last post 13y ago
  • [Collection]Snippets Vault[Flash]By NextGen1 in Flash & Actionscript
    3Last post 14y ago
  • [Collection]Snippets Vault[D3D]By NextGen1 in DirectX/D3D Development
    0Last post 15y ago

Tags for this Thread

None