Showing articles from C# tag

Nancy + Static Content + OWIN + SystemWeb
Serving static content with Nancy on IIS through OWIN and SystemWeb didn't work out of the box. The problem and the fix.

GPG in Outlook 2007 - OutlookGnuPG
No GPG plugin supported Outlook 2007, so I wrote my own: OutlookGnuPG, for signing mail with GPG straight from Outlook.

A Reworked MVC Preview 5 AccountController
ASP.NET MVC Preview 5's default AccountController didn't use the new form posting and validation features yet, so I reworked it. The controller and views, ready to copy.

C# World Of Warcraft Armory Library 0.1
A C# library for the World of Warcraft Armory, written to fill my guild's website with character statistics.

ArrayList Class
Resizable, index-based collection that boxes value types and supports foreach through IEnumerable.

BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.

BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.

BitVector32 Structure and BitVector32.Section Structure
Manipulates the bits of a 32-bit integer and packs multiple small numbers into one when storage is an issue.

Boxing And Unboxing
Boxing implicitly converts a value type to object by copying it to the heap; unboxing explicitly converts it back.

BufferedStream Class
Provides a buffer for another Stream, for when the underlying stream is not efficient at handling frequent calls.

CollectionsUtil Class
Helper class to create a case-insensitive Hashtable or SortedList.

Comparer Class
Default comparer used when sorting, for example with an ArrayList. Implements the IComparer interface.

DeflateStream Class
Compresses and decompresses data, with slightly smaller output than GZipStream because it omits header information.

Delegate Class
Holds a reference to a method; declared in a single line, with the framework providing the underlying implementation.

Directory Class and DirectoryInfo Class
DirectoryInfo extends FileSystemInfo with directory-specific operations and can represent a directory that does not exist yet.

DriveInfo Class and DriveType Enumeration
DriveInfo gives drive type, format, label and free space; AvailableFreeSpace is the free space for the current user, TotalFreeSpace for the whole drive.

Encode text by using Encoding classes
Encoding classes: listing available encodings and writing the same text as UTF-7, UTF-8, UTF-16 and UTF-32 to compare the files.

EventArgs Class
EventArgs carries event data; use it for events without data and derive from it to pass custom data.

EventHandler Delegates
EventHandler and EventHandler<T> let you define events without declaring your own delegate, plus a pattern for disposing event listeners.

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Exception classes
Exception class hierarchy, catch ordering, finally, try/catch/finally scopes and the recommended constructors for custom exceptions.

File Class and FileInfo Class
File and FileInfo: file-specific operations, static helpers, NTFS encryption, replacing a file with a backup, and writing or appending text.

FileStream Class
Provides a file-specific implementation of a Stream.

FileSystemInfo Class and FileSystemWatcher Class
FileSystemInfo is the base class of FileInfo and DirectoryInfo; FileSystemWatcher monitors a directory for created, deleted, renamed and changed files.

Generic Dictionary class
Generic version of the Hashtable class, storing its items as KeyValuePair<TKey, TValue>.

Generic KeyValuePair structure
Defines a key/value pair, the element type you get when enumerating a generic Dictionary.

Generic List class
Generic version of the ArrayList class, with support for Comparison<T> delegates when sorting.

Generic Queue class
Generic version of the Queue class.

Generic SortedDictionary class
Sorted version of the generic Dictionary class. It stores KeyValuePair items and sorts them automatically by key.

Generic SortedList Class
Generic version of the SortedList class, a key-value collection that automatically sorts items based on the key.

Generic Types
Generics let the caller fill in type placeholders, giving strongly typed collections with compile-time type checking and optional constraints.

Group Class and GroupCollection Class
Contains the named and unnamed results of matches in a regex. Unnamed results are numbered starting from 1.

GZipStream Class
Compresses and decompresses data in gzip format. Output is slightly larger than DeflateStream because of extra header information.

Hashtable Class
Non-generic key-value collection of DictionaryEntry objects, accessed by key rather than by index and stored by hash code.

ICloneable Interface
Enables objects to be cloned, without specifying deep or shallow copy, which makes it problematic in public APIs.

IComparable Interface
IComparable is required for sorting. CompareTo returns less than 0, 0 or greater than 0 to order the current object relative to another.

IConvertible Interface
Enables a class to be converted to a base type such as Boolean, Byte, Double or String, plus widening, narrowing and operator conversions.

IDisposable Interface
Enables users of your class to free the resources an instance has consumed. Implement it for disposable members or native resources.

IEquatable Interface
Enables instances of a class to be compared for equality through a strongly typed Equals method.

IFormattable Interface
Enables classes to control how they are formatted, with more options than ToString.

