Archive

Archive for January, 2009

The Plastic Wrap effect in Photoshop: Add dripping paint to a can

January 18, 2009 scerrimark Leave a comment

The Plastic Wrap filter provides you with a simple, easy-to-use way to add realistic gloss and moisture effects to photography and illustration. In this tutorial we will use the plastic wrap filter to render a realistic paint effect on a mug. Open up photoshop and load the following image.

11-oz-coated-mug

No we need to draw the path that will represent the dripping paint. Use the pen tool (shortcut is P) to draw a paint drip shape. First connect a couple of vertical points, then drag out a semi-circle cap at the end and go straight back up. You can use an actual photo reference if you are finding it difficult. The drawing should yield something like this.

drip

Then on a new layer fill the dripping paint with the colour of your choice using the brush. Now use the burn tool with 50% exposure and add shadows to the drip. Then enlarge the brush and add depth to the centre. The effect should be like this.

paintdrip

The last step is to apply the plastic wrap. Go to Filter -> Artistic -> and Plastic Wrap. You have to play a bit with the values to obtain the desired effect. Here is my finished product.

11-oz-coated-mug

Categories: Photoshop

C# .NET Tutorial 9: Regular Expression in C#

January 15, 2009 scerrimark 1 comment

The last post was dedicated to regular expressions. In this tutorial of the C# Tutorial series I am going to discus how you can use regular expressions in C#.

Using Regular Expressions for Pattern Matching

To help you understand let’s create a console application that accepts two strings as input and determines whether the first string, which is a regular expression, matches the second string. The console application must use the System.Text.RegularExpressions namespace. The check will be performed using the Regex.IsMatch static method. Here is the code.

using System.Text.RegularExpressions;

namespace TestRegExp
{
    class Class1
    {
        [STAThread]
        static void main (string[] args)
        {
            if (Regex.IsMatch(args[1], args[0])
                Console.WriteLine("Input matches regular expression.");
            else
                Console.WriteLine("Input does not match regular expression.");
        }
    }
}

To test it give it the following data:

  • ^\d{5}$ 1234 – should not match.
  • ^\d{5}$ 12345 – should match.

How to Specify Regular Expression Options

You can modify a regular expression pattern with options that affect matching behaviour. Regular expression options can be set by specifying the options parameter in the Regex(pattern, options) constructor, where options is a bitwise or combination of RegexOptions enumerated values. The following are the members of the RegexOptions enumeration:

  • None – no options are set.
  • IgnoreCase – Specifies case-insensitive matching.
  • MultiLine – matching is performed from the beginning to the end of each new line not from the beginning to the end of the string.
  • ExplicitCapture – specifies that only valid captures are explicitly named.
  • Compiled – specifies that the regular expression will be compiled to an assembly. It will generate Microsoft intermediate language code (MSIL) for the regular expression. This yields faster execution at the expense of start up time.
  • SingeLine – specifies single-line mode. This changes the meaning of the character (.) so that it matches every character (instead of every character except \n).
  • IgnorePatternWhitespace – specifies that unescaped white space is excluded from the pattern, and enables comments following a number sign (#).
  • RightToLeft – the search moves from right to left. With such an option the starting position in a regular expression should be specified at the end of the string instead of the beginning).
  • ECMAScript – specifies that ECMAScript – compliant behaviour is enabled for the expression. This option can only be used in conjunction with IgnoreCase and MultiLine flags. Other options will throw an exception.
  • CultureInvariant – specifes that cultural differences in language are ignored.

How to Extract Matched Data

Besides determining whether a string matches a pattern one can also extract information from a string. For example if you have the url www.markscerri.com and you only want the part between the www. and the .com you can extract it with a regular expression. To do this you need to:

  • Create a regular expression and enclose in parentheses the pattern to be matched.
  • Create an instance of the System.Text.RegularExpressions.Match class using the static method Regex.Match.
  • Retreive the matched data by accessing the elements of the Match.Groups array.

Here is an example:

string input = "www.markscerri.com";
Match m = Regex.Match(input, @"www.(\w+).com");
Console.WriteLine(Match.Groups[1]); //note that matches start from 1

The following example searches an input string and prints out all the href=”…” values and their locations in the string.

void GetHrefs(string input)
{
    Regex r;
    Match m;

    r = new Regex("href\\s*=\\s*(?:\"(?[^\"]*)\"|(?\\S+))", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    for (m = r.Match(input); m.Success; m=m.NextMatch())
    {
        Console.WriteLine("Found href " + m.Groups[1] + " at " + m.Groups[1].Index);
    }
}

You can also use the Match.Result method to reformat extracted substrings. For example the following code extracts the protocol and port from a url. That is http://www.markscerri.com:8080/ will result in the string http:8080.

String Extractor(String url)
{
    Regex r = new Regex(@"^(?
\w+)://[^/]+?(?
:\d+)?/",RegexOptions.Compiled);
    return r.Match(url).Result("${proto}${port}");
}

How to Replace Substrings using Regular Expressions

You can use regular expressions to make replacements that are more complex than you can do with String.Replace. The following code uses the Regex.Replace static method to replace dates in mm/dd/yy format to dd-mm-yy format.

String ChangeFormat(String input)
{
    return Regex.Replace(input, "\\b(?\\d{1,2})/(?\\d{1,2})/(?\\d{2,4})\\b",
        "${day}-${month}-${year}");
}

In this example we use back references within regular expressions. The replacement expression ${day} inserts the substring captured by the group (?…).

Character escapes and substitutions are the only special constructs recognized in a replacement pattern. For example the replacement pattern a*${txt}b inserts the string a*, followed by the substring matched by the txt capturing group, followed by the string b. The * character is not recognized as a meta character within a replacement pattern.

The following list shows how to define named and numbered replacement patterns:

  • $number – substitutes the last substring matched by the group number number.
  • ${name} – substitutes the last substring matched by a (?<name>) group.
  • $$ – substitutes a single $ literal.
  • $& – substitutes a copy of the entire match itself.
  • $` – substitutes all the text of the input string before the match.
  • $’ – substitutes all the text of the input string after the match.
  • $+ – substitutes the last group captured.
  • $_ – substitutes the entire input string.

Validating Names with Regular Expressions

Regular expressions can be efficiently used to validate user input. However certain input such as names can be very difficult to validate because a name can have a lot of different valid strings. The following regular expression can be used to validate names and surnames:

[a-zA-Z'`-À,Â\s]{1,40}

Well that’s it for today. In the next tutorial I will be discussing encoding and decoding of strings. Until then enjoy!!


Categories: C# .NET

Regular Expressions

January 9, 2009 scerrimark 2 comments

Lately I was working on a small project and I had to use some regular expressions. I thought I should write a post on the regular expression syntax patterns. And here it is. So let’s go.

First of all what are regular expressions? A regular expression is a set of characters that can be compared to a string to determine whether a string meets specified format requirements. You can also use regular expressions to extract portions of the text or to replace text. So let’s take a look at the syntax of regular expressions.

How to Match Simple Text

The simplest way to use regular expressions is to determine whether a string matches a pattern. For example, the regular expression “test” will match the string “This is a test”, “test”, and “Welcome to test1″ because all contain the regular expression.

How to Match Text in Specific Locations

If you want to match text beginning at the first character of a string, start the regular expressionwith a “^” symbol. For example the regular expression “^test” will match “test1″ but not “this is a test”. To match text that is at the end of a string use the “$” symbol. For example the following regular expression “test$” will give us all those sentences ending with “test”.

When searching for words you can use word boundaries. A word boundary is specified by “\b” and a non-word boundary is specified by “\B”. For example “test\b” will match “test” and “the test” however it will not match “test1″. Now “test\B” matches “test1″ but not “the test”.

The following are the characters that you can use in regular expressions to spefiy location:

  • ^ – specifies that the match must begin at the first character of a string of the first character of a line in multi-line input.
  • $ – specifies that the match must end at the last character of a string, or the last character before \n at the end of the string, or the last character at the end of a line.
  • \A – specifies that the match must begin at the first character of a string and ignores multi-line.
  • \Z – specifies that the match must end at the last character of a string or the last character before \n before the end of the string and ignores multi-line.
  • \z – specifies that the match must end at the last character of a string.
  • \G – specifies that the match must occur at the point where the previous match ended.
  • \b – specifies that the match must occur on a word boundary.
  • \B – specifies that the must must not occur on a \b boundary.

How to match Special Characters

