<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-6892494754021144209</id><updated>2024-02-19T13:49:15.240+00:00</updated><category term="c#"/><category term="async"/><category term="threading"/><category term="client"/><category term="com"/><category term="dropbox"/><category term="events"/><category term="generics"/><category term="git"/><category term="interop"/><category term="lambda"/><category term="linq"/><category term="marshal"/><category term="minecraft"/><category term="misc"/><category term="network"/><category term="predicates"/><category term="scm"/><category term="server"/><category term="socket"/><category term="string"/><category term="struct"/><category term="sxs"/><category term="tcp"/><title type='text'>RobJDavey</title><subtitle type='html'>A software engineers blog about work, play and anything in the middle.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://robjdavey.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://robjdavey.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/10612519606212564303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>9</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-6892494754021144209.post-9165182752121028741</id><published>2012-04-26T14:50:00.005+01:00</published><updated>2012-04-26T14:52:11.076+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="c#"/><category scheme="http://www.blogger.com/atom/ns#" term="com"/><category scheme="http://www.blogger.com/atom/ns#" term="interop"/><category scheme="http://www.blogger.com/atom/ns#" term="sxs"/><title type='text'>Creating a Side by Side Manifest (sxs) to allow Registration Free Activation of COM in C#</title><content type='html'>This is a topic that I found many posts on, but none gave a simple method for generating a side by side manifest and getting it to work. In this example I will use MyCOMLib.dll as an example. So here we go:&lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;In this step we will generate the Type Library for the COM assembly. If you already have the .tlb file go to step 2.&lt;br /&gt;This is a very simple process. First, open Visual Studio and click File -&amp;gt; Open -&amp;gt; File...&lt;br /&gt;In the Open dialog select your COM dll. The assembly will be shown as a tree view. In the tree view you should see a node called &quot;TYPELIB&quot;. Expand this and you should see at least one item in this category, usually called 1. Right click on this and select Export....&lt;br /&gt;Save this file as a .tlb (e.g. MyCOMLib.tlb) in the same folder as your .dll is located. You can now close Visual Studio again.&lt;/li&gt;
&lt;li&gt;To generate our side by side manifest we will use &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/windows/desktop/aa375649.aspx&quot;&gt;Mt.exe&lt;/a&gt;. This should be available if you open the Visual Studio command prompt. The command to use is as follows:&lt;br /&gt;&lt;span style=&quot;font-family: monospace;&quot;&gt;&lt;b&gt;mt.exe -tlb:&quot;&lt;/b&gt;&lt;/span&gt;&lt;span style=&quot;color: red; font-family: monospace; font-weight: bold;&quot;&gt;MyCOMLib&lt;/span&gt;&lt;span style=&quot;font-family: monospace;&quot;&gt;&lt;b&gt;.tlb&quot; -dll:&quot;&lt;/b&gt;&lt;/span&gt;&lt;span style=&quot;color: red; font-family: monospace; font-weight: bold;&quot;&gt;MyCOMLib&lt;/span&gt;&lt;span style=&quot;font-family: monospace;&quot;&gt;&lt;b&gt;.dll&quot; -identity:&quot;&lt;/b&gt;&lt;/span&gt;&lt;span style=&quot;color: red; font-family: monospace; font-weight: bold;&quot;&gt;MyCOMLib&lt;/span&gt;&lt;span style=&quot;font-family: monospace;&quot;&gt;&lt;b&gt;.sxs, version=1.0.0.0, type=win32&quot; -out:&quot;&lt;/b&gt;&lt;/span&gt;&lt;span style=&quot;color: red; font-family: monospace; font-weight: bold;&quot;&gt;MyCOMLib&lt;/span&gt;&lt;span style=&quot;font-family: monospace;&quot;&gt;&lt;b&gt;.sxs.manifest&quot;&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Simply replace the MyCOMLib with the name of your assembly and this command should generate a new manifest file that contains all the information needed for side by side.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;To use the newly created side by side manifest, open your visual studio project and then add a reference to the manifest. This will automatically create any necessary Interops (sign them if necessary) and then, provided any dependencies for your library are available in the Debug folder, the local version of the COM assembly will be used rather than the registered version. You should note that if you are using a 64-bit machine, it may be necessary to set the platform target to x86.&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
That&#39;s it! So simple once you know what to do but this took me a long time to figure out. You can now use your side by side COM anywhere you like by simply referencing this manifest file in your project references. Enjoy!&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://robjdavey.blogspot.com/feeds/9165182752121028741/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://robjdavey.blogspot.com/2012/04/creating-side-by-side-manifest-sxs-to.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/9165182752121028741'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/9165182752121028741'/><link rel='alternate' type='text/html' href='http://robjdavey.blogspot.com/2012/04/creating-side-by-side-manifest-sxs-to.html' title='Creating a Side by Side Manifest (sxs) to allow Registration Free Activation of COM in C#'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/10612519606212564303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total><georss:featurename>Walton-le-Dale, Preston, Lancashire PR5 4PE, UK</georss:featurename><georss:point>53.7360157 -2.6862353</georss:point><georss:box>53.733667700000005 -2.6911708 53.7383637 -2.6812997999999997</georss:box></entry><entry><id>tag:blogger.com,1999:blog-6892494754021144209.post-5957896237630018908</id><published>2012-03-05T17:00:00.000+00:00</published><updated>2012-03-06T14:07:04.754+00:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="dropbox"/><category scheme="http://www.blogger.com/atom/ns#" term="git"/><category scheme="http://www.blogger.com/atom/ns#" term="minecraft"/><category scheme="http://www.blogger.com/atom/ns#" term="scm"/><title type='text'>Using Git and Dropbox to keep Minecraft world history</title><content type='html'>&lt;b&gt;Introduction&lt;/b&gt;&lt;br /&gt;
I am a huge fan of Minecraft, although bizarrely although I have a copy of the game, I spend more time watching Lets Play videos from people like &lt;i&gt;&lt;a href=&quot;http://twitter.com/GuudeLP&quot; target=&quot;_blank&quot;&gt;Guude&lt;/a&gt;&lt;/i&gt; and &lt;i&gt;&lt;a href=&quot;http://twitter.com/BdoubleO100&quot; target=&quot;_blank&quot;&gt;BdoubleO&lt;/a&gt;&lt;/i&gt;&amp;nbsp;than playing it myself. One thing I do notice however is that these guys (and indeed almost anyone you&#39;ll find posting pictures on &lt;a href=&quot;http://www.reddit.com/r/minecraft&quot; target=&quot;_blank&quot;&gt;/r/minecraft&lt;/a&gt;) have incredibly detailed worlds that they have spent hundreds, if not thousands of hours playing on.&lt;br /&gt;
Recently &lt;a href=&quot;http://twitter.com/jeb_&quot; target=&quot;_blank&quot;&gt;Jeb&lt;/a&gt; has started releasing snapshots on a regular basis but these snapshots always come with a risk of incompatibility if you want to revert back to the current stable release, and the problem for many of the guys making Lets Play videos is their fans want to see them playing these snapshots, but they don&#39;t want to risk corrupting their whole world if they either choose to go back to the stable, or another change before the next release makes their now &#39;beta&#39; world invalid.&lt;br /&gt;
In this post I will explain how to use a combination of &lt;a href=&quot;http://git-scm.com/&quot; target=&quot;_blank&quot;&gt;Git&lt;/a&gt; (a tool used for source code versioning) and &lt;a href=&quot;http://www.dropbox.com/&quot; target=&quot;_blank&quot;&gt;Dropbox&lt;/a&gt; (a cloud based storage provider) to keep full histories of all your past worlds so that in the event something goes wrong you can revert back to any previous point in that worlds history (provided you remembered to save). As it will be passing a copy of this data to Dropbox you can also retrieve it if your PC gets corrupted etc.&lt;br /&gt;
&lt;b&gt;Installation&lt;/b&gt;&lt;br /&gt;
The first step is to get Git and Dropbox installed. You will also need an account on Dropbox if you&#39;ve not already got one. This is not a guide to installing and these tools are fairly self explanitory so I&#39;ll skip over the actual installation, but this guide will be written based on a Windows installation with the following file paths:&lt;br /&gt;
&lt;u&gt;Dropbox Folder:&lt;/u&gt;&amp;nbsp;C:\Users\&lt;i&gt;username&lt;/i&gt;\Dropbox&lt;br /&gt;
&lt;u&gt;Minecraft Saves Folder:&lt;/u&gt;&amp;nbsp;C:\Users\&lt;i&gt;username&lt;/i&gt;\AppData\Roaming\.minecraft\saves&lt;br /&gt;
If these are not the same paths that you are using, you will need to adjust any steps in this guide accordingly.&lt;br /&gt;
&lt;b&gt;Open up Bash&lt;/b&gt;&lt;br /&gt;
For all the steps from this point on we will need to use the Git Bash shell. This will have been included with your installation and you should be able to find it at Start -&amp;gt; All Programs -&amp;gt; Git -&amp;gt; Git Bash. It should also be noted that all these commands should be run wile Minecraft is CLOSED! Running it with the program open (especially if you&#39;re in your world) will cause you an infinite amount of trouble. Anything you need to type is in &lt;b&gt;&lt;span style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;bold monospaced font&lt;/span&gt;&lt;/b&gt;. The text in &lt;span style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;normal monospaced font&lt;/span&gt; is additional output you will see in the bash window.&amp;nbsp;Bash is a Unix environment so the C:\ drive is now /C/ and you should use / instead of the Windows \. Also your home folder (Usually /C/Users/username/ ) has a shortcut symbol of ~ which I will use in this post rather than typing the full path.&lt;br /&gt;
&lt;b&gt;Create the Dropbox Repository&lt;/b&gt;&lt;br /&gt;
The Dropbox Repository will act like a backup location. We will create this as what Git calls a Bare repository. A bare repository does not contain a copy of the files saved in the repository (or at least not in a form visible to the user). The nice feature about having this backup is that we can send the history to it whenever we like and it will still include all the history of our saves, while at the same time not actually including a &#39;real&#39; copy of the files.&lt;br /&gt;
First in our bash window we need to navigate to the dropbox folder. Type the command in Bold to change to the correct folder (replacing username with your actual username). You can also use the tab key for auto-completion on these paths.&lt;br /&gt;
&lt;pre&gt;user@machine ~
$ &lt;b&gt;cd ~/Dropbox/&lt;/b&gt;
user@machine ~/Dropbox
$&lt;/pre&gt;
Now we want to create our repository folder called &lt;i&gt;minecraft&lt;/i&gt; and move inside that folder:&lt;br /&gt;
&lt;pre&gt;user@machine ~/Dropbox
$ &lt;b&gt;mkdir minecraft&lt;/b&gt;
user@machine ~/Dropbox
$ &lt;b&gt;cd minecraft/&lt;/b&gt;
user@machine ~/Dropbox/minecraft
$&lt;/pre&gt;
With that done it&#39;s time to initialize this to an new bare repository:
&lt;br /&gt;
&lt;pre&gt;user@machine ~/Dropbox/minecraft
$ &lt;b&gt;git init --bare&lt;/b&gt;
Initialized empty Git repository in c:/Users/username/Dropbox/minecraft/
user@machine ~/Dropbox/minecraft (BARE:master)
$&lt;/pre&gt;
That&#39;s it. We&#39;ve created what will be our backup location. Easy wasn&#39;t it? Notice how the command prompt path is now suffixed with (BARE:master). The bare means we are inside a bare repository (it will only contain history and not a visible copy of the files) and the master is the name of our current branch. We won&#39;t worry about branch names for the moment but keep that name in mind as we&#39;ll use the branch name master a lot.&lt;br /&gt;
&lt;b&gt;Create the Minecraft Saves Repository&lt;/b&gt;&lt;br /&gt;
Next we want to create a normal (not bare) repository in our Minecraft saves folder, and add all our current saves to it. First lets move the bash window to the correct folder and create the repository:&lt;br /&gt;
&lt;pre&gt;user@machine ~/Dropbox/minecraft (BARE:master)
$ &lt;b&gt;cd ~/AppData/Roaming/.minecraft/saves/&lt;/b&gt;
user@machine ~/AppData/Roaming/.minecraft/saves
$ &lt;b&gt;git init&lt;/b&gt;
Initialized empty Git repository in c:/Users/username/AppData/Roaming/.minecraft/saves/.git/
user@machine ~/AppData/Roaming/.minecraft/saves (master)
$&lt;/pre&gt;
Just like before we now have our branch name (master) at the end of our command line however this does not include the word BARE because this is not a BARE repository. This will contain real versions of the files so of course now we have created our repository lets add all our existing saves to it! To do this we will tell Git to add all the files to the repository, and then save them (or as Git calls it, commit them) with the message &quot;Adding existing worlds&quot;.&lt;br /&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git add .&lt;/b&gt;
user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git commit -a -m &quot;Adding existing worlds&quot;&lt;/b&gt;
[master (root-commit) .......] Adding existing worlds
 ...&lt;/pre&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves (master)
$&lt;/pre&gt;
Now we&#39;ve added all our current data into the repository. We can check this by running the command &lt;br /&gt;
&lt;pre&gt;$ &lt;b&gt;git log&lt;/b&gt;&lt;/pre&gt;
which will show us the most recent log items from the repository as well as each entries unique ID.&lt;br /&gt;
&lt;b&gt;Linking the repositories together&lt;/b&gt;&lt;br /&gt;
As we have created our two repositories we need to link them together so that every now and then we can push the history from our save folder repository to our backup repository. To do this we need to set the Dropbox repository as a &#39;remote&#39;.&lt;br /&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git remote add Dropbox ~/Dropbox/minecraft/&lt;/b&gt;
user@machine ~/AppData/Roaming/.minecraft/saves (master)
$&lt;/pre&gt;
This has added the Dropbox folder as a remote repository with the name &#39;Dropbox&#39;. We can now send our history to that folder. Lets do that now so that we have a backup of our first commit. To do this we use a command called push. We want to tell Git to push our current repository to the Dropbox repository using the branch master (remember I told you we&#39;d use that name later).&lt;br /&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git push Dropbox master&lt;/b&gt;
Counting objects: 9, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (7/7), done.
Writing objects: 100% (9/9), 1.59 MiB, done.
Total 9 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (9/9), done.
To c:/Users/username/Dropbox/minecraft/
 * [new branch]      master -&amp;gt; master
user@machine ~/AppData/Roaming/.minecraft/saves (master)
$&lt;/pre&gt;
Done! Now we have successfully backed up our history to our Dropbox backup for the first time. If you were to go back to the Dropbox folder and say &#39;git log&#39; you&#39;d see the log entry for &#39;Adding existing worlds&#39; in that repository now.&lt;br /&gt;
&lt;b&gt;Saving after we&#39;ve played&lt;/b&gt;&lt;br /&gt;
Now that we&#39;re all set up we can carry on playing Minecraft as normal. Whenever you decide you want to create a restore point (I call it a restore point but it&#39;s basically a point in time that you can get back to in the future if you want to) you will have to run some of the same commands we ran before:&lt;br /&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git add .&lt;/b&gt;
user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git commit -a -m &quot;&amp;lt;Some Message&amp;gt;&quot;&lt;/b&gt;
user@machine ~/AppData/Roaming/.minecraft/saves (master)
$&lt;/pre&gt;
What these commands say are:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Add any new files that have been created to the repository&lt;/li&gt;
&lt;li&gt;Save all the new files and any change files with the log message &quot;&amp;lt;Some Message&amp;gt;&quot;.&lt;/li&gt;
&lt;/ol&gt;
The value of &amp;lt;Some Message&amp;gt; can be anything you like, so it might describe what you did before you saved (e.g. &quot;Added roof to my house and made a pond outside&quot;) or just a time and date.&lt;br /&gt;
We can repeat this process as often as we like but you should note that this is only adding it to our save repository. After we&#39;ve saved to our local repository a few times we might want to back up all of these saves to our Dropbox.&lt;br /&gt;
Again this is a simple command we used before.&lt;br /&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git push --tags Dropbox master&lt;/b&gt;
Counting objects: 17, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (7/7), done.
Writing objects: 100% (9/9), 2.37 MiB, done.
Total 9 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (9/9), done.
To c:/Users/username/Dropbox/minecraft/
   4a82680..01db97f  master -&amp;gt; master
user@machine ~/AppData/Roaming/.minecraft/saves (master)
$&lt;/pre&gt;
And this will push our save repository to the Dropbox. Simple!&amp;nbsp;Although not strictly necessary, the --tags flag in the command ensures that if we ever create some tags (see next section) these will be pushed to the Dropbox backup too.&lt;br /&gt;
&lt;b&gt;Tagging a save&lt;/b&gt;&lt;br /&gt;
Using this method there is a chance you will save after each time you play, and that&#39;s good it means you will always have a regular history of your minecraft save files. Each of these saves has a unique name (a long combination of letters and numbers it creates automatically) but there may be times that you want to create a Tag for a particular save (basically give that save a name). An example of this might be when you finally finished creating your house. You may want to name that particular save &quot;FinishedHouse&quot; that way you can easily identify it. Tagging is very easy, first we need to use the log command to identify the unique ID of the save we want to tag, then we use the tag command to create the tag.&lt;br /&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git log&lt;/b&gt;
commit e02727c676936ee9f8914191c3f5bb4a031af87c
Author: Robert Davey &amp;lt;email@address.com&amp;gt;
Date:   Tue Mar 6 12:37:49 2012 +0000

    Finished building my house

commit 01db97f91baf8300d246fc57eb9ca5c37c172e71
Author: Robert Davey &amp;lt;email@address.com&amp;gt;
Date:   Tue Mar 6 12:28:23 2012 +0000

    Knocked down a tree

commit 4a826804414420cf43b07c4e970811a9d6c805b8
Author: Robert Davey &amp;lt;email@address.com&amp;gt;
Date:   Tue Mar 6 11:44:43 2012 +0000

    Adding existing worlds

user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git tag FinishedHouse e027&lt;/b&gt;
user@machine ~/AppData/Roaming/.minecraft/saves (master)
$&lt;/pre&gt;
Above you can see that I got my log for my saves. I identified the save I wanted to tag based on its log message (&quot;Finished building my house&quot;) and so I can see that the save I want has ID&amp;nbsp;e02727c676936ee9f8914191c3f5bb4a031af87c. I can then tag it by using the git tag command followed by the name we want to tag it with (keep the name small with no punctuation and not spaces) and then the ID of the commit. You may note however that I only used the first 4 letters of the ID in my command. Git is very clever and so you only need to give it a small part of the ID (as long as it can uniquely identify the ID from those letters, if there were two IDs that have an identical first 4 letters I may have to provide 5 letters etc...) then the rest of the ID is not necessary.&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;Getting back to an older version&lt;/b&gt;&lt;br /&gt;
Eventually the time may come when you want to go back to an older version of your saved worlds. This is where things can get a little more complicated (but not too much). First you need to work out what version you want to get back to. If the save is one that you tagged (see above) then this is easy to identify because we have a tag name, otherwise we will need to find the ID using the log command (also see above). Once we have our ID (either a tag name or a commit ID) then we can run the following command (replacing the 4a82 with your ID):&lt;br /&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git reset --hard 4a82&lt;/b&gt;
HEAD is now at 4a82680 Adding existing worlds
user@machine ~/AppData/Roaming/.minecraft/saves (master)
$&lt;/pre&gt;
This command resets our repository to the state it was in at that particular commit. If you had a tag name then in the above example you would replace the 4a82 with the tag name. It should be noted that running this command will lose any information you&#39;ve not saved, so you may want to create a save point before doing this or you&#39;ll never be able to change your mind! Now if you load up Minecraft you&#39;ll find that your world is back how it was when you saved at that commit. Magic! :D&lt;br /&gt;
But what if we change our mind and we want to go forward again to the point at which we were before we saved. It&#39;s the same command, but there&#39;s a problem: The log command will only show us the log for things that happened before our current save and so we can&#39;t get the ID of the &#39;future&#39; save we want to go back to. Don&#39;t worry though we can get the full log using this command:&lt;br /&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git log --all&lt;/b&gt;&lt;/pre&gt;
This will include the log entries that come after our current save so we&#39;re ok, we can run the reset command again to change our save point back.&lt;br /&gt;
After this we can continue saving like we did before. If you do this you may find that encounter the following error when trying to push the new saves to your Dropbox backup.&lt;br /&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git push --tags Dropbox master&lt;/b&gt;
To c:/Users/username/Dropbox/minecraft/
 ! [rejected]        master -&amp;gt; master (non-fast-forward)
error: failed to push some refs to &#39;c:/Users/username/Dropbox/minecraft/&#39;
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. &#39;git pull&#39;) before pushing again.  See the
&#39;Note about fast-forwards&#39; section of &#39;git push --help&#39; for details.&lt;/pre&gt;
If this does happen then you can get around it by running the following set of commands instead:
&lt;br /&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git merge Dropbox/master -s ours&lt;/b&gt;
Merge made by the &#39;ours&#39; strategy.

user@machine ~/AppData/Roaming/.minecraft/saves (master)
$ &lt;b&gt;git push --tags Dropbox master&lt;/b&gt;
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 424 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
To c:/Users/username/Dropbox/minecraft/
   a824abd..b023ad0  master -&amp;gt; master

user@machine ~/AppData/Roaming/.minecraft/saves (master)
$&lt;/pre&gt;
And this should successfully push your files to the Dropbox backup. You can then go back to the normal push method afterwards.&lt;br /&gt;
&lt;b&gt;Getting your saves from your backup&lt;/b&gt;&lt;br /&gt;
If you&#39;ve ended up on a fresh copy of minecraft without your saves and you want to get them back out of your Dropbox backup it&#39;s simple. Navigate the bash window to your empty saves folder and run the following command:&lt;br /&gt;
&lt;pre&gt;user@machine ~/AppData/Roaming/.minecraft/saves
$ git clone -o Dropbox ~/Dropbox/minecraft .
Cloning into &#39;.&#39;...
done.
user@machine ~/AppData/Roaming/.minecraft/saves (master)
$&lt;/pre&gt;
You should now be back in a state where you can save and push just like before.&lt;br /&gt;
&lt;b&gt;Summary&lt;/b&gt;&lt;br /&gt;
Using this technique you can ensure that your Minecraft worlds are always saved and backed up in a safe manner that allows you to always get back to a previous point in time if things go wrong or you just fancy doing something a little different. If you have any questions about ways to use this then please post in the comments. Enjoy :)</content><link rel='replies' type='application/atom+xml' href='http://robjdavey.blogspot.com/feeds/5957896237630018908/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://robjdavey.blogspot.com/2012/03/using-git-and-dropbox-to-keep-minecraft.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/5957896237630018908'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/5957896237630018908'/><link rel='alternate' type='text/html' href='http://robjdavey.blogspot.com/2012/03/using-git-and-dropbox-to-keep-minecraft.html' title='Using Git and Dropbox to keep Minecraft world history'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/10612519606212564303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total><georss:featurename>Walton-le-Dale, Preston, Lancashire PR5 4PE, UK</georss:featurename><georss:point>53.7360157 -2.6862353</georss:point><georss:box>53.733667700000005 -2.6911708 53.7383637 -2.6812997999999997</georss:box></entry><entry><id>tag:blogger.com,1999:blog-6892494754021144209.post-692322484057866943</id><published>2012-02-27T17:00:00.000+00:00</published><updated>2012-02-28T13:38:00.132+00:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="async"/><category scheme="http://www.blogger.com/atom/ns#" term="c#"/><category scheme="http://www.blogger.com/atom/ns#" term="events"/><category scheme="http://www.blogger.com/atom/ns#" term="generics"/><category scheme="http://www.blogger.com/atom/ns#" term="threading"/><title type='text'>Raising Events in C#</title><content type='html'>The chances are that you&#39;ve seen a lot of different posts about how events should be raised in C#. The general rules to follow are &lt;a href=&quot;http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx&quot;&gt;this&lt;/a&gt;:
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Always create an invocator for raising events
&lt;/li&gt;
&lt;li&gt;This method should create a copy of the event handler
&lt;/li&gt;
&lt;li&gt;The handler should be checked for null.
&lt;/li&gt;
&lt;li&gt;Then call the handler with the required arguments.&lt;/li&gt;
&lt;/ul&gt;
So lets have a look at what a basic event invocator should look like:
&lt;br /&gt;
&lt;pre&gt;public event EventHandler Started;