IsolatedStorageFile Class
Represents an isolated storage area for application-specific data, with a machine-level and a user-level store per assembly.

IsolatedStorageFileStream Class
Exposes a file inside an isolated store as a FileStream; file paths are relative to the store.

Match Class and MatchCollection Class
Contains the results of matching a regex against a string.

MemoryStream Class
Provides an in-memory Stream for temporary data, for example to avoid keeping a file locked by a FileStream for long.

NameValueCollection Class
Like a StringDictionary, but can store multiple values under the same key; values can be retrieved by key or index.

Path Class
Provides helper methods for working with file system paths as strings.

Queue Class
First-in, first-out collection, like a queue of customers in a bank.

Reference Types
Reference type data lives on the heap and is cleaned up by the garbage collector; copying a reference copies only the pointer.

Regex Class
Used to work with regular expressions: anchoring patterns safely, plus examples of matching, replacing and named groups.

Snippets
C# snippets: operator overloading on an immutable struct, and a Predicate used with Array.TrueForAll.

SortedList Class
Key-value pair based collection. Contains DictionaryEntry objects. Accessible by index and key. Sorts items when they are added.

Specialized Dictionary
Specialized dictionaries ListDictionary, HybridDictionary and OrderedDictionary, and when to use each instead of a Hashtable.

Specialized String classes
StringCollection and StringDictionary, strongly typed string collections equivalent to List<string> and Dictionary<string, string>.

Stack Class
Last-in, first-out (LIFO) collection that works like a stack of papers on a desk.

Stream Class
A stream is an abstraction of a sequence of bytes, which helps isolate the programmer from the underlying implementation.

StreamReader Class and StreamWriter Class
Provides extra helper methods intended to read a stream as a string. Calling Close() on a StreamReader will close the underlying Stream as well.

StringBuilder Class
A StringBuilder keeps an internal buffer instead of allocating a new string every time. The default capacity is 16 characters.

StringReader Class and StringWriter Class
Used to read and write in-memory strings. StringWriter uses a StringBuilder behind the scenes.

TypeForwardedTo Attribute
TypeForwardedToAttribute marks a type as moved to another assembly, so client code keeps working without being recompiled.

Value Types
Value types: built-in types, structures, enums and nullable types, how they hold and copy values, and good practices for using them.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.

Design Patterns - State Pattern
The State Pattern: replacing an enum and its switch statements with a class per state, so a game unit acts differently when it's alive or dead.

Design Patterns - Composite Pattern
The Composite Pattern: tactical moves made of submoves, as a tree that the game treats as a single move.

Design Patterns - Iterator Pattern
The Iterator Pattern: one loop over two factions' orders, whether they're stored in a List or an array, and then the same with IEnumerable.

Design Patterns - Template Method Pattern
The Template Method Pattern: a base renderer that fixes the drawing order, while the 2D and 3D renderers fill in each step.

Design Patterns - Facade Pattern
The Facade Pattern: one LoadMap() call on a StorageFacade instead of juggling the CD, hard disk and memory classes yourself.

Design Patterns - Adapter Pattern
The Adapter Pattern: making a third-party Structure behave like our own IBuilding, the way a travel plug adapter does.

Design Patterns - Command Pattern
The Command Pattern: UI buttons that run commands without knowing about game units, with undo for the last action.

Design Patterns - Generic Singleton Pattern
A generic Singleton base class that creates its instance through the private constructor with reflection, worked out with readers' help.

Design Patterns - Singleton Pattern
The Singleton Pattern: a single GraphicsCard instance, why the simple version isn't thread-safe, and a lazy, thread-safe version with a nested class.

Design Patterns - Abstract Factory Pattern
The Abstract Factory Pattern: one GameUnit class per unit type, configured per faction by a factory passed in at runtime, and how it differs from Factory Method.

Design Patterns - Factory Method Pattern
The Factory Method Pattern: an abstract InfantryFactory building, with one subclass per faction deciding which units to create.

Design Patterns - Decorator Pattern
The Decorator Pattern: wrapping a building in upgrades like turrets and lasers instead of a class for every combination, with the Open/Closed Principle.

Design Patterns - Observer/Event Pattern
The Observer Pattern the .NET way: replacing the subject and observer interfaces with an event and a custom EventArgs class.

Design Patterns - Observer Pattern
The Observer Pattern: game screens subscribe to units through IObserver and ISubject, so new displays need no changes to the unit.

Design Patterns - Strategy Pattern
The Strategy Pattern, explained with a Command & Conquer-style game: shooting behaviours as interchangeable classes instead of copied or overridden code.

Long Absence - Design Patterns
Back after a break, reading Head First Design Patterns, and starting a series with one post per pattern.

