Page 1 of 2 12 LastLast
Results 1 to 15 of 22
  1. #1
    NextGen1's Avatar
    Join Date
    Dec 2009
    Gender
    male
    Location
    Not sure really.
    Posts
    6,312
    Reputation
    382
    Thanks
    3,019
    My Mood
    Amazed

    [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.




     


     


     



    The Most complete application MPGH will ever offer - 68%




  2. #2
    SPittn_Blood's Avatar
    Join Date
    Nov 2009
    Gender
    male
    Posts
    148
    Reputation
    10
    Thanks
    15
    My Mood
    Inspired

    Post 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());
    Last edited by SPittn_Blood; 10-01-2010 at 11:51 PM.

    Pixie force!

    -Current Projects-
    _______________________
    \//Stuff.. :P//\
    Current Code: C#

  3. The Following 2 Users Say Thank You to SPittn_Blood For This Useful Post:

    Lyoto Machida (05-09-2011),NextGen(1) (10-03-2010)

  4. #3
    NextGen1's Avatar
    Join Date
    Dec 2009
    Gender
    male
    Location
    Not sure really.
    Posts
    6,312
    Reputation
    382
    Thanks
    3,019
    My Mood
    Amazed
    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();
       }
    }
    Last edited by NextGen1; 10-04-2010 at 04:12 PM.


     


     


     



    The Most complete application MPGH will ever offer - 68%




  5. #4
    Kuro Tenshi's Avatar
    Join Date
    Jan 2009
    Gender
    male
    Location
    Where arth thou be
    Posts
    3,635
    Reputation
    70
    Thanks
    746
    My Mood
    Blah
    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]
    Last edited by Kuro Tenshi; 12-10-2010 at 03:12 AM.
    DigiDrawing|+ ( (Elfen Archer) )
    Link:
    https://www.mpgh.net/forum/148-showro...en-archer.html


    @ Anime Section,Otaku/weeabo (orz.) @Graphics Section, Novice DigiArtist


    neuest gift from Yura~Chan:
    https://bakyurayuu.deviantar*****m/#/d372taw
    2nd Place MOTM#9 Theme: CharMods - Combat Arms [No - Thanks] button
    come on you know that don't want to push that ordinary button

  6. #5
    SeptFicelle's Avatar
    Join Date
    Nov 2010
    Gender
    female
    Location
    In your backyard.
    Posts
    75
    Reputation
    10
    Thanks
    16
    My Mood
    Amused
    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.
    You see, maddness, as we know, is like gravity, all it takes is a little push.



    -------------------------------------
    Current Focus: C#
    Languages Known: C++, C#, F#, .NET
    Specialty: Inspection Of Algorithms
    Schooling Focus: Astrobiology
    -------------------------------------

    [IMG]https://i276.photobucke*****m/albums/kk13/Teddynezz/overallsig.png[/IMG]
    [IMG]https://i276.photobucke*****m/albums/kk13/Teddynezz/userbar97571.gif[/IMG]
    [IMG]https://i276.photobucke*****m/albums/kk13/Teddynezz/skypeuser5gu.png[/IMG]
    [IMG]https://i276.photobucke*****m/albums/kk13/Teddynezz/3dsmax9userot0.gif[/IMG]

  7. #6
    ♪~ ᕕ(ᐛ)ᕗ's Avatar
    Join Date
    Jun 2010
    Gender
    male
    Location
    Uterus
    Posts
    9,119
    Reputation
    1096
    Thanks
    1,970
    My Mood
    Doh
    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;
                }
            }
        }
    }

  8. #7
    ♪~ ᕕ(ᐛ)ᕗ's Avatar
    Join Date
    Jun 2010
    Gender
    male
    Location
    Uterus
    Posts
    9,119
    Reputation
    1096
    Thanks
    1,970
    My Mood
    Doh
    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);
    			}
    		}
    	}
    
    }

  9. #8
    ♪~ ᕕ(ᐛ)ᕗ's Avatar
    Join Date
    Jun 2010
    Gender
    male
    Location
    Uterus
    Posts
    9,119
    Reputation
    1096
    Thanks
    1,970
    My Mood
    Doh
    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
    }

  10. #9
    Kenshin13's Avatar
    Join Date
    May 2011
    Gender
    male
    Location
    Cloud 9
    Posts
    3,470
    Reputation
    564
    Thanks
    6,168
    My Mood
    Psychedelic
    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();
            }
        }
    }

  11. The Following 2 Users Say Thank You to Kenshin13 For This Useful Post:

    icebolt900 (11-19-2014),Plutonsvea (05-16-2015)

  12. #10
    azmazm's Avatar
    Join Date
    Feb 2010
    Gender
    male
    Posts
    10
    Reputation
    10
    Thanks
    2
    My Mood
    Asleep
    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);
                }
    
            }
    
            }
        }

  13. The Following User Says Thank You to azmazm For This Useful Post:

    SnRolls (03-27-2015)

  14. #11
    sorpz's Avatar
    Join Date
    Dec 2012
    Gender
    male
    Location
    C:\Countries\Germany\Frankfurt\..
    Posts
    35
    Reputation
    23
    Thanks
    115
    My Mood
    Hungover
    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));
    }
    Check out my...
    ProcessAccessor
    project. It got some cool features ..




  15. #12
    ♪~ ᕕ(ᐛ)ᕗ's Avatar
    Join Date
    Jun 2010
    Gender
    male
    Location
    Uterus
    Posts
    9,119
    Reputation
    1096
    Thanks
    1,970
    My Mood
    Doh
    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();
            }
        }

  16. #13
    wei.chen.testai's Avatar
    Join Date
    Aug 2013
    Gender
    male
    Location
    Taipei
    Posts
    2
    Reputation
    10
    Thanks
    10
    My Mood
    Confused

    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;
            }
        }

  17. #14
    xZekaHD's Avatar
    Join Date
    Nov 2013
    Gender
    male
    Location
    UK
    Posts
    12
    Reputation
    10
    Thanks
    6
    My Mood
    Buzzed
    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;
                }
            }
    Last edited by xZekaHD; 01-18-2014 at 12:11 PM.

  18. #15
    Impulser's Avatar
    Join Date
    Jan 2011
    Gender
    male
    Posts
    1
    Reputation
    10
    Thanks
    0
    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;
                }
            }
        }
    }
    Last edited by Impulser; 01-09-2015 at 11:48 PM.

Page 1 of 2 12 LastLast

Similar Threads

  1. [Source Code] Snippets Vault
    By NextGen1 in forum Visual Basic Programming
    Replies: 112
    Last Post: 06-14-2019, 07:51 PM
  2. [Collection]Snippets Vault[PHP]
    By NextGen1 in forum PHP Programming
    Replies: 13
    Last Post: 10-13-2018, 09:10 PM
  3. [Collection]Snippets Vault[Assembly]
    By NextGen1 in forum Assembly
    Replies: 5
    Last Post: 11-05-2012, 01:10 AM
  4. [Collection]Snippets Vault[Flash]
    By NextGen1 in forum Flash & Actionscript
    Replies: 3
    Last Post: 10-14-2011, 03:08 AM
  5. [Collection]Snippets Vault[D3D]
    By NextGen1 in forum DirectX/D3D Development
    Replies: 0
    Last Post: 09-28-2010, 08:36 AM