You can match special characters in regulare expressions. For example \t is a tab while \n represents a newline. The following are special characters in regular expressions:

  • \a – matches a bell.
  • \b – denotes a word boundary.
  • \t – matches a tab.
  • \r – matches a carriage return.
  • \v – matches a vertical tab.
  • \f – matches a form feed.
  • \n – matches a new line.
  • \e – matches an escape.
  • \ – when followed by a character that is not recognized as an escaped character, matches that character. For example \* represents an asterisk while \\ represents a backslash “\”.

How to match text using Wildcards

You can use regulare expressions to match repeated characters. The “*” symbol means zero or more occurrences of a character. For example “go*d” matches “gd”, “god”, “good”, “goood”, and so on. The “+” symbol works similarly however it requires 1 or more occurrences of a character. Therefore “go+d” matches “god”, “good”, “goood” and so on, but does not match “gd” because “o” must occur at least once.

To match a specific number of repeated characters use “{n}” where n is the number. Therefore “go{2}d” will only match “good”. To match a range of repeated characters you can use “{min, max}”. Therefore “go{1,2}d” will match “god” and “good”. You can leave the second number blank to specify a minimum. For example “go{2,}d” will match “good”, “goood” and so on but will not match “god”.

To specify an optional character use the “?” symbol.  For example “goo?d” will match “god” or “good” only. The “.” symbol means any character. This means that “.ad” will match “bad”, “sad”, “dad” and so on.

To match one of several characters you use the “[]” syntax. For example “Mar[kc]” can match “Mark” or “Marc” only.

The following are all the characters used to match multiple characters or a range of characters:

  • * – matches the preceding character or expression zero or more times.
  • + – matches the preceding character or expression one or more times.
  • ? – matches the preceding character or expression zero or one time.
  • {n} – where n > 0 matches exactly n times.
  • {n,} – where n > 0 matches at least n times.
  • {n,m} – where n and m are non-negative integers matches at least n times and at most m times.
  • . – matches any character except “\n”.
  • x | y – matches either x or y.
  • [xyz] – matches any of the enclosed characters.
  • [a-z] – matches a range of characters; from a to z in this example.