/// &amp;lt;summary&amp;gt;
/// Our basic event that we want to invoke.
/// &amp;lt;/summary&amp;gt;
public event EventHandler Connected;

/// &amp;lt;summary&amp;gt;
/// Our event invocator.
/// &amp;lt;/summary&amp;gt;
private void OnConnected(object sender, EventArgs e)
{
    //Create a copy
    EventHandler handler = Connected;
    //Check for null
    if(handler != null)
    {
        //Call the handler
        handler(sender, e);
    }
}&lt;/pre&gt;
That&#39;s all very well and good but we are likely to want to do this for every event we have. So lets make this a bit more generic and pass in the event handler we want to raise. We may also want to create a version for the EventHandler&amp;lt;T&amp;gt; delegate for when we have specialised event arguments.
&lt;br /&gt;
&lt;pre&gt;private void RaiseEvent(EventHandler handler, object sender, EventArgs e)
{
    EventHandler temp = handler;
    if(temp != null)
    {
        temp(sender, e);
    }
}

private void RaiseEvent&amp;lt;T&amp;gt;(EventHandler&amp;lt;T&amp;gt; handler, object sender, T e)
    where T : EventArgs
{
    EventHandler&amp;lt;T&amp;gt; temp = handler;
    if(temp != null)
    {
        temp(sender, e);
    }
}&lt;/pre&gt;
So now we have some basic event invocators that can invoke any (standard) event. We can even take this a step further and make this an extension method:
&lt;br /&gt;
&lt;pre&gt;public static class EventHandlerExtensions
{
    public static void RaiseEvent(this EventHandler handler, object sender, EventArgs e)
        { /* ... */ }

    public static void RaiseEvent&amp;lt;T&amp;gt;(this EventHandler&amp;lt;T&amp;gt; handler, object sender, T e)
        where T : EventArgs { /* ... */ }
}&lt;/pre&gt;
As you may have seen from my posts in the past however, I am a huge fan of Asynchronous programming, and the functionality provided. So what if we could make these event invocators async. It&#39;s not as simple as my earlier post on &lt;a href=&quot;http://robjdavey.blogspot.com/2012/02/async-in-c-part-2-making-methods-async.html&quot;&gt;Making Methods Async&lt;/a&gt;. In that post we were creating a delegate to a single method and invoking it asynchronously. The problem with event delegates is that they are likely to have multiple methods registered in their invocation list, and BeginInvoke will fail if the delegate contains more than one method in the invocation list. To get around this we must call each method individually using BeginInvoke. Here&#39;s the code for both asynchronous event invocators and their corresponding callback methods:
&lt;br /&gt;
&lt;pre&gt;public static void BeginRaiseEvent(this EventHandler handler, object sender, EventArgs e)
{
    EventHandler temp = handler;
    if(temp != null)
    {
        foreach(EventHandler eventHandler in temp.GetInvocationList())
        {
            eventHandler.BeginInvoke(sender, e, EndRaiseEvent, eventHandler);
        }
    }
}

