=== Example program for splitting on spaces (C#) ===
using System;
class Program { static void Main() { string s = "there is a cat"; // // Split string on spaces. // ... This will separate all the words. // string[] words = s.Split(' '); foreach (string word in words) { Console.WriteLine(word); } } }
The click event gets activated when a button is clicked on. Examine the default code for a button: private void button1_Click(object sender, EventArgs e) { } In between the round brackets, we have this:
object sender, EventArgs e
The object keyword refers to the object which activated the event, a button in this case. This is being placed in a variable called sender. You can test this for yourself. Start a new project. Add a button to your new form and double click it. Place the following code between the curly brackets:
MessageBox.Show( sender.ToString() );
We're just using the ToString method on the sender variable. Run your programme and click the button. You should see this:
The Message is displaying which object was the sender of the event, as well as displaying the Text property of the sender: the button with the Text "button1". The other argument in between the round brackets was this:
EventArgs e
EventArgs is a class. It's short for event arguments, and tells you which events was raised. The letter "e" sets up a variable to use this class. If you change your line of code to this:
// This "DoMath" delegate can point to ANY method that: // - Returns an int // - Accepts two ints as parameters public delegate int DoMath(int x, int y);
private void button1_Click(object sender, EventArgs e) { int result;
DoMath a = new DoMath(Add); result = a(3, 4); MessageBox.Show(Convert.ToString(result));
UseDelegate(a); }
public void UseDelegate(DoMath x) { int r = x(6, 6); MessageBox.Show(Convert.ToString(r));
}
//This method can be pointed to by the DoMath delegate public int Add(int x, int y) { return x+y; }
//This method can be pointed to by the DoMath delegate public int Subtract(int x, int y) { return x - y; }
//This method can NOT be pointed to by the DoMath delegate //because it has a different signature (only one argument) public string Test(string y) { return "Test method"; } }
To add embedded resources to your project, you must first add the files as part of your project. After you have added the files to your project, you can access and display the resources through the System.Reflection namespace.
Add Embedded Resources
To add a text file and an image file to your project as embedded resources, follow these steps:
Create a new Windows Application project for this demonstration. This form is used to display the resources that are accessed from the executing assembly during run time.
Right-click your project name, click Add, and then click Add New Item.
In the New Item dialog box, select Text File from the menu, and name the file MyTextFile.txt. When the file opens in the integrated development environment (IDE), add some text, and then close the file.
Repeat steps 1 and 2 to add a bitmap image to your project, but instead of selecting Text File as the new item type, select Bitmap File, and then change the file name to MyImage.bmp. When the new image is opened in the IDE, draw something on the image, and then close the file.
Right-click either the text file or the bitmap, and then select Properties.
In the Properties dialog box, locate the Build Action property. By default, this property is set to Content. Click the property and change the Build Action property to Embedded Resource.
Repeat steps 4 and 5 for the other file.
The next time you build the project, the compiler adds these files to your assembly. The compiler adds the root namespace of the project to the name of the resource when it is included in the project. For example, if the root namespace of your project is MyNamespace, the resources are named MyNamespace.MyTextFile.txt and MyNamespace.MyImage.bmp. NOTE: The resource file names are case-sensitive. When you access the resources, you must use the exact spelling and case of the file name. If you do not use the exact spelling and case of the file name, the method call to access the ManifestResourceStream returns Nothing, and the system does not raise an exception. NOTE: If you want to verify the resource names, you can use the Microsoft Intermediate Language Disassembler (ILDASM) to view the Manifest data, which lists the included resources.
Access Resources
To access the resources that you have embedded in the Manifest of your assembly, import the System.IO and the System.Reflection namespaces, as follows:
using System.IO; using System.Reflection;
The System.IO namespace provides the definition of a stream and the System.Reflection namespace defines the Assembly class that provides methods to access the resources that are embedded in your assembly.
When you declare the following in the general declaration area, the resources from the assembly are read when the form is loaded:
NOTE: To access the Load event for the form in the Code Editor, double-click the form in the Design Editor.
To read the resource from the assembly that is executing the current code, you must obtain an instance of that assembly. To do this, use the GetExecutingAssembly method of the assembly, as follows:
_assembly = Assembly.GetExecutingAssembly();
Reading the information from the resource to a stream is performed with a method call to GetManifestResourceStream. The parameter that is passed to this method is the name of the resource that is to be accessed. The two resources are then read to their corresponding streams as the Load event of the form is executed.
_imageStream = _assembly.GetManifestResourceStream("MyNameSpace.MyImage.bmp"); _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNameSpace.MyTextFile.txt"));
The code in the Load event for the form resembles the following:
The Try-Catch statement, known as structured error handling in .NET, is used to catch any errors that may have occurred while the instance of the Assembly class accesses the resources.
Display Resources
This example uses two buttons to display the embedded resources. When you click the first button, a bitmap image that is based on the resource that is read from the assembly is created and displayed in the PictureBox
To display the embedded resources, follow these steps: control of the form. The second button reads from a text resource and displays the text in a text box.
Add a PictureBox control to the form.
Add a new Button control to the form, and then change its Text property to Show Image.
Double-click the button to open its Click event in the code viewer, and then paste the following code in this event:
/* Author: Perry Lee * Submission: Capture Screen (Add Screenshot Capability to Programs) * Date of Submission: 12/29/03 */ using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; // If you have any questions regarding functions (methods) imported from // GDI32.dll and User32.dll refer to 'msdn.microsoft.com' class GDI32 { [DllImport("GDI32.dll")] publicstaticexternbool BitBlt(int hdcDest,int nXDest,int nYDest,int nWidth,int nHeight,int hdcSrc,int nXSrc,int nYSrc,int dwRop); [DllImport("GDI32.dll")] publicstaticexternint CreateCompatibleBitmap(int hdc,int nWidth, int nHeight);[DllImport("GDI32.dll")] publicstaticexternint CreateCompatibleDC(int hdc); [DllImport("GDI32.dll")] publicstaticexternbool DeleteDC(int hdc); [DllImport("GDI32.dll")] publicstaticexternbool DeleteObject(int hObject); [DllImport("GDI32.dll")] publicstaticexternint GetDeviceCaps(int hdc,int nIndex); [DllImport("GDI32.dll")] publicstaticexternint SelectObject(int hdc,int hgdiobj); class User32 { [DllImport("User32.dll")] publicstaticexternint GetDesktopWindow(); [DllImport("User32.dll")] publicstaticexternint GetWindowDC(int hWnd); [DllImport("User32.dll")] publicstaticexternint ReleaseDC(int hWnd,int hDC); } class Example { publicvoid CaptureScreen(string fileName,ImageFormat imageFormat) { int hdcSrc = User32.GetWindowDC(User32.GetDesktopWindow()), hdcDest = GDI32.CreateCompatibleDC(hdcSrc), hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, GDI32.GetDeviceCaps(hdcSrc,8),GDI32.GetDeviceCaps(hdcSrc,10)); GDI32.SelectObject(hdcDest,hBitmap); GDI32.BitBlt(hdcDest,0,0,GDI32.GetDeviceCaps(hdcSrc,8), GDI32.GetDeviceCaps(hdcSrc,10),hdcSrc,0,0,0x00CC0020); SaveImageAs(hBitmap,fileName,imageFormat); Cleanup(hBitmap,hdcSrc,hdcDest); } privatevoid Cleanup(int hBitmap,int hdcSrc,int hdcDest) { User32.ReleaseDC(User32.GetDesktopWindow(),hdcSrc); GDI32.DeleteDC(hdcDest); GDI32.DeleteObject(hBitmap); } privatevoid SaveImageAs(int hBitmap,string fileName,ImageFormat imageFormat) { Bitmap image = new Bitmap(Image.FromHbitmap(new IntPtr(hBitmap)), Image.FromHbitmap(new IntPtr(hBitmap)).Width, Image.FromHbitmap(new IntPtr(hBitmap)).Height); image.Save(fileName,imageFormat); } } Explanation of methods: publicvoid CaptureScreen(string fileName,ImageFormat imageFormat) { int hdcSrc = User32.GetWindowDC(User32.GetDesktopWindow()), // Get a handle to the desktop windowhdcDest = GDI32.CreateCompatibleDC(hdcSrc), // Create a memory device contexthBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, // Create a bitmap and place it in the memory DC GDI32.GetDeviceCaps(hdcSrc,8),GDI32.GetDeviceCaps(hdcSrc,10)); // GDI32.GetDeviceCaps(hdcSrc,8) returns the width of the desktop window// GDI32.GetDeviceCaps(hdcSrc,10) returns the height of the desktop windowGDI32.SelectObject(hdcDest,hBitmap); // Required to create a color bitmapGDI32.BitBlt(hdcDest,0,0,GDI32.GetDeviceCaps(hdcSrc,8), // Copy the on-screen image into the memory DCGDI32.GetDeviceCaps(hdcSrc,10),hdcSrc,0,0,0x00CC0020); SaveImageAs(hBitmap,fileName,imageFormat); // Save the screen-capture to the specified file using the designated image formatCleanup(hBitmap,hdcSrc,hdcDest); // Free system resources} privatevoid Cleanup(int hBitmap,int hdcSrc,int hdcDest) { // Release the device context resources back to the systemUser32.ReleaseDC(User32.GetDesktopWindow(),hdcSrc); GDI32.DeleteDC(hdcDest); GDI32.DeleteObject(hBitmap); } privatevoid SaveImageAs(int hBitmap,string fileName,ImageFormat imageFormat) { // Create a bitmap from the Windows handleBitmap image = new Bitmap(Image.FromHbitmap(new IntPtr(hBitmap)), Image.FromHbitmap(new IntPtr(hBitmap)).Width, Image.FromHbitmap(new IntPtr(hBitmap)).Height); image.Save(fileName,imageFormat); }
The serialized stream can be encrypted, authenticated and compressed, supporting the needs of secure Java computing.
Serialized classes can support coherent versioning and are flexible enough to allow gradual evolution of your application's object schema.
Serialization can also be used as a mechanism for exchanging objects between Java and C++ libraries, using third party vendor libraries (like RogueWave's Tools.h++ ) within C++.
There are simply too many critical technologies that rely upon serialization, including RMI, JavaBeans and EJB.
However, serialization has some disadvantages too:
It should ideally not be used with large-sized objects, as it offers significant overhead. Large objects also significantly increase the memory requirements of your application since the object input/output streams cache live references to all objects written to or read from the stream until the stream is closed or reset. Consequently, the garbage collection of these objects can be inordinately delayed.
The Serializable interface does not offer fine-grained control over object access - although you can somewhat circumvent this issue by implementing the complex Externalizable interface, instead.
Since serialization does not offer any transaction control mechanisms per se, it is not suitable for use within applications needing concurrent access without making use of additional APIs.
Serialization is the process of converting an object into a stream of bytes in order to persist it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
How Serialization Works
This illustration shows the overall process of serialization.
The object is serialized to a stream, which carries not just the data, but information about the object's type, such as its version, culture, and assembly name. From that stream, it can be stored in a database, a file, or memory.
Uses for Serialization
Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.
Making an Object Serializable
To serialize an object, you need the object to be serialized, a stream to contain the serialized object, and a Formatter. System.Runtime.Serialization contains the classes necessary for serializing and deserializing objects. Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. A SerializationException exception is thrown if you attempt to serialize but the type does not have the SerializableAttribute attribute. If you do not want a field within your class to be serializable, apply the NonSerializedAttribute attribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and the field cannot be meaningfully reconstituted in a different environment, then you may want to make it nonserializable. If a serialized class contains references to objects of other classes that are marked SerializableAttribute, those objects will also be serialized.
Binary and XML Serialization
Either binary or XML serialization can be used. In binary serialization, all members, even those that are read-only, are serialized, and performance is enhanced. XML serialization provides more readable code, as well as greater flexibility of object sharing and usage for interoperability purposes.
Binary Serialization
Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network streams.
XML Serialization
XML serialization serializes the public fields and properties of an object, or the parameters and return values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization contains the classes necessary for serializing and deserializing XML. You can apply attributes to classes and class members in order to control the way the XmlSerializer serializes or deserializes an instance of the class.
SOAP Serialization
XML serialization can also be used to serialize objects into XML streams that conform to the SOAP specification. SOAP is a protocol based on XML, designed specifically to transport procedure calls using XML. As with regular XML serialization, attributes can be used to control the literal-style SOAP messages generated by an XML Web service.
/* Port Scanner * http://ProjectGhostt.com * FreckleS */
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets;
namespace Port_Scanner { class Program { static void Main(string[] args) { // Scan specific port int port = 135; if (TestPort(port) == true) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Port {0} is OPEN!", port); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Port {0} is CLOSED!", port); }
// Scan a range of ports for (int i = 1; i < 1000; i++) // for (int i = startPort; i < stopPort; increment port) { if (TestPort(i) == true) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Port {0} is OPEN!", i); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Port {0} is CLOSED!", i); } } }
When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
publicabstractint Read( byte[] buffer, int offset, int count )
When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
// Adam Boulfoul - "A Beginner's Simple Encryption Tutorial / Example" chebby_shabby@hotmail.com ///////////////////////////////////////////////////////////////////////////////////////////////// // This is not an "uncrackable" type of encryption but once you can understand the basics of // this type of file encryption you CAN make better ones than me. This is just a quick example // of basic encryption. Highly commented to help beginners. ///////////////////////////////////////////////////////////////////////////////////////////////// // Before we start: // What this basic program does is simply getting a byte from a file then adding 25 to it // (ofcouse you can change it to whatever you like). ///////////////////////////////////////////////////////////////////////////////////////////////// // If you have any questions, my e-mail is above /////////////////////////////////////////////////////////////////////////////////////////////////
#include // We need this for input and output to the user #include // This is the header to read or write files #include // We only need this to delete a file using remove() // As mentioned abode, we simply add 25 to a byte, change this to whatever you like. #define ENCRYPTION_FORMULA (int) Byte + 25 // The decryption formula is the opposite to encryption formula, every "+" is a "-" #define DECRYPTION_FORMULA (int) Byte - 25
/////////////////////////////////////////////////////////////////////////////////////////// // TIP: Everytime you see ENCRYPTION_FORMULA ot DECRYPTION_FORMULA mensioned, highlight it // then press on definition and it will bring you up here! (Only on Visual C++) ///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////// // Our main function, put this in your program, FILENAME is the file to encrypt // and NEW_FILENAME is the new location of the encrypted file /////////////////////////////////////////////////////////////////////////////////
int Encrypt (char * FILENAME, char * NEW_FILENAME) { ifstream inFile; // This is the file that we're going to encrypt and read ofstream outFile; // Once we encrypt the file, this is it's new location
char Byte; // This is the FILENAME's byte, we'll add 25 to this later
/////////////////////////////////////////////////////////////// // Before we continue: // ios:: in - Used for reading a file // ios::out - Used for writing a file // ios::binary - Used for reading or writing binary files ///////////////////////////////////////////////////////////////
inFile.open(FILENAME, ios::in | ios::binary); // We read this file in binary mode outFile.open(NEW_FILENAME, ios::out | ios::binary); // And we write the file in binary mode
// eof() stands for End Of File, so while we are still reading the file, continue while(!inFile.eof()) { // Remember we need to change a byte so we add 25 to it char NewByte;
////////////////////////////////////////////////// // NOTE: Only use the .put() and .get() in loops // because it only reads 1 Byte at a time! //////////////////////////////////////////////////
// Out old byte is recieved from the file Byte = inFile.get();
// If the file that we are reading has an error, turn 0 if (inFile.fail()) return 0; //Remember our Encryption Formula above? //Our new byte is recieved from it, see above NewByte = ENCRYPTION_FORMULA; // This simple puts the new byte, into the new file! outFile.put(NewByte); }
// We have to be neat so we close both the file that we're reading // and the file that we're writing inFile.close(); // (File to read) outFile.close(); // (File to write)
return 1; // Success! }
/////////////////////////////////////////////////////////////////////////////// // What's the point of encrypting a file if you can't decrypt it? // If you're wondering why this is not commented it's because I've already // explained everything above, notice that everything is the same except for // two lines! ///////////////////////////////////////////////////////////////////////////////
if (inFile.fail()) return 0; ///////////////////////////////////////////////////// NewByte = DECRYPTION_FORMULA; // New Line! We just change the ENCRYPTION_FORMULA // to DECRYPTION_FORMULA, see above ///////////////////////////////////////////////////// outFile.put(NewByte); }
inFile.close(); outFile.close();
return 1; }
/////////////////////////////////////////////////////////////////////// // WARNING: If you choose to decrypt a file that it already decrypted // then the file would be encrypted! ///////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////// // To use the functions in your program (doesn't have to be a DOS program), // copy the 2 functions above, this is just an example, in the example I'm // encrypting ///////////////////////////////////////////////////////////////////////////////////
int main() { /////////////////////////////////////////////////////////////////// // The functions can be used in not only DOS programs // Since this is an example, I'll show you how to use them ///////////////////////////////////////////////////////////////////
char EncFile[200]; // This is the string for the file to be encrypted char NewEncFile[200]; // This is the new location of the encrypted file
char DecFile[200]; // This is the string for the file to be decrypted char NewDecFile[200]; // This is the new location of the decrypted file
// In case you didn't know, all these "cout" just display a message // Cin tells the user to input something cout << "NOTE: You must encrypt the file with the same file extension!"< cout << "Enter 1 to Encrypt / 2 to Decrypt"< cin >> Choice; // In this case, our input is the user's choice
switch(Choice) { case 1: // Did the user choose to encrypt a file? cout << "Enter the current Filename: "; cin >> EncFile; // The user's input for the current file to be encrypted
cout << "Enter the new Filename: "; cin >> NewEncFile; //The user's input for the new location of the encrypted file
Encrypt(EncFile, NewEncFile); /*********** ENCRYPT FUNCTION ************/ break;
case 2: // Or did the user choose to decrypt a file? cout << "Enter the current Filename: "; cin >> DecFile; //Already explained but with the decrypted file this time!
cout << "Enter the new Filename: "; cin >> NewDecFile;
Decrypt(DecFile, NewDecFile); /*********** DECRYPT FUNCTION ************/ break; }
return 0; //Exit! }
////////////////////////////////////////////////////////////////////////////////// // That's it! Looks so long yet it's so simple and easy to understand! ////////////////////////////////////////////////////////////////////////////////// // So what we basicly done is open a file and add 25 to every byte of the file! // Very simple! ////////////////////////////////////////////////////////////////////////////////// // Any questions to chebby_shabby@hotmail.com // If this tutorial is successful then my next tutorial is // "A Beginner's Simple Compression Tutorial / Example ////////////////////////////////////////////////////////////////////////////////// // by Adam Boulfoul //////////////////////////////////////////////////////////////////////////////////
using System; using System.IO; using System.Security; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Text;
namespace CSEncryptDecrypt { class Class1 { // Call this function to remove the key from memory after use for security [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint="RtlZeroMemory")] public static extern bool ZeroMemory(IntPtr Destination, int Length);
// Function to Generate a 64 bits Key. static string GenerateKey() { // Create an instance of Symetric Algorithm. Key and IV is generated automatically. DESCryptoServiceProvider desCrypto =(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
// Use the Automatically generated key for Encryption. return ASCIIEncoding.ASCII.GetString(desCrypto.Key); }
static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey) { DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //Set initialization vector. DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
//Create a file stream to read the encrypted file back. FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); //Print the contents of the decrypted file. StreamWriter fsDecrypted = new StreamWriter(sOutputFilename); fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd()); fsDecrypted.Flush(); fsDecrypted.Close(); }
static void Main() { // Must be 64 bits, 8 bytes. // Distribute this key to the user who will decrypt this file. string sSecretKey;
// Get the Key for the file to Encrypt. sSecretKey = GenerateKey();
// For additional security Pin the key. GCHandle gch = GCHandle.Alloc( sSecretKey,GCHandleType.Pinned );
// Encrypt the file. EncryptFile(@"C:\MyData.txt", @"C:\Encrypted.txt", sSecretKey);
// Decrypt the file. DecryptFile(@"C:\Encrypted.txt", @"C:\Decrypted.txt", sSecretKey);
// Remove the Key from memory. ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2); gch.Free(); } } }