Obfuscation - Making Reverse Engineering Harder
A strong name doesn't stop anyone from decompiling your .NET assemblies. Obfuscation goes a long way towards keeping your code safe.

String Concatenation vs Memory Allocation
Five ways to build the same string in C#, compared on string instances and memory in a profiler: +, +=, String.Concat, StringBuilder and AppendFormat.

Code Signing as Reverse Engineering Protection
Signing a .NET assembly stops casual tampering, but stripping the strong name defeats it; why you should still sign your code.

Reverse Engineering with Reflector and Reflexil
Cracking a small password check in a .NET assembly by flipping one IL branch with Reflector and the Reflexil add-in.

Using PowerShell: Writing and Debugging Cmdlets
Writing a PowerShell Cmdlet in C# that works stand-alone and in a pipeline, with a Visual Studio setup that installs and debugs it on every run.

Writing an Outlook Add-in
A small Outlook add-in that shows the internal ID of any selected item, which I needed to link to my own contact from Outlook Today.

Sync FLAC Library with iPod
A small tool built with TagLib#, LAME and FLAC that syncs my lossless FLAC music archive to my iPod.

Visual Studio 2008 and PHP Coloring
Getting PHP syntax coloring in Visual Studio 2008 by treating .php files as C++ with a registry file and a custom usertype.dat.

Using DebugView and C#
Writing debug messages from C# with System.Diagnostics and reading them, locally or remotely, with Sysinternals DebugView.

Remoting Server-Side
Controlling a Windows Service with .NET Remoting instead of ServiceController, which could only send integers and got nothing back.

Boxing/Unboxing in .NET
Boxing and unboxing in .NET: what happens on the stack and the heap, and why the overhead hurts heavy code like path finding.

BlogCast: Alternate Data Streams
My first BlogCast: an 8-minute video on NTFS Alternate Data Streams, demonstrated from the command prompt and in C#.

Stream Music over Wi-Fi: JustePort, MP3 Support Needed
JustePort streams Apple music files to an AirPort Express from C#; who'll add MP3 support so I can stream from Winamp?

ConvertToProperties Macro
The link to the C# property macro from Jan Tielens' .NET Magazine #5 article went missing in print; here it is.

Passing Bitwise OR Enum Values
How to pass several options in one enum parameter, like RegexOptions, using powers of two, bitwise OR and bitwise AND.

Error Reporting to the EventLog with NUnit
Building a C# class that reads and writes the Windows EventLog, test-driven with NUnit, from failing setup to passing tests.

FrontPage Server Extensions and the IIS Metabase
Setting FrontPageWeb in the IIS metabase from C# doesn't install FrontPage Server Extensions; running owsadm.exe from KB 300543 does.

Parameterized Queries with MySQL
Switching to parameterized queries with MySQL and MyODBC: don't put quotes around the ? placeholders, or you insert a question mark.

Differences between PHP and ASP.NET
Answers to a forum question for PHP developers moving to ASP.NET with C#: quotes, output, operators, string formatting and arrays.

Birthday, 20 Years: Small Console ChatServer
Turning 20, so three articles as a present: a console chat server, a word wrapper and gathering e-mail addresses from Outlook.

Custom WordWrapper
A C# word wrap method with a maximum width and an optional prefix, written for a forum question when I couldn't find one online.

Outlook and C#: Gather Addresses
A C# console app that walks an Outlook folder and collects every e-mail address from senders, recipients and message bodies.

Small Console ChatServer
A small C# console chat server: a TcpListener on its own thread, one Connection object per client, and every message broadcast to all.

Create Hashes: MD5, SHA1, SHA256, SHA384, SHA512
A small C# Hash class that makes MD5, SHA1, SHA256, SHA384 and SHA512 hashes as easy as md5() or sha1() in PHP.

Associating Your Program with Every File: ShellExtension
A C# class that adds your program to the right-click menu of every file, by writing a shell command key under HKEY_CURRENT_USER.

C# Script
CS-Script: a small tool that compiles and runs a single .cs file in memory, like a batch script for C#.

Including Resources in .exe
Embedding the Non-Rectangular Form's bitmap in the .exe as a resource, and loading it with one line of C#.

Non-Rectangular Form
Turning any bitmap into a non-rectangular Windows Form in C#: build a Region from every non-transparent pixel.

A Console IRC Bot
Getting on IRC with C#: a console bot that connects, logs in, joins a channel and reacts to server and user commands.

Basic C# Examples
Most posts here assume a lot of background, so I asked fellow students for their C# questions and answered them with basic examples.

Setting NTFS Permissions with C#
Setting NTFS permissions on new directories from C# with the GotDotNet 'ACLs in .NET' sample, before .NET had it built in.