private static void EndRaiseEvent(IAsyncResult result)
{
    var handler = ((AsyncResult)result).AsyncDelegate as EventHandler;
    if(handler != null)
    {
        try
        {
            handler.EndInvoke(result);
        }
        catch(Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }
    }
}

public static void BeginRaiseEvent&amp;lt;T&amp;gt;(this EventHandler&amp;lt;T&amp;gt; handler, object sender, T e)
    where T : EventArgs
{
    EventHandler&amp;lt;T&amp;gt; temp = handler;
    if(temp != null)
    {
        foreach(EventHandler&amp;lt;T&amp;gt; eventHandler in temp.GetInvocationList())
        {
            eventHandler.BeginInvoke(sender, e, EndRaiseEvent&amp;lt;T&amp;gt;, eventHandler);
        }
    }
}

private static void EndRaiseEvent&amp;lt;T&amp;gt;(IAsyncResult result)
    where T : EventArgs
{
    var handler = ((AsyncResult)result).AsyncDelegate as EventHandler&amp;lt;T&amp;gt;;
    if(handler != null)
    {
        try
        {
            handler.EndInvoke(result);
        }
        catch(Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }
    }
}&lt;/pre&gt;
Now we can invoke any event we like asynchronously by simply calling the BeginRaiseEvent method like this:
&lt;pre&gt;MyEvent.BeginRaiseEvent(this, EventArgs.Empty);&lt;/pre&gt;
Enjoy :)</content><link rel='replies' type='application/atom+xml' href='http://robjdavey.blogspot.com/feeds/692322484057866943/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://robjdavey.blogspot.com/2012/02/raising-events-in-c.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/692322484057866943'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/692322484057866943'/><link rel='alternate' type='text/html' href='http://robjdavey.blogspot.com/2012/02/raising-events-in-c.html' title='Raising Events in C#'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/10612519606212564303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total><georss:featurename>Walton-le-Dale, Preston, Lancashire PR5 4PE, UK</georss:featurename><georss:point>53.7360157 -2.6862353</georss:point><georss:box>53.733667700000005 -2.6911708 53.7383637 -2.6812997999999997</georss:box></entry><entry><id>tag:blogger.com,1999:blog-6892494754021144209.post-2051932327493179775</id><published>2012-02-20T17:00:00.000+00:00</published><updated>2013-01-27T12:50:57.045+00:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="async"/><category scheme="http://www.blogger.com/atom/ns#" term="c#"/><category scheme="http://www.blogger.com/atom/ns#" term="client"/><category scheme="http://www.blogger.com/atom/ns#" term="network"/><category scheme="http://www.blogger.com/atom/ns#" term="server"/><category scheme="http://www.blogger.com/atom/ns#" term="socket"/><category scheme="http://www.blogger.com/atom/ns#" term="tcp"/><title type='text'>Creating an asynchronous TCP Server</title><content type='html'>&lt;b&gt;Creating an asynchronous TCP Server&lt;/b&gt;
&lt;br /&gt;
How do I make an asynchronous TCP server? This is a question that gets asked regularly by C# developers but isn&#39;t documented well in many places. When I was doing my degree I studied this subject in some detail as I was creating my own TCP based Client/Server application. There are a lot of examples on the net that I&#39;ve seen in the past, some good, some bad, but none that I feel are as effective as the method I used to create my server. First off here&#39;s a few ways that you shouldn&#39;t do it...&lt;br /&gt;
&lt;b&gt;Polling&lt;/b&gt;
&lt;br /&gt;
This isn&#39;t asynchronous, it just spins around in a loop using unnecessary processor cycles checking to see if clients have anything new to tell it, and if they do the other clients will have to wait until it&#39;s finished dealing with the current request. This method is simple (because it&#39;s single threaded) but definitely the worst way to implement something that definitely needs to be asynchronous.&lt;br /&gt;
&lt;b&gt;Creating threads&lt;/b&gt;
&lt;br /&gt;
Of course you can create a thread for each client that connects to your listener and let it poll itself, or block that thread until the user sends some information. The problem with this I find is that now you&#39;re in charge of that thread. It&#39;s your responsibility to ensure that thread is managed correctly. If the user goes to close the app and you have a blocking call on that thread, you could end up with the application hanging in the background. This can make debugging a huge pain.&lt;br /&gt;
&lt;b&gt;So what&#39;s the best way&lt;/b&gt;
&lt;br /&gt;
In my opinion the best way to create an asynchronous server in C# is using callbacks. A callback allows a method to go away and execute in a system managed thread and once it&#39;s finished executing, it will call one of our methods and give us the result of the operation. This is good because it means:&lt;br /&gt;
a) if the system managed thread needs to block and the application closes, the system will ensure that thread is joined so the application can close successfully&lt;br /&gt;
b) we don&#39;t have to keep track of the threads ourself, the system does all that for us and passes control back to us at the relevant times&lt;br /&gt;
c) we can&#39;t overload the server, as these threads are borrowed from the systems thread pool it means that if we are currently using all the available threads in the pool, the actions will get queued up until a thread becomes available&lt;br /&gt;
&lt;b&gt;Creating the server&lt;/b&gt;
&lt;br /&gt;
For this example I will use the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx&quot;&gt;TcpListener&lt;/a&gt; and &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx&quot;&gt;TcpClient&lt;/a&gt;. These are wrappers around the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx&quot;&gt;Socket&lt;/a&gt; class so they have slightly lower performance but they make what I am trying to do more obvious in this example. Changing this code to use the Socket class should not take too much work as it supports a similar set of methods.&lt;br /&gt;
The first thing we need to do is the standard creation of a listener and hooking it up to the correct port. There&#39;s no point in us doing this asynchronously as we have to wait for this to be complete before we can start accepting incoming clients so we&#39;ll just do this in the standard synchronous way.&lt;br /&gt;
&lt;pre&gt;listener = new TcpListener(IPAddress.Any, port);
listener.Start();&lt;/pre&gt;
Now that we have an active listener we will start an asynchronous accept of a tcp client. Normally the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.accepttcpclient.aspx&quot;&gt;AcceptTcpClient&lt;/a&gt; method will block until a client connects. By using callbacks we can tell the system to go away and block in a different thread, then when a client connects, call our designated callback method. The callback methods must always match the signature of an &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.asynccallback.aspx&quot;&gt;AsyncCallback&lt;/a&gt; which means it must have a return type of void and a single parameter that is an IAsyncResult. I tend to name all my callbacks as the synchronous method name followed by Callback. We don&#39;t need to use the return value of the call as we will be given the same object in the callback, which is where we will use it. We also don&#39;t need to pass anything in the state parameter as we don&#39;t need any additional information in the callback that isn&#39;t available as an instance member.&lt;br /&gt;
&lt;pre&gt;listener.BeginAcceptTcpClient(AcceptTcpClientCallback, null);&lt;/pre&gt;
In our callback method we need to end the asynchronous method call which will give us back our new TcpClient that just connected. We will then tell the server to begin accepting the next client.&lt;br /&gt;
&lt;pre&gt;private void AcceptTcpClientCallback(IAsyncResult asyncResult)
{
    TcpClient client = listener.EndAcceptTcpClient(asyncResult);
    listener.BeginAcceptTcpClient(AcceptTcpClientCallback, null);
}&lt;/pre&gt;
This method is not yet complete. There are a few issues we need to solve. Firstly, if an exception is thrown in the AcceptTcpClient method then we need to handle this in some way. Normally a user of a synchronous server would wrap the call in a try catch block themselves, however currently we are not on the users thread so they have no way to enclose our method like that. Instead I favour adding an event onto our class of type EventHandler&amp;lt;ErrorEventArgs&amp;gt;. The &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.io.erroreventargs.aspx&quot;&gt;ErrorEventArgs&lt;/a&gt; class can wrap up an exception which we can then pass back to the user (assuming they are listening to the event) to deal with.&lt;br /&gt;
&lt;pre&gt;public event EventHandler&lt;erroreventargs&gt; Error;