Regular expressions also provide special characters to represent common character ranges. For example “[0-9″ can be represented by “\d”. Here is the complete list:

  • \d – matches a digit character.
  • \D – matches a non-digit character.
  • \s – matches any white space character including tab, space, and form feed.
  • \S – matches any non white space character.
  • \w – matches any word character, including underscore and numbers.
  • \W – matches any non word character.

So this was a basic introduction to regular expressions. The above will be enough for the majority however there are more complex stuff related to regular expressions. For those interested you can check one of the following very good books:

Categories: General

C# .NET Tutorial 8: Working with Isolated Storage

January 8, 2009 scerrimark 3 comments

Welcome to number 8 of this C# tutorial series. Today we will discuss working with isolated storage. With the emergence of viruses, malware, and spyware developers know that applications working in a sandbox of limited access is better for users. However applications sometimes need to store state data and this represents a problem for applications running on restricted priveleges. It would be nice if we had a place where applications can store information that is safe to use without having to test whether the application has enough rights to save data to the hard drive. The .NET Framework provides a solution for this. This is isolated storage. With isolated storage an application can save data without having to worry whether it is running in partial, limited, or full trust.

IsolatedStorageFile Class

The IsolatedStorageFile class provides the mechanism to create files and folders in isolated storage. These are the most important static methods of this class:

  • GetMachineStoreForApplication – retrieves a machine-level store for the called Click-Once application.
  • GetMachineStoreForAssembly – retrieves a machine-level store for the assembly that called.
  • GetMachineStoreForDomain – retrieves a machine-level store for the AppDomain within the current assembly that called.
  • GetStore – retrieves stores based on the IsolatedStorageScope enumerator.
  • GetUserStoreForApplication – retrieves a user-level store for the called Click-Once application.
  • GetUserStoreForAssembly – retrieves a user-level store for the assembly that called.
  • GetUserStoreForDomain – retrieves a user-level store for the AppDomain within the current assembly that called.

The following are the most important IsolatedStorageFile properties:

  • ApplicationIdentity – The Click-Once application’s identity that scopes the isolated storage.
  • AssemblyIdentity – The assembly’s identity that scopes the isolated storage.
  • CurrentSize – the size of the current data stored in the isolated storage.
  • MaximumSize – the maximum storage size of the isolated storage.
  • DomainIdentity – the identity of the AppDomain that scopes the isolated storage.
  • Scope – the IsolatedStorageScope enumeration value that describes the scope of this isolated storage.

These are the commonly used IsolatedStorageFile methods:

  • Close – closes an instance of the store.
  • CreateDirectory – creates a directory within the store.
  • DeleteDirectory – deletes a directory within the store.
  • DeleteFile – deletes a file within the store.
  • GetDirectoryNames – gets a list of directory names within the store that match a file mask.
  • GetFileNames – gets a list of file names within the store that match a file mask.
  • Remove – removes the entire store from the current system.

Note: Click-Once applications are new types of applications (in .NET 2.0) that are meant to be deployed and installed from web pages. These new type of applications are meant to solve deployment of applications across a large company. For more info click here.

How to Create a Store

Before saving data in isolated storage one needs to determine the scope for the data in the store. For most applications you normally choose one of the following two methods:

  • Assembly/Machine – this method creates a store to keep information that is specific to the calling assembly and the local machine. It is well suited for application-level data.
  • Assembly/User – this method creates a store to keep information that is specific to the calling assembly and the current user. It is well suited for user-level data.

To create one of the following you use the following code:

//Assembly/Machine store
IsolatedStorageFile myStorage = IsolatedStorageFile.GetMachineStoreForAssembly();

//Assembly/User store
IsolatedStorageFile myStorage = IsolatedStorageFile.GetUserStoreForAssembly();

For Click-Once deployed applications one can use an application-level store that supports both a machine-level store and a user-level store. This only works with Click-Once applications because the executing assembly has its own evidence that might or might not be valid for local applications.

IsolatedStorageFileStream Class

The IsolatedStorageFileStream encapsulates a stream that is used to create files in isolated storage. It derives from the FileStream class and therefore its properties and methods are the same.

Reading and Writing data to Isolated Storage

To create data within isolated storage you do it through the IsolatedStorageFileStream class. You create a new instance of the class specifying a relative file name and a store. Here is the  code.

//create a store
IsolatedStorageFile myStorage = IsolatedStorageFile.GetUserStoreForAssembly();
//create an isolated storage file stream
IsolatedStorageFileStream userStream = new IsolatedStorageFileStream("UserSettings.dat", FileMode.Create, userStore);

Working with the IsolatedStorageFileStream is just like working with any other stream. The following code provides an example.

//wrap IsolatedStorageFileStream to a StreamWriter
StreamWriter writer = new StreamWriter(userStream);
writer.WriteLine("UserName = Mark");
writer.Close();

Reading is also done in a very similar way. The only difference is that you need to change the FileMode to Open as shown here.

IsolatedStorageFileStream userStream = new IsolatedStorageFileStream("UserSettings.dat", FileMode.Open, userStore);

The only difference from the other streams is that the Isolated Storage does not support checking for the existing of files directly like File.Exists. To do this you need to use the following code:

string[] files = userStore.GetFileNames("UserSettings.dat");
if (files.length == 0)
    Console.WriteLine("File not found");
else
    Console.WriteLine("File found");

How to use Directories in Isolated Storage

In isolated storage one can also create directories as shown in this code:

userStore.CreateDirectory("TestDirectory");

IsolatedStorageFileStream userStream = new IsolatedStorageFileStream(
                                                                      @"TestDirectory/UserSettings.dat",FileMode.Create, userStore);

To check for existence of directories you need to use the following code:

string[] directories = userStore.GetDirectoryNames("TestDirectory");
if (directories.length == 0)
{
    //directory not found
}
else
{
    //
}

The IsolatedStorageFilePermission Class

The IsolatedStorageFilePermission class encapsulates the permission that can be granted to code to allow it to access isolated storage. The following are the important properties:

  • UsageAllowed – gets or sets the type of usage allowed.
  • UserQuota – gets or sets the overall size of storage allowed per user.

Isolated Storage and Permissions

Before an assembly or application uses the isolated storage it needs the necessary permissions. Demanding permission can be accomplished by annotating your class or method with the IsolatedStorageFilePermission as shown here.

[IsolatedStorageFilePermission(SecurityAction.Demand)]
class Example
{
}

This ensures that any calls to work with isolated storage within this class willl succeed. This permission also supports several attributes that can be used to modify how isolated storage is used as shown below.

[IsolatedStorageFilePermission(SecurityAction.Demand, UserQuota=1024, UsageAllowed=IsolatedStorageContainment.AssemblyIsolataionByUser)]
class Example
{
}

Well that’s all for today! In the next two tutorials we will focus on text, specifically searching, modifying, and encoding text. In the next tutorial we will turn our attention to regular expressions in C#. See you soon!

Categories: C# .NET

C# .NET Tutorial 7: Compressing Streams

January 7, 2009 scerrimark Leave a comment

By now you have got used to the C# tutorials. If not you can view all of them here. This tutorial will focus on stream classes that support compression of data. In the .NET Framework there are two such streams.

In the I/O system of the .NET Framework that are two method of compressing data: GZIP and DEFLATE. Both these compression algorithms are industry-standard and are limited to compression of uncompressed data up to 4GB. These compression methods are exposed in two streams: GZipStream, and DeflateStream classes.

GZipStream Class and the DeflateStream Class

The functionality of these two classes is identical. The only difference is the compression algorithm that they use. Here are the important properties of these classes:

  • BaseStream – gets the underlying stream.
  • CanRead – determines whether the stream supports reading while decompressing a file.
  • CanWrite – determines whether the stream can be written to.
  • CanTimeout – determines whether the stream can timeout.
  • CanSeek – determines whether the stream supports seeking.
  • Length – this is inherited from the Stream class however do not use it with these classes because it will throw a NotSupportedException
  • Position – this is inherited from the Stream class however do not use it with these classes because it will throw a NotSupportedException
  • ReadTimeout – gets or sets the stream’s time out for read operations.
  • WriteTimeout – gets or sets the stream’s time out for write operations.

The following are the most commonly used methods:

  • Close – closes the streams and any other resources associated with it.
  • Flush – clears any buffers within the stream and forces any changes to be written to the underlying system or device.
  • Read – performs a sequential read of a specified number of bytes and then moves the cursor accordingly.
  • ReadByte – reads a single byte and moves the cursor by one.
  • Write – writes a specified number of bytes of data to the stream and updates the cursor to reflect the new write position.
  • WriteByte – writes a single byte to the stream and updates the position.
  • Seek – Not implemented. It will throw a NotSupportedException.
  • SetLength – Not implemented. It will throw a NotSupportedException.

How to Compress Data with a Compression Stream

Compression streams are a little different than the other streams. Instead of the stream writing to a resource such as a file or memory, the compression streams write to another stream. The compression streams take in data like any other stream. But then it writes it in compressed format to another stream. The following example demonstrates how to compress a file and write a new compressed version.

//first we need to open the file and create a new file for the compressed version
FileStream sourceFile = File.OpenRead(@"C:\data.bak");
FileStream destFile = File.Create(@"C:\data.gzip");

//now we need the compression stream to wrap the outgoing stream
GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);

//all we need to do now is write from the source file to the compression stream
int aByte = sourceFile.ReadByte();
while (aByte != -1)
{
    compStream.WriteByte((byte)aByte);
    aByte = sourceFile.ReadByte();
}

Note that we never wrote in the destination file. Because we are writing in the compression stream, the compression stream will write the compressed version in the destination file. Also if you want to use the Deflate algorithm all you need to do is change the compression stream to the DeflateStream.

How to Decompress Data with a Compression Stream

Here is the code used for decompression.

//Like before we need to declare a source file and a destination file. But now the source file is the compressed version.
FileStream sourceFile = File.OpenRead(@"C:\data.gzip");
FileStream destFile = File.Create(@"C:\data.bak");

//Now the change comes in the compression stream algorithm. We will wrap the source file and we will used the Decompress mode
GZipStream decompStream = new GZipStream(sourceFile, CompressionMode.Decompress);

//Now we need to read from the compression stream (not the source file) and write to the destination file
int aByte = decompStream.ReadByte();
while (aByte != -1)
{
    destFile.WriteByte((byte)aByte);
    aByte = decompStream.ReadByte();
}

So you now know how to compress and decompress streams. What’s next? In the next tutorial I will show you how to work with isolated storage. With isolated storage, data is always isolated by user and by assembly. Until then enjoy!!

Categories: C# .NET