public void OnError(object sender, Exception ex)
{
    EventHandler&lt;erroreventargs&gt; handler = Error;
    if(handler != null)
    {
        ErrorEventArgs e = new ErrorEventArgs(ex);
        handler(sender, e);
    }
}

private void AcceptTcpClientCallback(IAsyncResult asyncResult)
{
    TcpClient client;
    try
    {
        client = listener.EndAcceptTcpClient(asyncResult);
    }
    catch (Exception ex)
    {
        OnError(listener, ex);
        Stop();
        return;
    }
    listener.BeginAcceptTcpClient(AcceptTcpClientCallback, null);
}&lt;/erroreventargs&gt;&lt;/erroreventargs&gt;&lt;/pre&gt;
For ease we could do to wrap the client up in a simple object that will allow us to keep it with its buffer. We can expand this at a later date so lets make the wrapper now.&lt;br /&gt;
&lt;pre&gt;public class Client
{
    private readonly TcpClient tcpClient;
    private readonly byte[] buffer;

    public Client(TcpClient tcpClient)
    {
        this.tcpClient = tcpClient;
        int bufferSize = tcpClient.ReceiveBufferSize;
        buffer = new byte[bufferSize];
    }

    public TcpClient TcpClient
    {
        get { return tcpClient; }
    }

    public byte[] Buffer
    {
        get { return buffer; }
    }

    public NetworkStream NetworkStream
    {
        get { return tcpClient.GetStream(); }
    }
}&lt;/pre&gt;
Now we have this wrapper we can create a list to store the connected clients and tell the client to start reading into our buffer.&lt;br /&gt;
&lt;pre&gt;private void AcceptTcpClientCallback(IAsyncResult asyncResult)
{
    // ...
    listener.BeginAcceptTcpClient(AcceptTcpClientCallback, null);
    Client client = new Client(tcpClient);
    connectedClients.Add(client);
    NetworkStream networkStream = client.NetworkStream;
    networkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client);
}&lt;/pre&gt;
So now our client has been accepted asynchronously, our listener is now trying to accept the next client asynchronously, and our new client is asynchronously listening for new data. Of course now we need to implement the read callback we&#39;ve used above. As before this needs to match the AsyncCallback delegate, which takes an IAsyncResult and returns void. The first thing we need to do is get hold of the client this callback belongs to. This is why we passed the client object as the state parameter. Once we have the client we can get the correct network stream object that will allow us to end the asynchronous call. When we end the read it will tell us how many bytes have been read from the client. It should be noted that if you read from the client, and the number of bytes read is 0 (zero) this means that the client has disconnected from us. We can then copy the data that has been read to a new buffer, raise the data read event, and send the client back off to do another asynchronous read.
&lt;br /&gt;
&lt;pre&gt;private void ReadCallback(IAsyncResult asyncResult)
{
    Client client = asyncResult.AsyncState as Client;
    if (client != null)
    {
        NetworkStream networkStream = client.NetworkStream;
        int read;
        try
        {
            read = networkStream.EndRead(asyncResult);
        }
        catch (Exception ex)
        {
            OnError(client, ex);
            return;
        }

        if (read == 0)
        {
            OnClientDisconnected(client.TcpClient);
            connectedClients.Remove(client);
            return;
        }

        byte[] data = new byte[read];
        Buffer.BlockCopy(client.Buffer, 0, data, 0, read);
        OnDataRead(client.TcpClient, data);
        networkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client);
    }
}&lt;/pre&gt;
&lt;b&gt;Summary&lt;/b&gt;
&lt;br /&gt;
This is the basics of an asynchronous server using callbacks. The listener will just keep accepting clients in the background, the clients will keep reading in the background, and your main thread isn&#39;t blocked ever. You can even add the write methods to be asynchronous so that even when you write to the clients you aren&#39;t blocked. If you want to know when data has been sent successfully you could always assign each write operation a Guid and then event the Guid when the write ends successfully. If I get chance I&#39;ll post a full example at a later date. Enjoy.</content><link rel='replies' type='application/atom+xml' href='http://robjdavey.blogspot.com/feeds/2051932327493179775/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://robjdavey.blogspot.com/2012/02/creating-asynchronous-tcp-server.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/2051932327493179775'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/2051932327493179775'/><link rel='alternate' type='text/html' href='http://robjdavey.blogspot.com/2012/02/creating-asynchronous-tcp-server.html' title='Creating an asynchronous TCP Server'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/10612519606212564303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total><georss:featurename>Walton-le-Dale, Preston, Lancashire PR5 4PE, UK</georss:featurename><georss:point>53.7360157 -2.6862353</georss:point><georss:box>53.733667700000005 -2.6911708 53.7383637 -2.6812997999999997</georss:box></entry><entry><id>tag:blogger.com,1999:blog-6892494754021144209.post-6186476772037317573</id><published>2012-02-16T17:00:00.000+00:00</published><updated>2012-02-17T14:31:29.829+00:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="c#"/><category scheme="http://www.blogger.com/atom/ns#" term="lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="linq"/><category scheme="http://www.blogger.com/atom/ns#" term="predicates"/><category scheme="http://www.blogger.com/atom/ns#" term="string"/><title type='text'>String validation in C#</title><content type='html'>There are times when we need to check that all the characters in a string are within our acceptable range. In this post I will demonstrate how to create various useful methods for validating the characters in strings. The information in this post will use &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb397926.aspx&quot;&gt;LINQ&lt;/a&gt; and &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb397687.aspx&quot;&gt;Lambda Expressions&lt;/a&gt;, so it&#39;s necessary to be using C# 3.5+.&lt;br /&gt;
First lets look at what we might want to check. Lets say we want to ensure that a string does not contain any control characters. We can check for these with &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/18zw7440.aspx&quot;&gt;Char.IsControl&lt;/a&gt;&amp;nbsp;method. This method is what we would call a Char &lt;b&gt;predicate&lt;/b&gt;, in other words, it takes a Char as an input, and returns true or false depending on whether the char meets the criteria.&lt;br /&gt;
So here&#39;s a simple method that would check a string for containing control characters:&lt;br /&gt;
&lt;pre&gt;public static bool ContainsControlCharacters(string str)
{
    foreach(char c in str)
    {
        if (char.IsControl(c))
        {
            return true;
        }
    }
    return false;
}
&lt;/pre&gt;
This is all very good, but because IsControl is a char predicate, we can use it as a parameter for some of the LINQ extension methods. As we&#39;re checking to see if there are any control characters we want to use the extension method &#39;Any&#39;. So lets try that again:&lt;br /&gt;
&lt;pre&gt;public static bool ContainsControlCharacters(string str)
{
    return str.Any(char.IsControl);
}
&lt;/pre&gt;
It&#39;s very neat and simple. It almost reads like English... &quot;&lt;b&gt;return&lt;/b&gt; whether &lt;b&gt;string&lt;/b&gt; has &lt;b&gt;any char&lt;/b&gt; that &lt;b&gt;is control&lt;/b&gt;&quot;.
However the Char class actually has a lot of these char predicates, so lets make this a bit more generic, lets allow the user to pass any predicate they like (as long as it takes a char, and returns a bool).&lt;br /&gt;
&lt;pre&gt;public static bool Contains(string str, Func&amp;lt;char, bool&amp;gt; predicate)
{
    return str.Any(predicate);
}
&lt;/pre&gt;
So now the user can call our method with whatever they like, so they may say:
&lt;br /&gt;
&lt;pre&gt;bool result = Contains(&quot;Hello World!&quot;, char.IsControl);&lt;/pre&gt;
or they could pass a lambda expression:
&lt;br /&gt;
&lt;pre&gt;bool result = Contains(&quot;Hello World!&quot;, c =&amp;gt; c &amp;gt; &#39;D&#39; &amp;amp;&amp;amp; c &amp;lt; &#39;I&#39;);&lt;/pre&gt;
For anyone that doesn&#39;t understand lambda the expression above matches the signature &lt;i&gt;bool Method(char)&lt;/i&gt;.
The c =&amp;gt; means we have an input we called c, which we know must be a char based on the method signature.
Then we return from the method the result of (c &amp;gt; &#39;D&#39; &amp;amp;&amp;amp; c &amp;lt; &#39;I&#39;).
So basically this is a predicate that matches the characters &#39;E&#39;, &#39;F&#39;, &#39;G&#39;, and &#39;H&#39;. Not very useful I know but an example all the same!&lt;br /&gt;
So now we can check a string for multiple conditions, but what if we want to know things like &quot;Is this string only made up of this type of character?&quot;, or &quot;Does this string not contain any of these characters?&quot;. We could call this method in various ways, but wouldn&#39;t it be much easier to create some methods we can use for this type of question.
&lt;br /&gt;
&lt;pre&gt;public static bool OnlyContains(string str, Func&amp;lt;char,bool&amp;gt; predicate)&lt;/pre&gt;
&lt;pre&gt;&lt;char, bool=&quot;&quot;&gt;{
    return str.All(predicate);
}

public static bool DoesNotContain(string str, Func&amp;lt;char,bool&amp;gt;&lt;char, bool=&quot;&quot;&gt; predicate)
{
    return !str.Any(predicate);
}&lt;/char,&gt;&lt;/char,&gt;&lt;/pre&gt;
These methods can tell us if a string is only made up of, or does not contain any of, a particular type of character.
Of course sometimes we may want to say &quot;Only made up of letters, numbers, whitespace and puctuation&quot;. Well of course this would fail in the above code because we&#39;d have to check these individually, or write a new complex predicate to test all these. So why not make it so the code can take multiple predicates?
&lt;br /&gt;
&lt;pre&gt;&lt;char, bool=&quot;&quot;&gt;&lt;char, bool=&quot;&quot;&gt;
&lt;/char,&gt;&lt;/char,&gt;public static bool OnlyContains(string str, params Func&amp;lt;char, bool&amp;gt;[] predicates)
{
    return str.All(c =&amp;gt; predicates.Any(p =&amp;gt; p(c)));
}&lt;/pre&gt;
&lt;pre&gt;public static bool DoesNotContain(string str, params Func&amp;lt;char, bool&amp;gt;[] predicates)
{
    return !str.Any(c =&amp;gt; predicates.Any(p =&amp;gt; p(c)));
}&lt;/pre&gt;
Now these methods can take a variety of predicates into each one so we can perform complex statements such as:
&lt;br /&gt;
&lt;pre&gt;string str = &quot;Hello World!&quot;;
bool result = OnlyContains(str, char.IsLetter, char.IsPunctuation, char.IsWhiteSpace) &amp;amp;&amp;amp;
              DoesNotContain(str, char.IsControl, c =&amp;gt; (c == &#39;@&#39;));
&lt;/pre&gt;
The above statement says &quot;Ensure that str only contains letters, punctuation and whitespace but does not contain control characters or the letter @&quot;.
Very useful.
The only thing I&#39;d use to top this off, it to make the methods an extension, by changing the method signature to
&lt;br /&gt;
&lt;pre&gt;public static bool OnlyContains(&lt;b&gt;this&lt;/b&gt; string str, params Func&amp;lt;char, bool&amp;gt;[] predicates)&lt;/pre&gt;
which then allows us to simply say
&lt;pre&gt;str.DoesNotContain(char.IsControl);&lt;/pre&gt;
Simple! :D</content><link rel='replies' type='application/atom+xml' href='http://robjdavey.blogspot.com/feeds/6186476772037317573/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://robjdavey.blogspot.com/2012/02/string-validation-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/6186476772037317573'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/6186476772037317573'/><link rel='alternate' type='text/html' href='http://robjdavey.blogspot.com/2012/02/string-validation-in-c.html' title='String validation in C#'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/10612519606212564303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total><georss:featurename>Walton-le-Dale, Preston, Lancashire PR5 4PE, UK</georss:featurename><georss:point>53.7360157 -2.6862353</georss:point><georss:box>53.733667700000005 -2.6911708 53.7383637 -2.6812997999999997</georss:box></entry><entry><id>tag:blogger.com,1999:blog-6892494754021144209.post-3871542929132214778</id><published>2012-02-14T17:00:00.000+00:00</published><updated>2012-02-21T10:19:41.568+00:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="async"/><category scheme="http://www.blogger.com/atom/ns#" term="c#"/><category scheme="http://www.blogger.com/atom/ns#" term="threading"/><title type='text'>Async in C# - Part 2: Making methods async</title><content type='html'>&lt;b&gt;Contents&lt;/b&gt;&lt;br /&gt;
Async in C#&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;http://robjdavey.blogspot.com/2012/02/async-in-c-part-1-what-is-async.html&quot;&gt;What is async?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://robjdavey.blogspot.com/2012/02/async-in-c-part-2-making-methods-async.html&quot;&gt;Making methods async&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;b&gt;Introduction&lt;/b&gt;&lt;br /&gt;
In Part 1 I talked about what asynchronous programming is and how it is implemented within the .NET framework (or more specifically C#) currently. In this part I&#39;ll look at how we can take any method we like and make it asynchronous. So lets pick a random synchronous method in the .NET framework and create our own asynchronous implementation. For this I&#39;m going to use the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.console.readkey.aspx&quot;&gt;Console.ReadKey&lt;/a&gt;. It&#39;s not a method that you&#39;re often going to use as an asynchronous method, however it has an input parameter, a return type, and it blocks the program while you&#39;re waiting for the user to press a key, which makes it perfect for us to use as an example.&lt;br /&gt;
&lt;b&gt;Breaking down the signature&lt;/b&gt;
&lt;br /&gt;
The signature for the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/x3h8xffw.aspx&quot;&gt;Console.ReadKey&lt;/a&gt; overload that we&#39;re going to use is:&lt;br /&gt;
&lt;pre&gt;public static ConsoleKeyInfo ReadKey(bool intercept)&lt;/pre&gt;
So the first thing we will need to do is create a delegate that matches this signature. We&#39;ll call this delegate ReadKeyDelegate.&lt;br /&gt;
&lt;pre&gt;public delegate ConsoleKeyInfo ReadKeyDelegate(bool intercept);&lt;/pre&gt;
Please note that although I have created this delegate explicitly this is not necessary. Instead you can use the &lt;br /&gt;
&lt;pre&gt;Func&amp;lt;bool, consolekeyinfo&amp;gt;&lt;/pre&gt;
delegate when required and get the same effect.&lt;br /&gt;
As we saw before, to make a method asynchronous we need to create two methods, a Begin and an End. The Begin method will take the parameters from our synchronous method, and the End method will return the result. As we also discussed before, a Begin method should always have a return type of IAsyncResult, and always have the parameters from the synchronous method, followed by an AsyncCallback delegate and an object. Lets create the signature for our begin method now:&lt;br /&gt;
&lt;pre&gt;public static IAsyncResult BeginReadKey(bool intercept,
    AsyncCallback callback, object state)&lt;/pre&gt;
So there we have it, a method that is called Begin[methodname] with a return type of IAsyncResult and the parameters are the same as the synchronous method followed by an AsyncCallback and an object. It should also be noted that as the synchronous method was static, I&#39;ve made this method static too. We don&#39;t want to make our users have to create an instance of a class just to use a static method asynchronously. So now lets look at the End method, this needs to have a return type that matches the synchronous methods return type, so ConsoleKetInfo in this case, and also take a single parameter of an IAsyncResult. Lets create this now:&lt;/methodname&gt;&lt;br /&gt;
&lt;pre&gt;public static ConsoleKeyInfo EndReadKey(IAsyncResult asyncResult)&lt;/pre&gt;
Again I have made this static, your Begin and End methods should always be either both static or both instance members, and best practice would be to make them always match their synchronous counterpart.&lt;br /&gt;
&lt;b&gt;Implementing the methods&lt;/b&gt;
&lt;br /&gt;
Now that we have our method signatures and our delegate, the actual implementation of the methods is extremely easy. Lets start with the begin method. First we need to create an instance of our delegate and connect it to the synchronous method:&lt;br /&gt;
&lt;pre&gt;ReadKeyDelegate readKey = Console.ReadKey;&lt;/pre&gt;
As I mentioned before, if you do not want to create an explicit delegate you can of course use the built in Func delegate like this:&lt;br /&gt;
&lt;pre&gt;Func&amp;lt;bool, consolekeyinfo&amp;gt; readKey = Console.ReadKey;&lt;/pre&gt;
For the moment however we&#39;ll stick to our explicit delegate. So now we have a delegate created we want to asynchronously invoke this method using the parameters the user has passed in. To do this we will use the BeginInvoke method from our delegate. This method will match our Begin signature exactly, and so we can just return its result to the user:&lt;br /&gt;
&lt;pre&gt;return readKey.BeginInvoke(intercept, callback, state);&lt;/pre&gt;
That&#39;s it, the begin method is now complete. I told you it was easy. Now lets look at the End method. The first thing we need to do is get the delegate that matches the call. An End call must always be performed on the same delegate that the Begin was called on, so if we were to create a new ReadKeyDelegate and assign it to ReadKey again, the End call would fail because this is a different instance of the delegate. Luckily for us, the IAsyncResult we are passed actually knows what the delegate it was called on was! This is because internally it is actually an &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.asyncresult.aspx&quot;&gt;AsyncResult&lt;/a&gt; object. So lets get hold of our delegate:&lt;br /&gt;
&lt;pre&gt;ReadKeyDelegate readKey =
    (ReadKeyDelegate)((AsyncResult)asyncResult).AsyncDelegate;&lt;/pre&gt;
Now that we&#39;ve got our original delegate it&#39;s simply a case of calling EndInvoke on the delegate and passing the result back to the user (when I said this was easy, I meant it):&lt;br /&gt;
&lt;pre&gt;return readKey.EndInvoke(asyncResult);&lt;/pre&gt;
So just to recap, here&#39;s all our code so far in full:&lt;br /&gt;
&lt;pre&gt;public delegate ConsoleKeyInfo ReadKeyDelegate(bool intercept);

public static IAsyncResult BeginReadKey(bool intercept,
    AsyncCallback callback, object state)
{
    ReadKeyDelegate readKey = Console.ReadKey;
    return readKey.BeginInvoke(intercept, callback, state);
}

public static ConsoleKeyInfo EndReadKey(IAsyncResult asyncResult)
{
    ReadKeyDelegate readKey = 
        (ReadKeyDelegate)((AsyncResult)asyncResult).AsyncDelegate;
    return readKey.EndInvoke(asyncResult);
}&lt;/pre&gt;
&lt;b&gt;Summary&lt;/b&gt;
&lt;br /&gt;
So effectively that&#39;s it. That is everything that is required to make any method in C# asynchronous.
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Create a delegate that matches the methods signature
&lt;/li&gt;
&lt;li&gt;Create a Begin method that creates an instance of the delegate and calls BeginInvoke.
&lt;/li&gt;
&lt;li&gt;Create an End method that retrieves the instance of our delegate and calls EndInvoke.
&lt;/li&gt;
&lt;/ol&gt;
Now you or your user can use these methods in the same way I described in &lt;a href=&quot;http://robjdavey.blogspot.com/2012/02/async-in-c-part-1-what-is-async.html&quot;&gt;Part 1&lt;/a&gt;.
Enjoy</content><link rel='replies' type='application/atom+xml' href='http://robjdavey.blogspot.com/feeds/3871542929132214778/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://robjdavey.blogspot.com/2012/02/async-in-c-part-2-making-methods-async.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/3871542929132214778'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/3871542929132214778'/><link rel='alternate' type='text/html' href='http://robjdavey.blogspot.com/2012/02/async-in-c-part-2-making-methods-async.html' title='Async in C# - Part 2: Making methods async'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/10612519606212564303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total><georss:featurename>Walton-le-Dale, Preston, Lancashire PR5 4PE, UK</georss:featurename><georss:point>53.7360157 -2.6862353</georss:point><georss:box>53.733667700000005 -2.6911708 53.7383637 -2.6812997999999997</georss:box></entry><entry><id>tag:blogger.com,1999:blog-6892494754021144209.post-3846027378773468565</id><published>2012-02-14T01:00:00.177+00:00</published><updated>2012-02-21T10:22:14.999+00:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="async"/><category scheme="http://www.blogger.com/atom/ns#" term="c#"/><category scheme="http://www.blogger.com/atom/ns#" term="threading"/><title type='text'>Async in C# - Part 1: What is async?</title><content type='html'>&lt;b&gt;&lt;br /&gt;
Contents&lt;/b&gt;&lt;br /&gt;
Async in C#&lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;&lt;li&gt;&lt;a href=&quot;http://robjdavey.blogspot.com/2012/02/async-in-c-part-1-what-is-async.html&quot;&gt;What is async?&lt;/a&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://robjdavey.blogspot.com/2012/02/async-in-c-part-2-making-methods-async.html&quot;&gt;Making methods async&lt;/a&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;/ol&gt;&lt;b&gt; Introduction&lt;/b&gt;&lt;br /&gt;
First lets start with a quick explanation of what asynchronous is. In a normal computer program operations are synchronous. It does one thing, when it&#39;s done it moves onto the next. This is synchronous behaviour. It only focuses on one task at once. When something happens asynchronously it means the computer can start one task, and while that task is running it can be doing something else. At a later point in time it can catch up with the previous task to get the result of it when it&#39;s needed. This can be extremely useful if you have a task that will take a long time to run, but you do not need the result of it immediately. You can start the task as soon as possible and then later on when you need to use the result of the task you can either get it immediately (if the task has now finished) or you can wait at that point for it to finish (but this wait will be shorter than if you only just started the task of course). &lt;br /&gt;
&lt;b&gt; Async in C#&lt;/b&gt;&lt;br /&gt;
When we perform tasks&amp;nbsp;asynchronously&amp;nbsp;in C# they occur on a different thread. Of course it is possible to manually create the thread yourself and tell it what method to execute and so on, but then you have to keep track of the thread yourself and it&#39;s all your responsibility. Why go to all that effort when C# already has the technology built in to do it for you. &lt;br /&gt;
&lt;b&gt; A C# example&lt;/b&gt;&lt;br /&gt;
To begin lets look at an example method in C# that already has an asynchronous implementation. The synchronous method is &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses.aspx&quot; target=&quot;_blank&quot;&gt;Dns.GetHostAddresses&lt;/a&gt;. This method looks up the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.net.ipaddress.aspx&quot; target=&quot;_blank&quot;&gt;IPAddress&lt;/a&gt;es for a particular host name (e.g. www.google.co.uk). Of course if the addresses aren&#39;t already in your ARP table your machine will need to talk to your DNS server, and any communication over a network can take time. If we don&#39;t want out program to stop while it&#39;s looking these values up then we can use the Asynchronous version of it. This comes in the form of two different methods,&amp;nbsp;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.net.dns.begingethostaddresses.aspx&quot;&gt;Dns.BeginGetHostAddresses&lt;/a&gt; and &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.net.dns.endgethostaddresses.aspx&quot;&gt;Dns.EndGetHostAddresses&lt;/a&gt;, and we need to use both to complete an asynchronous operation. &lt;br /&gt;
&lt;b&gt; The &lt;i&gt;Begin...&lt;/i&gt; method&lt;/b&gt;&lt;br /&gt;
The &quot;Begin&quot; method starts the&amp;nbsp;asynchronous&amp;nbsp;operation on a different thread. In addition to whatever parameters were required for the synchronous method, it will also take an &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/System.AsyncCallback.aspx&quot;&gt;AsyncCallback&lt;/a&gt; delegate and an object. The method signature for an AsyncCallback is: &lt;br /&gt;
&lt;pre&gt;public delegate void AsyncCallback(IAsyncResult ar);&lt;/pre&gt;This delegate is the method that will get called when our asynchronous operation is completed. The object, usually known as state, can be any object which you would like to be available to you from within the callback method. &lt;br /&gt;
&lt;b&gt; The &lt;i&gt;End...&lt;/i&gt; method&lt;/b&gt;&lt;br /&gt;
The &quot;End&quot; method is used to complete the asynchronous operation. When this is called it will return the value that was returned from the method called asynchronously, so in our example above EndGetHostAddresses will return an IPAddress[]. It always takes a single parameter which is an &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx&quot;&gt;IAsyncResult&lt;/a&gt;&amp;nbsp;interface. The object passed in here must be the same one that was generated by the Begin method otherwise it will throw an exception. If you are using the callback mechanism this will be sorted for you so you don&#39;t need to worry but I&#39;ll explain more on that in a minute. &lt;br /&gt;
&lt;b&gt; Signatures&lt;/b&gt;&lt;br /&gt;
So now lets see how the method signature of our&amp;nbsp;synchronous&amp;nbsp;method breaks down into our two asynchronous methods. Our original method signature was: &lt;br /&gt;
&lt;pre&gt;public static &lt;span style=&quot;color: red;&quot;&gt;IPAddress[]&lt;/span&gt; GetHostAddresses(&lt;span style=&quot;color: blue;&quot;&gt;string hostNameOrAddress&lt;/span&gt;)&lt;/pre&gt;The begin method signature is: &lt;br /&gt;
&lt;pre&gt;public static &lt;span style=&quot;color: purple;&quot;&gt;IAsyncResult&lt;/span&gt; BeginGetHostAddresses(&lt;span style=&quot;color: blue;&quot;&gt;string hostNameOrAddress&lt;/span&gt;,
    &lt;span style=&quot;color: purple;&quot;&gt;AsyncCallback requestCallback, Object state&lt;/span&gt;)&lt;/pre&gt;and the end method signaure is: &lt;br /&gt;
&lt;pre&gt;public static &lt;span style=&quot;color: red;&quot;&gt;IPAddress[]&lt;/span&gt; EndGetHostAddresses(&lt;span style=&quot;color: purple;&quot;&gt;IAsyncResult asyncResult&lt;/span&gt;)&lt;/pre&gt;As you can see from the colour coding the whole signature is there, it&#39;s just spread over the two methods. We can also see from the &lt;span style=&quot;color: purple;&quot;&gt;purple&lt;/span&gt; text the additional parts of a signature that should always be present in the begin and end methods for asynchronous calls. &lt;br /&gt;
&lt;b&gt; Usage&lt;/b&gt;&lt;br /&gt;
There are two different ways in which the asynchronous methods can be used to&amp;nbsp;retrieve&amp;nbsp;a value asynchronously. These are by using callbacks (we&#39;ll call this the &quot;Callback&quot; method for now) or by keeping track of the IAsyncResult that is generated (we&#39;ll call this the &quot;Variable&quot; method). &lt;br /&gt;
&lt;b&gt; Callback Method&lt;/b&gt;&lt;br /&gt;
To use the callback method we must declare a method that will be called when the method completes. This method must match the signature of an AsyncCallback. Within this method is where we will call our End method. Here&#39;s some example code of this in use. &lt;br /&gt;
&lt;pre&gt;namespace RDavey
{
    public class AsyncTest
    {
        public void Foo()
        {
            Dns.BeginGetHostAddresses(
                // The usual host name parameter
                &quot;www.google.com&quot;,
                // The AsyncCallback delegate to call when we&#39;re done
                GetHostAddressesCallback,
                // Our state is null, we don&#39;t need to send any additional info
                null);
        }

        public void GetHostAddressesCallback(IAsyncResult ar)
        {
            // We pass the IAsyncResult into the End method.
            IPAddress[] addresses = Dns.EndGetHostAddresses(ar);
            // We can now do what we want with &#39;addresses&#39;.
            // We may just wish to store it as a member variable.
            // If we had set the &#39;state&#39; object we could retrieve it like this:
            object state = ar.AsyncState;
            // Of course in this example it is null because we passed null!
        }
    }
}
&lt;/pre&gt;&lt;b&gt; Variable Method&lt;/b&gt;&lt;br /&gt;
The variable method is best suited to asynchronous operations where we will need the result of the operation later in the same method. When we call begin it will give us back the IAsyncResult that corresponds to our asynchronous operation. We can then use this at a later date to call the End method. If the End method has not yet finished, it will then block (effectively becoming synchronous) until it is done. Here&#39;s some code to demonstrate this method. &lt;br /&gt;
&lt;pre&gt;namespace RDavey
{
    public class AsyncTest
    {
        public void Foo()
        {
            IAsyncResult ar = Dns.BeginGetHostAddresses(
                // The usual host name parameter
                &quot;www.google.com&quot;,
                // We&#39;re not using the callback method so this can be null
                null,
                // Our state is null, we don&#39;t need to send any additional info
                null);
            // Now we can do other stuff here
            // ...
            // While the GetHostAddresses occurs in the background
            // ...
            // And once we&#39;re ready to use the IP Addresses we call
            IPAddress[] addresses = Dns.EndGetHostAddresses(ar);
        }
    }
}
&lt;/pre&gt;&lt;b&gt; Next...&lt;/b&gt;&lt;br /&gt;
In Part 2 I&#39;ll discuss how to make our own asynchronous version of methods.</content><link rel='replies' type='application/atom+xml' href='http://robjdavey.blogspot.com/feeds/3846027378773468565/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://robjdavey.blogspot.com/2012/02/async-in-c-part-1-what-is-async.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/3846027378773468565'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/3846027378773468565'/><link rel='alternate' type='text/html' href='http://robjdavey.blogspot.com/2012/02/async-in-c-part-1-what-is-async.html' title='Async in C# - Part 1: What is async?'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/10612519606212564303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total><georss:featurename>Walton-le-Dale, Preston, Lancashire PR5 4PE, UK</georss:featurename><georss:point>53.7360157 -2.6862353000000212</georss:point><georss:box>53.7355272 -2.6870488000000212 53.736504200000006 -2.6854218000000212</georss:box></entry><entry><id>tag:blogger.com,1999:blog-6892494754021144209.post-8918104902340041051</id><published>2012-02-13T17:00:00.001+00:00</published><updated>2012-02-14T12:42:19.936+00:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="c#"/><category scheme="http://www.blogger.com/atom/ns#" term="marshal"/><category scheme="http://www.blogger.com/atom/ns#" term="struct"/><title type='text'>Casting bytes to structures in C#</title><content type='html'>Sometimes you&#39;ll end up in a situation where you&#39;ve read some data in it&#39;s binary form and you want to get this data formatted as a structure. In C++ you could just cast the memory location to the type of structure you want and away you go, but as C# is managed it&#39;s not that easy.&lt;br /&gt;
Here&#39;s a fast and easy set of extension methods that can do this for you. For this to work the structure used &lt;b&gt;must&lt;/b&gt; be set to either &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.layoutkind.aspx&quot; target=&quot;_blank&quot;&gt;LayoutKind&lt;/a&gt;.Sequential or &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.layoutkind.aspx&quot; target=&quot;_blank&quot;&gt;LayoutKind&lt;/a&gt;.Explicit. Although structures are generally sequential automatically this shouldn&#39;t be relied on and should be set explicitly. This can be done using a &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx&quot; target=&quot;_blank&quot;&gt;StructLayoutAttribute&lt;/a&gt;.&lt;br /&gt;
The ByteCaster class can be used in one of two ways, as a static call&lt;br /&gt;
&lt;pre&gt;MyStruct myStruct = ByteCaster.GetStructure&amp;lt;MyStruct&amp;gt;(bytes);&lt;/pre&gt;or as an extension method&lt;br /&gt;
&lt;pre&gt;MyStruct myStruct = bytes.GetStructure&amp;lt;MyStruct&amp;gt;();&lt;/pre&gt;There is also a &quot;try&quot; version of the method which will not throw but will return a boolean to inform the caller if the operation succeeded. If this boolean is false, the structure will be a valid struct, but the data within it will not be representative of the data so this value should always be checked.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;namespace RDavey
{
&amp;nbsp; &amp;nbsp; /// &amp;lt;summary&amp;gt;
&amp;nbsp; &amp;nbsp; /// Allows the manipulation of bytes into structures.
&amp;nbsp; &amp;nbsp; /// &amp;lt;/summary&amp;gt;
&amp;nbsp; &amp;nbsp; public static class ByteCaster
&amp;nbsp; &amp;nbsp; {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;summary&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// Attempts to get a byte array as a structure.
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;/summary&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;typeparam name=&quot;T&quot;&amp;gt;The type of structure we wish to represent the bytes as.&amp;lt;/typeparam&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;param name=&quot;bytes&quot;&amp;gt;The bytes to convert to a structure.&amp;lt;/param&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;param name=&quot;structure&quot;&amp;gt;The structure we wish to populate.&amp;lt;/param&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;returns&amp;gt;True if the operation succeeded, false if there was an error.&amp;lt;/returns&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; public static bool TryGetStructure&amp;lt;T&amp;gt;(this byte[] bytes, out T structure) where T : struct
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; try
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; structure = GetStructure&amp;lt;T&amp;gt;(bytes);
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return true;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; catch
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; structure = default(T);
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return false;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }

&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;summary&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// Gets a strucure representation of a byte array.
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;/summary&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;typeparam name=&quot;T&quot;&amp;gt;The type of structure we wish to represent the bytes as.&amp;lt;/typeparam&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;param name=&quot;bytes&quot;&amp;gt;The bytes to convert to a structure.&amp;lt;/param&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;exception cref=&quot;ArgumentException&quot;&amp;gt;The structureType parameter layout is not sequential or explicit.
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// -or-
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// The structureType parameter is a generic type.&amp;lt;/exception&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; /// &amp;lt;returns&amp;gt;The structure populated with the data from the byte array.&amp;lt;/returns&amp;gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; public static T GetStructure&amp;lt;T&amp;gt;(this byte[] bytes) where T : struct
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; GCHandle gch = GCHandle.Alloc(bytes, GCHandleType.Pinned);
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; IntPtr ptr = gch.AddrOfPinnedObject();
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; T result;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; try
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; result = (T)Marshal.PtrToStructure(ptr, typeof(T));
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; finally
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; gch.Free();
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return result;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }
&amp;nbsp; &amp;nbsp; }
}
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://robjdavey.blogspot.com/feeds/8918104902340041051/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://robjdavey.blogspot.com/2012/02/casting-bytes-to-structures-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/8918104902340041051'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/8918104902340041051'/><link rel='alternate' type='text/html' href='http://robjdavey.blogspot.com/2012/02/casting-bytes-to-structures-in-c.html' title='Casting bytes to structures in C#'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/10612519606212564303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total><georss:featurename>Walton-le-Dale, Preston, Lancashire PR5 4PE, UK</georss:featurename><georss:point>53.7360157 -2.6862353000000212</georss:point><georss:box>53.7355272 -2.6870488000000212 53.736504200000006 -2.6854218000000212</georss:box></entry><entry><id>tag:blogger.com,1999:blog-6892494754021144209.post-1757780840697350703</id><published>2012-02-11T17:00:00.002+00:00</published><updated>2012-02-14T12:42:41.477+00:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="misc"/><title type='text'>New Blog</title><content type='html'>I&#39;ve decided to move over to Blogger (as every other service I use comes from Google and I&#39;m a huge fan of their new dynamic templates).&lt;br /&gt;
I&#39;ll start to migrate my old data over to this website over the coming weeks (although I want to re-write many of the examples to be more user friendly so it may take a short while).</content><link rel='replies' type='application/atom+xml' href='http://robjdavey.blogspot.com/feeds/1757780840697350703/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://robjdavey.blogspot.com/2012/02/new-blog.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/1757780840697350703'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6892494754021144209/posts/default/1757780840697350703'/><link rel='alternate' type='text/html' href='http://robjdavey.blogspot.com/2012/02/new-blog.html' title='New Blog'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/10612519606212564303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total><georss:featurename>Walton-le-Dale, Preston, Lancashire PR5 4PE, UK</georss:featurename><georss:point>53.7360157 -2.6862353000000212</georss:point><georss:box>53.7355272 -2.6870488000000212 53.736504200000006 -2.6854218000000212</georss:box></entry></feed>