The book is divided into 16 easy to read chapters. Chapters contain small snippets of code and demonstrate various security issues ensuring the reader understands the problem being discussed. Detailed advice is then given and solutions provided to fix the various issues.
Issues are supplemented with real world examples and the author’s own experience (I chuckled at the index server example) and help provide some colour to what can be a difficult topic to keep interesting.
The book covers all major web based security issues such as XSS, XSRF, Sql Injection and also related topics such as securing IIS and issues surrounding the file system. Important concepts such as encryption, hashing and certificates are also covered in depth. The final chapters cover advanced topics such as CAS, Securing IIS and third party authentication solutions.
So what could be better? very little the book is clear, easy to read and contains concise examples. I would have perhaps liked to see an example of implementing a custom membership provider and a bit more on client side scripting/ajax related issues but the book does a great job covering the major areas and pointing the reader towards further resources.
I liked that the book provides recipes for dealing with complex problems such as implementing certificate based authentication and implementing Open ID. Several useful tools I wasn’t aware of are also referenced.
Before I began reading Barry’s book although no security expert I considered that I had a pretty good knowledge of security and was glad to see for the most part the book confirmed my understanding! It always surprises me how many web developers have so little knowledge of basic security concepts and best practice. There is no excuse now and if you have never looked into security this book should be required reading! However don’t think that this book has nothing to offer the intermediate/advanced developer as it had many gem’s for me (correct implementation of salting passwords, certificates, ViewStateUserKey, WCF security).
This book is a great introduction to security and related concepts and will serve as a useful reference/cook book to more experienced developers.
]]>Keith Dodds (Thoughtworks) gave an introduction to the group and kudos to him for setting this up. I guess I was a little unclear on what the groups objectives were and think this should have been emphasised more rather than discussions of boards etc. I am a little wary of organizations (particularly in an Agile usergroup) with a hierarchy etc. I do however understand the need for this in larger organisations - especially those that have a membership fee. I found a membership page on Tuesday that I cannot find now that listed individual membership as $100 which seemed a little steep although I understand this would be deducted from price of a yearly conference ticket.
After Keiths introduction there was an excellent speech by Roy Singham on some of the work Thoughtworks had been doing with UNICEF. Whatever you may think about Roy there is no doubt he is a brilliant speaker. Roy held the crowds attention easily and it was fantastic as an amateur speaker myself to see an expert in action.
I am not sure I would agree with all the points Roy made through such as:
It will be interesting to see what happens with the group and it is early days. I like the idea of an agile discussion group and to hear about others experiences of what works and what doesn’t. I do think that there is a risk with this type of group that they can become vehicles for promoting individuals and organisations and very much about being seen to be doing the right thing rather than dealing with the original issues they were set up for.
]]>If you dont know who Barry is the chances are you have run into him or felt his influence if you have attended a UK dev community event (he is the rather vocal lanky irish chap). Barry has contributed a huge amount to the UK development community over the years, is a regular speaker, coordinated the Nxtgen Oxford group (since taken over by the very capable Richard Hopton), Security MVP, author and was fundamental in running and setting up the DDD events. Barry has also assisted me with a number of dev and community related issues. Barry was given a well deserved send off on DDD8.
So in conclusion whilst there is little doubt Barry is a bit of git, he is just probably not as much of one as he would like you to think (probably).
]]>The event was divided into two tracks a beginner and advanced. In practice through people switched between the tracks depending on the topics they were interested in. There were apparently 150 delegates registered for the event with another 100 or so on the waiting list which is a great achievement given the little publicity the event was given. It also bodes well for DDD Melbourne in the coming months.
The day began with a talk from the Development manager of a division of NAB (may not be correct job title) who had some interesting figures on NAB’s development structure and spending. Next up was an excellent key note from Scott Barnes who used to be the product manager for Silverlight. It was really interesting to hear from someone inside Microsoft of their experiences and it was a great presentation although the Mankini image is going to take a bit of repressing.
The next session I attended was by Brendan Forster on MEF amp; Silverlight. MEF’s a tricky thing to demo well and in my experience difficult to get across some of the benefits. I think the session would have worked better in a more intimate group where they could have explored in more detail and would have benefited from more visual examples. Brendan knew his stuff through and probably did a better job than I did when I tried to explain it. I think we both made the same mistake through of using Console applications to demonstrate some of the features. One of the best MEF presentations I have seen was by Ben Hall who demonstrated putting together an application.
Next up was Mahesh Krishnan’s session an intro to Blend. Mahesh did a well structured presentation and I enjoyed this hour even though I knew how to use most of these features.
Lunch was a nice BBQ which worked great on such a hot day with sandwiches being provided on the second day.
I think one of the highlights of day 1 for me was the Qamp; A panel where the inevitable should we wait for HTML 5 question was raised. This was well answered well with responses such as HTML 5 is not actually ratified yet and it will take time for the browsers to catch up. At least at the moment the conclusion seemed to be Silverlight will be the way to go for rich UI experiences which I think I would agree with.
After the QA session there was a lightening talk hour. This was fun and anyone could speak for up to 10 minutes. I decided to jump in with a book plug/10 min intro to VS2010 amp; .net 4. It reminded me of how much I enjoy giving talks and I look forward to my next one.
The next session I saw was Alex amp; Jordan Knight on Designer/Developer. This was an enjoyable session and they were both good presenters (hats off to Alex for his first presentation) and had a great demo app but not sure how much I learnt from this session.
The final session on day 1 was getting started with Silverlight Sketch Flow with Shane Morris. Poor old Shane had a nightmare time with a laptop when it wouldn’t display more than 640 resolution. He did incredibly well under difficult circumstances and still managed a great talk in sweltering heat for an hour. I would like to see more Shane Morris talks as he was very entertaining to listen to and I love learning more about the UX side of things.
Day 2 began with a presentation from Adam Cogan on Sharepoint 2010. I don’t really have any interest in Sharepoint but it was a fun and informative presentation which involved lots of audience interaction.
Next up was Julian Hedt’s presentation on Silverlight controls. Many of the presentations were at an overview level so it was good to see Julian delve deeper. Julian ran out of time just as he was getting onto the testing Silverlight app’s - I’d like to see more from this guy as he had a lot to show and hear more about his testing experiences.
After Julian, Miguel Madro presented on Silverlight security. Miguel started off really well with an interesting example showing how easy it is to modify a Silverlight App and the network traffic it sent. Miguel’s presentation seemed to petter off towards the end a bit and I think he could have made some of the points clearer e.g. never trust client input but it was a fascinating session none the less.
It was then lunch and I had an interesting discussion with Mahesh, Brian, Shane and Microsoft evangelist Michael on Ipad, Iphones, Windows Mobile and writing books.
They day ended with Stephen Dekker discussing his experiences of developing a Silverlight application for NAB. I love hearing about other applications architecture and the problems they had. The parts Stephen showed us looked as if ASP.net would have probably fulfilled the requirements but who knows what else it did and I wouldn’t turn down an opportunity for Silverlight development either! I guess now they also have some experience for more complex apps.
I think the following would have improved the event:
In conclusion these are minor improvements and it was a great weekend thanks to all the speakers and Stephen Dekker for organizing.
]]>Craig Murphy posted a review on his blog and Microsoft evangalist Eric Nelson gave it a mention on his blog.
Below is a review from Dave Sussman. I was particularly interested in Dave's review and advice as he has authored many books himself.
Reviewing Introducing .NET 4.0 with Visual Studio 2010 by Alex Mackey (Apress) was an interesting exercise because I already know quite a lot of the material. The review therefore partly became a hunt for things I didn’t know, of which there were enough to keep me interested. There were however, sections I skipped through lightly simply because the particular topics aren’t part of my development life and therefore aren’t directly relevant. While skimming those topics though, I’ve now enough background knowledge to dig deeper should I need to, a fact that’s been made easier throughout the book by ample references to online topics, blogs, etc, where more depth or discussions could prove useful.
Topic relevancy is the first important point about the book, clearly stated by Alex at the beginning; this is a shallow and wide book, rather than deep and narrow, or as Alex puts is “breadth rather than depth”, which is perhaps more accurate, as shallow gives the impression the book is light on content, which it definitely isn’t. The target audience is developers using previous version of the .NET framework and Visual studio, for whom there has been little time or incentive to either work with the latest betas or read up on the new features. What’s quite bold is the restriction to the Professional edition of Visual Studio 2010, thus eliminating the advanced features which are more niche and aren’t going to be a major part of most developers’ requirements. I like this approach as it reduces the size, and therefore cost, of the book, while still keeping it relevant for the majority of the audience.
Alex clearly breaks down the topics, showing both the toolset and framework features, with enough code to give you an understanding, but without overwhelming you. The opening salvo is into the tool itself, discussion the changes to the editor, the technology behind it and the extensibility it brings; it’s an area that has huge potential for productivity improvements and one that will provide a rich ecosystem of tools. Alex then digs into the languages, the CLR and class libraries and support for parallelization, before breaking out into the frameworks, such as Workflow (WWF), Communication (WCF), and data (EF and WCF Data Services). Next come the UI features: ASP.NET, Ajax and jQuery, MVC, Silverlight and WPF, before finishing up on cloud services and Azure.
Despite the fact that Alex has limited the depth of coverage, at 450 pages there is still plenty of technical material to learn about the new features, as well as learn the basics of many of the technologies. It’s certainly a great overview and a good starting point if you wanted to trial one of the backend or UI frameworks without buying a specific book. I enjoyed it. Is it suitable for ever developer? Of course not, that’s not its purpose. Is it suitable for developers who’ve not been following the 4.0 trends? Absolutely, and I wouldn’t hesitate to recommend it to anyone who needs to get a heads up into .NET 4.0 and Visual Studio 2010. Was there anything I didn’t like? No.
]]>The idea!
Just over a year or so ago I decided to write a book. This decision was brought about by two things: a discussion with a guy called Simon Pease who was contracting at my place of work and frustration with a few developers who kept asking me the same old questions!
Simon and I discussed the huge number of technologies Microsoft were bringing out and how it would be useful if there was an overview book to introduce each new technology. This would negate the need for the reader to wade through blogs, books and conference videos to find areas they were interested in. I thus proposed to write a breadth rather than depth book that would give a good introduction to .net 4 and Visual Studio 2010.
So how do you get to write a book in the first place?
Well if you are well known in your industry I guess you probably get approached but for everyone else you put together a proposal. Chris Webb has some excellent articles and advice on this process.
For everyone else you put together a proposal and discuss it with the publisher. I submitted a proposal directly to Apress via their website. It was nice that Apress gave an unknown a chance to write. My original proposal was for an easy to read overview covering web based changes in VS2010 amp; .net 4. I wanted to focus on the web as that is my own experience. Apress understandably however wanted to cover a wider range of technologies so the proposal was modified to include additional areas.
The entire .net framework is of course huge and this makes for a much bigger proposition and one I don’t think I would attempt on my own again. As you can probably imagine covering the full .net framework was a huge amount of work. Additionally you cannot be an expert in all areas so to ensure I wasn’t writing crazy stuff I spoke to many different people who were experts in their field.
* Tip - consider writing with someone else. This will reduce the workload and give you someone else to bounce ideas off
Once the proposal was approved, contracts were signed. It is my understanding the Apress contract is one of the least restrictive around - you can even view it on the main Apress site.
I then had to write 3 chapters by Xmas 2008 for approval before the rest of the book could continue. Once these chapters were approved I then received the first payment and the book essentially got the go ahead.
Most book publishers will give you an advance payment (mine was $6000 and divided into 3 parts that would be paid throughout the books development.
Note the advance is an advance on final sales not in addition to! This means sales will pay off the advance before you get any more money (the publisher also holds some back in case of returned stock). Peter Cooper has a good post on how this works on his website.
* Tip - don’t be afraid to talk to other people most are very helpful and only too happy to assist. It was fantastic to get contributions and assistance from some of the Microsoft teams directly and some well known individuals in the .net community.
Apress said they would be able to arrange briefings with the Microsoft teams to assist my research. This however never happened and I organised it myself. I was lucky in that I had some good friends and contacts through my user group involvment. I was grateful for the assistance of Microsoft UK evangelists Mike Ormond and Eric Nelson and almost all of the Microsoft teams were very helpful in responding to queries.
* Tip - you are probably going to have to do much the leg work yourself..
When you are writing you will have a number of questions that you will need to discuss with your editor. Dealing with Apress in this respect was a bit frustrating. They must be pretty busy as it took days (and even weeks) to respond to some queries. When they did however the advice was helpful and they certainly have some good people working for them. However Apress even modified the title of my book several times without my approval! Their approach to source control is also “interesting..”
* Tip - Dealing with (some?) publishers can be painful at times (heh they probably say the same about writers!)
Technical Review
One of the highlights of working with Apress was working with my technical reviewer Stefan Turluski. I cannot recommend Stefan highly enough. Stefan was of great help, helped me improve as a developer and the book is sooo much better from his input. We have all read books that contained missing or incomplete instructions. I now appreciate how very easy it is to miss out steps when writing even the simplest bits of code so was grateful for Stefans eagle eye!
* Tip - Technical Review is vital and will be your best friend!
Beta technologies
Writing about Beta technologies is difficult. There is a lack of documentation, stuff doesn’t work properly and there is a big learning curve. When you write a book you will be given probably half the time you would want to write it. At one point I was given 10 days to write a chapter – bear in mind that each chapter is roughly 5000-7000 words, you are researching new changing technologies and you can see how this can be pretty difficult. You want a social life as well as writing a book? forget it!
* Tip - Books take a huge amount of time (but you probably already knew this..)
Its a material world..
Despite the lofty ambitions you may have for your book it is also a product. Remember this. You signed a contract which handed over some of your rights to the publisher. If you want full control then you will have to self publish - seriously consider this option you can probably make more money this way.
I can understand why Apress launched my book when they did (first .net 4/VS2010 book) but personally feel they could have waited a bit longer and I could have added more content (sounds a bit like pretty much any software development project you know!).
If you have read my book you will probably notice the strange double brackets on some of the method names when they are quoted in text, interesting punctuation and a few typos and spelling mistakes. Apress were given a list of many of these to correct (which took me about a week to do) but decided for an some reason not make these changes. This makes me pretty mad and hopefully doesnt detract from the content too much but it does mean the book is not as polished as it could and should have been.
So.. my apologies for these issues but they were out of my control. I guess different publishers have different processes. For example I understand one publisher uses four different technical reviewers to Apress's one so are likely to catch more issues. Additonally given the beta nature of the technologies and a number of similar books being produced by competitors we decided not to release an early acess edition which is a shame as the book would have benefited from others input.
Tip - Your work of art is a product
Summary
So good things for me:
Not so good things:
Conclusion
A good experience on the whole that was slightly jaded towards the end. Would I do it again? Hmm certainly not for a while and I would look at self publishing next time.
Thanks for reading.
The below image made me laugh - just 1.5 days after ebook released - a compliment of sorts and if more people read it and benefit all the better I guess (cheap skates!):
]]>Garbage Collection prior to .net 4
As you probably know the CLR allocates memory for your applications as they require it and assumes an infinite amount of memory is available (we wish). This is of course a mad assumption so a process called the Garbage collector (GC) is needed in order to clean up unused resources.
The GC keeps an eye on available memory resources and will perform a cleanup in 3 situations: a threshold is exceeded, the user specifically calls the garbage collector or a low system memory condition occurs.
To make this as efficient as possible the GC divides items to be collected into “generations”. When an item is first created it is considered a generation 0 item (gen 0) and if it survives subsequent collections (e.g. it is still in use) then it is promoted to a later generation - generation 1 and later generation 2.
This division allows the garbage collector to be more efficient in the removal and reallocation of memory. For example generation 0 items mainly consist of instance variables that can be quickly removed (freeing resources earlier) whilst the older generations contain objects such as global variables that will probably stick around for the life time of your application. On the whole the GC works very well and saves us writing lots of tedious clean up code to release memory.
The GC operates in a number of modes: Workstation, Concurrent workstation (default for multi-core machines) and Server. These modes are optimized for different scenarios. For example workstation is the default mode and optimized for ensuring your applications have a quick response time (important for UI based applications) whilst server mode is optimized for throughput of work (generally more important for server type applications). Server mode does however have the disadvantage that it pauses all other managed threads during a garbage collection. If Server mode was used for a Windows forms application this collection could manifest itself as intermittent pauses which would be very annoying.
Garbage Collection in .net 4
So what’s changed then?
Prior to .net 4 a Concurrent Workstation GC could do most but not all of a generation 0 and 1 collection at the same time as a generation 2 collection. The GC was also unable to start another collection when it was in the middle of a collection which meant that only memory in the current segment could be reallocated. In .net 4 however Concurrent Workstation GC collection is replaced by background garbage collection. The simple explanation (and GC gets very complex) is that background garbage collection allows another GC (gen 0amp;1) to start at the same time as an existing full GC (gen 0,1 and 2) is running reducing the time full garbage collections take. This means that resources are freed earlier and that a new memory segment could be created for allocation if the current segment is full up.
Background collection is not something you have to worry about – it just happens and will make your applications perform quicker and be more efficient so yet another good reason to upgrade your existing applications to .net 4. It is important to note that background collection is not available in Server mode GC although the CLR team has stated they are aiming to achieve this in the next version of the framework.
The GC team have also done work to ensure garbage collection works effectively on up to 128 core machines and improved GC ‘s efficiency reducing the time needed to suspend managed threads
For more information and a detailed interview with the GC team please refer to:
http://blogs.msdn.com/ukadc/archive/2009/10/13/background-and-foreground-gc-in-net-4.aspx
http://channel9.msdn.com/shows/Going+Deep/Maoni-Stephens-and-Andrew-Pardoe-CLR-4-Inside-Background-GC/
try
{
// do something that may fail
}
catch(System.exception e)
{
..
}
As we all know this is almost always a very naughty way to write code as all exceptions will be hidden. Hiding exceptions you don’t know about is rarely a good thing. Additionally there are some exceptions that should never be caught (even by lazy developers) such as low down beardy stuff like access violations and calls to illegal instructions. These exceptions are potentially so dangerous that you it’s best to just shut down the application as quick as possible to prevent further damage. So in .net 4 corrupted state exceptions will never be caught even if you specify a try catch block like above. However if you do want to enable the catching of corrupted state exceptions application wide (e.g. to route them to an error logging class) then you can add the following setting in your applications configuration file:
LegacyCorruptedStateExceptionsPolicy=true
This behavior can also be enabled on individual methods with the following attribute:
[HandleProcessCorruptedStateExceptions]
Early impressions are very promising and it is much much quicker than previous preview versions. Beta 2 also has a go live licence so feel free to use it to develop your applications. As per usual Microsoft have played around with release editions. VS2010 is available in Express, Professional, Premium and Ultimate editions (details to follow as I look into this). You will have to wait until March 22nd for the final release.
]]>DDD events are free to attend and were supported by Microsoft UK and sponsors such as Camtasia and DevExpress who provided a venue and refreshments.
In a DDD event the agenda is created by delegates - anyone can submit a conference session (as long as it is Microsoft or development focussed) but the actual agenda is then voted for by attendees. DDD events were very successful in the UK and the highlight of the conference calendar. Events were nearly always booked out with 200+ delegates.
I am currently looking to hold DeveloperDeveloperDeveloper Melbourne event some time in the future - watch this space!
Hello Code Contracts
To ensure values are not null you have probably written code similar to the following many times:
Public function myFunction(string input)
{
If(input==null)
{
throw new System.NullReferenceException(“Input cannot be null”);
}
}
Or perhaps you utilized the Trace/Assert statement:
Trace.Assert(input!=null)
Code contracts are superior to the above methods for the following reasons:
Let’s now create a simple code contract to ensure that an input value is not null or equal to five.
Create a new console application
Add the following using directive:
using System.Diagnostics.Contracts;
Now add the following code
static void Main(string[] args)
{
DoSomething(5);
}
public static void DoSomething(int? Input)
{
Contract.Assert(Input != null);
Contract.Assert(Input != 5)
}
Note how the code compiles but when run you will receive an error message.
Hang on don’t code contracts get validated at compile time?
Enabling code contract static verification (TFS edition only)
To enable static go into the project properties, select the code analysis tab then ensure that the “perform static contact checking” check box is checked. You may question why this option is not enabled by default. One possible reason is that if you are writing unit tests then you may want to pass null values into your methods and check your code handles them correctly. If static verification was always “on” then you could run your unit tests!
Architecture
Behind the scenes code contracts interacts and rewrites the generated IL of your application. At a high level we can divide code contract functionality into 3 main components:
Let’s now look at how we declare assumptions in our code using code contracts static methods.
Conditions
Code Contracts allows you to create 3 types of conditions:
Below I have listed some of the conditions you may want to utilize (this is by no means an exhaustive list):
Preconditions
Preconditions are a type of condition that must be true at the entry of a method for it to be executed.
Contract.Requires
Ensure the condition is true before the code is processed.
The following will ensure the input parameter is not null
Contract.Requires(input != null);
Contract.RequiresAlways
When an assumption is declared using the RequiresAlways method it will be verified even if code contract static checks are not set to run. The following ensures that the input parameter is not null.
Contract.RequiresAlways(input != null);
Contract.EndContractBlock
Contract.EndContractBlock statement tells the compiler to treat code as a precondition and allows you to utilize legacy code without converting it to code contracts format.
if (input==null) throw new System.NullReferenceException(“input is null”);
Contract.EndContractBlock();
Note you cannot use EndContractBlock in conjunction with any other preconditions.
Post conditions
Post conditions are conditions that are true at the exit of your method calls.
Contract.Ensures
Ensures a condition is true on exit of method:
Contract.Ensures(MyValue != 7);
Contract.EnsuresOnThrow
Use to ensure a specific exception type is thrown for a condition
Contract.EnsuresOnThrow
Contract.forall(cart, s=gt; s!=i))
Allows the iteration through a set to ensure all members meet a specific condition:
Contract.forall(MySet, i=gt; i!=null));
Object Invariants
Object invariants allow you to specify conditions that must always be true for an object and are created by decorating a procedure with the [ContractInvariantMethod] attribute. The following code ensures that the ImportantData variable can never be null:
[ContractInvariantMethod]
void MyInvariant() {
Contract.Invariant(ImportantData !=null);
}
Code contract Values
Code contracts offer some useful pseudo variables that can be useful when creating conditions.
Contract.Result
Contract.Result accesses a value in a condition that will be returned from a function without referring to it directly:
Contract.Ensures(Contract.Result
Contract.OldValue
Contract.OldValue represents the values state is at the start of the method call. OldValue performs a shallow copy of the specified variable and could be used to check if a value has changed:
CodeContract.Ensures(MyValue != CodeContract.OldValue(MyValue));
]]>Using System.Threading.Tasks;
One way to create a new Task is with the Task.Factory.StartNew method. This method accepts an Action delegate and immediately starts a task.
Task task1 = Task.Factory.StartNew(() =gt; StockService.CallSomeLongRunningService(Stocks[0]));
Another way you can start a task is to pass the code you want run into the Task’s constructor. The main difference here is that we have to explicitly start the Task when using this method. This could be useful for scenarios where you don’t want the task to start running straight away:
Task task2 = new Task(
delegate
{
StockService.CallSomeLongRunningService(Stocks[0]);
}
);
task1.Start();
Console.ReadKey();
Task.Wait amp; Task.WaitAll
Task.Wait and Task.WaitAll allow you to pause the flow of execution until the tasks you specify have completed. For example when running the above code you may find the main program exits before the StockService has completed its work and output the results to the screen.
Below shows an example of using the Wait method to ensure task1 has completed and the WaitAll method to ensure tasks2,3 and 4 have finished:
Task task1 = new Task(delegate { StockService.CallSomeLongRunningService(Stocks[0]);});
Task task2 = new Task(delegate { StockService.CallSomeLongRunningService(Stocks[1]); });
Task task3 = new Task(delegate { StockService.CallSomeLongRunningService(Stocks[2]); });
Task task4 = new Task(delegate { StockService.CallSomeLongRunningService(Stocks[3]); });
task1.Start();
task2.Start();
task3.Start();
task4.Start();
task1.Wait();
Task.WaitAll(task2, task3, task4);
Console.ReadKey();
Task.WaitAny
You can also wait for the results of any task to complete with Task.WaitAny – perhaps you would use this if many Tasks are retrieving the same data from different sources:
Task.WaitAny(task2, task3, task4);
IsCompleted
You can also check if a task is completed by querying the IsCompleted property. This will return a boolean value indicating if the task has completed its work.
while (task1.IsCompleted == false)
{
Console.WriteLine("Waiting on task 1");
}
ContinueWith
It is often necessary to specify work should be performed in a specific order . This can be declared in a fluent like manner with the ContinueWith method:
Task task3 = Task.Factory.StartNew(delegate{ StockService.CallSomeLongRunningService(Stocks[0]); })
.ContinueWith(delegate
{ StockService.CallSomeLongRunningService(Stocks[1]); })
.ContinueWith(delegate
{ StockService.CallSomeLongRunningService(Stocks[2]); });
Console.ReadKey();
Returning values from Tasks
You can retrieve a value that has been returned from a task by querying the result property:
var data = Task.Factory.StartNew(() =gt; StockService.CallSomeLongRunningService(Stocks[0])).Result;
Console.WriteLine("Parallel task returned with value of {0}",data);
Alternatively you can use one of the generic Task classes and again query the result property:
Tasklt;stringgt; t = new Tasklt;stringgt;(delegate{return doSomething();} );
t.Start();
Console.WriteLine("Parallel task returned with value of {0}", t.Result);
What happens if the Task does not yet have a result?
If you try and access the result if the task has completed its work then the value will be returned. If however the task has not completed its work then the code will block until the task has completed. As you can probably predict this could slow your application down as the CLR waits for the return value. To minimize slow down you probably want to run the task as soon possible before you need access to the actual value.
Any suggestions/requests welcome!
]]>These are all valid comments that I can learn from– apart from the demo one - if the CTP was worth showing I would have demoed it!
I think it’s probably impossible to please everyone. From the comments there were obviously some hard core devs who wanted much more detail – not sure this would have been so enjoyable or useful to everyone else. Maybe future session should make clear the level they are aimed at to avoid these disappointments.
Despite the suggestions I covered too much material too quickly many commented they liked the quick overview.
Lesson – you cannot please everyone!
These sort of comments can probably be minimized by writing a good session abstract.
In conclusion I will be doing a newer version of this presentation at DevEvening the end of Aug/very early Sep. The new presentation will be very much demo based now the Beta is here (maybe beta 2 by then?) and I will be limiting Power Point to the minimum. I think I will also pick fewer areas and go into more detail.
Overall very happy with feedback.
For me the best presentation of the day was given by Sebastian Lambla. Seb is a very entertaining presenter and was discussing MVC best practices. Unfortunatly the demo gods were not with him :O Near the beginning of his talk he suffered a BSOD mid presentation. His machine wouldnt turn on and he then had some weird issue where ASP.net could not find Castle IOC assemblies. If that wasnt enough R# was then causing issues. However Seb managed to recover from this very well and I think the audience probably went away more impressed because of it.
I learnt a number of lessons from the conference talks:
I look forward to Microsoft releasing a newer CTP and being able to go into more detail. At present I have a load of information and documentation on the various upcoming changes but cant play around with it until have a working version. All in all an enjoyable day and thanks to all the organisers
My special badge given to me by Barry "Sock" Dorrans after proper one read Alax Mackey
]]>
]]>Okay let's get started.
First if you havent already you will need to install the Oslo preview from:
http://www.microsoft.com/downloads/details.aspx?FamilyID=f2f4544c-626c-44a3-8866-b2a9fe078956amp;displaylang=en
Once this is installed it will install an application called Intellipad Intellipad is an editor for working with M languages
Open Intellipad
As not everything is implmented yet you will need to manually create a new file called PokerHand.mg (mg is the extension for MGrammar language files)
Open up Intellipad (Samples enabled)
Change the mode we are working in. To do this click the top right corner where it says Standard Mode click and change the mode to MGrammarMode. This will change the menus available to you on the main bar.
Click the MGrammar menu on the menu bar and select Tree Preview
An open file dialogue will appear (it wont be like this in final release) select the PokerHand.mg file you created earlier
In the centre pane (this is where we define our Grammar) enter the following to create our grammar:
/*
Author: Alex Mackey
Web: www.simpleisbest.co.uk
Description: Simple MGrammar to hold poker deck
*/
module SimpleIsBest
{
language CardDeck
{
syntax Deck = "Deck";
//Card values 1-9 Jack, Queen, King, Ace
token Value = "1".."9"
|"10"
|"J"
|"Q"
|"K"
|"A";
//Card suit Hearts, Club, Diamond, Spades
token Suit = "H"
|"C"
|"D"
|"S";
//A card is made up of value + suit
token Card= Value + Suit;
syntax PokerHand = Deck Card Card Card Card Card;
//Change how results are displayed (or projected official term)
syntax Main = ph:PokerHand+ =gt; [ph];
// Ignore whitespace
syntax LF = "\u000A";
syntax CR = "\u000D";
syntax Space = "\u0020";
interleave Whitespace = LF | CR | Space;
}
}
I think most of thats pretty readable. The only tricky bits are:
syntax Main = ph:PokerHand+ =gt; [ph]; - this changes how the data is displayed or projected
interleave Whitespace = LF | CR | Space; - this just means ignore the whitespace
In the left hand pane (where we put our test data) enter the following test data:
Deck KC 3C 5H 2H 2H
Deck KH 3C 5H 2H 2C
In the right hand section you should see how M has transformed our input data.
In the next post we will look at how to actually use our DSL within Visual Studio with aid of the DynamicCompiler class.
]]>How do GA’s work?
Glad you asked - let’s take the example of task scheduling. We have a number of different task items and want to know what is the best order to complete them so we can generate the highest profit as soon as possible.
To do this we will use a simple function (known as a fitness function) that return a numeric value for an inputted task set. The value will be calculated by totalling the billable amount of the first two schedule items in a set. In reality the fitness function would be more complex and take into account factors such as task length, priority, resource usage etc but you get the idea.
We will setup an initial list of task items and then generate eight new lists of tasks by swapping two items around (there are a number of ways to do this but I think this is the simplest). We will then use the task set with the highest fitness as the basis to generate our next generation. This process will carry on for a number of iterations (called epochs) hopefully the best solution should then be found as the best is used from each generation. GA’s require many iterations and can be quite slow however the more epochs you perform the better your solution is likely to be.
Below is a simple example I knocked up in C#. The highest fitness value that can be returned is 4800 (3200 + 1600). Obviously in this example it is simple to work out the best solution as there are only a few task but imagine if you had thousands of tasks and a more complex fitness function and you can see how GA’s can be useful. Try changing the epoch number to 100 and notice how you need many epochs (around 10,000 for this example) to consistently get the best order. The number of epochs needed could be drastically improved by randomizing a set in the initial population and then choosing the fittest.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GAScheduling
{
class Program
{
public static int Epochs = 10000;
public static double MutationPossibility = 0.1;
static void Main(string[] args)
{
int CurrentEpoch = 0;
Listlt;TaskItemgt; Tasks = new Listlt;TaskItemgt;();
Listlt;TaskItemgt; BestGeneration = new Listlt;TaskItemgt;();
//Setup new tasks
Tasks.Add(new TaskItem { ID = 1, BillableAmount = 100 });
Tasks.Add(new TaskItem { ID = 2, BillableAmount = 200 });
Tasks.Add(new TaskItem { ID = 3, BillableAmount = 400 });
Tasks.Add(new TaskItem { ID = 4, BillableAmount = 800 });
Tasks.Add(new TaskItem { ID = 5, BillableAmount = 1600 });
Tasks.Add(new TaskItem { ID = 6, BillableAmount = 3200 });
BestGeneration = new Listlt;TaskItemgt;(Tasks);
Listlt;TaskItemgt; NewTasks;
while (CurrentEpoch != Epochs)
{
NewTasks = CreateNewGeneration(BestGeneration);
//Is this generation better than last if so use it in next cross over
if (CalculateFitness(NewTasks) gt; CalculateFitness(BestGeneration))
{
BestGeneration = NewTasks;
}
CurrentEpoch++;
}
Console.WriteLine("Best fitness: " + CalculateFitness(BestGeneration).ToString() + "\n");
//Show items
Console.WriteLine("Order:");
foreach (TaskItem TaskItem in BestGeneration)
{
Console.WriteLine(TaskItem.ID.ToString() + " (" + TaskItem.BillableAmount + ")");
}
Console.ReadKey();
}
public static Listlt;TaskItemgt; CreateNewGeneration(Listlt;TaskItemgt; InputTasks)
{
int PopulationCount = 7;
int CurrentPopulationIndex = 0;
Listlt;TaskItemgt; BestGeneration = new Listlt;TaskItemgt;();
decimal HighestRating = 0;
//Generate new populations
while (CurrentPopulationIndex != PopulationCount)
{
Listlt;TaskItemgt; NewGeneration = Randomize(new Listlt;TaskItemgt;(InputTasks));
decimal FitnessRating = CalculateFitness(NewGeneration);
//Is this new generation better than the old population?
if (FitnessRating gt; HighestRating)
{
HighestRating = FitnessRating;
BestGeneration = NewGeneration;
}
CurrentPopulationIndex++;
}
//Return best generation
return BestGeneration;
}
//Swaps a task item around
public static Listlt;TaskItemgt; Randomize(Listlt;TaskItemgt; InputTasks)
{
Random Random=new Random();
Listlt;TaskItemgt; TmpTasks = new Listlt;TaskItemgt;(InputTasks);
//Get two random numbers making sure second is not same as first
int Index1 = Random.Next(0, TmpTasks.Count);
int Index2=0;
do
{
Index2 = Random.Next(0, TmpTasks.Count);
}
while (Index2 == Index1);
//Swap items around
TaskItem Item1 = TmpTasks[Index1];
TaskItem Item2 = TmpTasks[Index2];
TmpTasks[Index1] = Item2;
TmpTasks[Index2] = Item1;
//Check for mutation
if (Random.NextDouble() lt; MutationPossibility)
{
//Mutation is sometimes introduced to stop generations stagnating
}
return TmpTasks;
}
//Fitness function calculated by totaling billable cost of first two iterations
public static decimal CalculateFitness(Listlt;TaskItemgt; InputSchedule)
{
int Count = 0;
decimal RevenueValue = 0;
while(Count!=2)
{
RevenueValue += InputSchedule[Count].BillableAmount;
Count++;
}
return RevenueValue;
}
}
public class TaskItem
{
public int ID = 0;
public decimal BillableAmount = 0;
}
}
Disadvantages
However the disadvantages are equally numerous:
In addition to these issues are you going to store your data?
At the time of writing Azure provides facilities for storing and accessing data in a RESTful manner through the use of blobs, queues, table storage. In addition to the mentioned Azure storage methods there is also SQL data services that provides “advanced functionality” such as concurrency and richer querying. Annoyingly SQL data services is nothing like either:
A) SQL server
B) ADO.net data services/Astoria
You could argue that SQL server is not going to scale as well as a REST solution (and it probably wont) but SQL server seems to be working pretty well for many existing customers. So.. currently if you want to use Azure you will probably need to rewrite your data layer of the application (oh and make sure you are not using LINQ to SQL but EF). Fantastic.
One of Azure’s most touted benefits is its scalability - create a start-up with zero investment and then scale it out as needed. I am not sure that hosting was the major obstacle for most start-ups, a sustainable business plan was perhaps a bigger issue?
What I like..
Summary
Maybe I am being too negative about Windows Azure/cloud computing and we are not yet at a version one release but for me the current benefits seem mostly confined to high traffic applications and then you will need to rewrite your data layer. In my opinion to achieve main stream adoption Azure needs to offer developers an easy way to store relational data such as SQL server.
]]>
To work with Azure storage currently you have 2 options:
• Make a request to the REST API directly
• Utilize StorageClient wrapper classes to access the REST API
So as you can see the choice is ultimatly REST API or er REST API!
StorageClient
To ease working with the REST API in the Azure SDK samples is a wrapper class called StorageClient. StorageClient is great for putting together test applications and understanding how Azure Storage works but Microsoft dont advise you to use it for live applications.
Lets REST for a minute
If you are not familiar with REST, REST stands for Representational State Transfer and is a style of architecture introduced by a guy named Roy Fielding (one of the main authors of http protocol).
You can read more about what Roy proposed at: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
Applications implementing Roy’s proposed architecture are sometimes described as RESTful.
I don’t want to get into a debate about what exactly constitutes a RESTful system (some people feel scarily passionate about this) so the important points to note for our purposes are that:
• There is no state in REST applications
• Everything is abstracted into a resource which is accessible by a unique address
This might not seem a big deal but these characteristics are essential for cloud based applications. These features allow inter platform operability, easy integration and allow us to easily scale out our applications by taking advantage of features aimed for website performance such as caching and load balancing. There is no difference at an http level from a request to Azure storage to a web page request.
Using REST API directly
I wanted to understand what StorageClient was doing behind the scenes with the REST API so I put together the following code (with help from David Lemphers article at: http://blogs.msdn.com/davidlem/archive/2008/12/20/windows-azure-storage-exploring-blobs.aspx) to list the containers present in the system.
Overview of how we access Azure Storage Rest API
1. A request is made to a URL and port. The following URL for example is used to retrieve a list of containers held in Azure Storage:
http://127.0.0.1:10000/devstoreaccount1/devstoreaccount1?comp=list
2. We then set a number of headers in the request
3. We set the http verb of the request to describe what we are doing e.g. GET, PUT etc
4. Calculate a hash of the headers and a hidden key so no one can modify the request and Azure Storage can authenticate us
5. Azure Storage will then give us our results back as XML
Okay let's create our test application now.
Example Application
Create a new console application
Add the following using statement:
using System.Net;
Enter the following code
static void Main(string[] args)
{
//Gets a list of containers
string AccountName = "devstoreaccount1";
string AccountSharedKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==";
string Address = "http://127.0.0.1";
string Port = "10000";
//Action to perform e.g. ?comp=list
string QueryString = "?comp=list";
string uri = Address + ":" + Port + "/" + AccountName + QueryString;
string MessageSignature = "";
//Build Request
HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(uri);
Request.Method = "GET";
Request.ContentLength = 0;
Request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R"));
//Create signaure of message contents
MessageSignature += "GET\n"; //Verb
MessageSignature += "\n"; //MD5 (not used)
MessageSignature += "\n"; //Content-Type
MessageSignature += "\n"; //Date optional if using x-ms-date header
MessageSignature += "x-ms-date:" + Request.Headers["x-ms-date"] + "\n"; //Date
MessageSignature += "/" + AccountName + "/" + AccountName + QueryString; //resource
//Encode signature using HMAC-SHA256
byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(MessageSignature);
System.Security.Cryptography.HMACSHA256 SHA256 = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(AccountSharedKey));
// Now build the Authorization header
String AuthorizationHeader = "SharedKey " + AccountName + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));
// And add the Authorization header to the request
Request.Headers.Add("Authorization", AuthorizationHeader);
//Get response
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
using (System.IO.StreamReader sr = new System.IO.StreamReader(Response.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
Ensure Azure Storage is running
Press F5 to run your application
The application should then list all the containers in your application in an XML format:
For futher information on the REST API consult the SDK documentation at: C:\Program Files\Windows Azure SDK\v1.0\doc\ServiceHostingSDK
A classic example of code that would benefit from being run in parallel is code that iterates through stock quotes and performs a long running calculation on each quote. As each individual calculation is independent from the others it can be run in parallel so the overall task is completed quicker.
Some people like to refer to problems such as above as embarrassingly parallel in that they are very suited for the benefits of parallelization.
Crap Code running in parallel is just Parallelized crap code!
Before trying to speed up any code by parallelizing it, check that you cannot optimize it any further. Crap code running in parallel is still just parallelized crap code and is still likely to be quite slow! Done that? Okay you are ready to look at the Parallel Enhancements.
The parallel extensions and enhancements can be divided into 5 areas:
To learn about the extensions I suggest you download the Visual Studio 2010 CTP and check out the following websites:
http://blogs.msdn.com/pfxteam/
http://www.danielmoth.com/Blog/
http://channel9.msdn.com/pdc2008/TL26/
Pretty cool eh?
For more information Wikipedia as usual is our friend:
http://en.wikipedia.org/wiki/Genetic_algorithm
Currently .net and to some degree SQL services are available.
To play around with Azure you need to register so sign up at: http://www.microsoft.com/azure/register.mspx.
Microsoft will then send you a key (mine took about a week to arrive) allowing you to access the online facilities.
Until you get this key you can still play around to an extentby downloading the SDK: http://www.microsoft.com/downloads/details.aspx?FamilyId=BB893FB0-AD04-4FE8-BB04-0C5E4278D3E9amp;displaylang=en.
I suggest you also download the tools for visual studio from http://www.microsoft.com/downloads/details.aspx?FamilyId=63D0D248-1B08-4F7D-ABDE-62EB75CB1E69amp;displaylang=en. As this is beta software you probably want to be running it in virtual pc (although I didnt and everything seems fine still).
The first thing you should do is watch Steve Marx's presentation on developing an application in Azure at: http://channel9.msdn.com/pdc2008/ES01/
Steve is an excellent preseter, great to watch and will take you through the basics of Windows Azure.
After installing the Visual Studio tools you can create Web Cloud service ASP.net projects. Cloud projects are very similar to standard ASP.net projects but contain another project that has some additional files that describe where the service is hosted and configuration settings (.csdef and .cscfg).
If you look at the project name in Visual Studio you will see it is called something like CloudService1_webRole. Role is a term within Azure that seems to describe the type of service you are running. If you right click on the service project you can deploy it to the cloud (which they havent given me access to yet).
As it would be inconvenient to deploy your app every time you wanted to test it Microsoft provide an application called the development fabric which simulates how it will function in the cloud (below). If you open the cscfg in studio you will see its an XML file that contains the following:
lt;?xml version="1.0"?gt;
lt;ServiceConfiguration serviceName="CloudService3" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"gt;
lt;Role name="WebRole"gt;
lt;Instances count="1"/gt;
lt;ConfigurationSettingsgt;
lt;/ConfigurationSettingsgt;
lt;/Rolegt;
lt;/ServiceConfigurationgt;
If you alter the instances count element and run the app you will see more instances created in development fabric. This simulates adding capacity to your Azure application e.g. if you are expecting many visitors to hit the site.
Once you have your key and have activated it you can log into the Azure services platform. This will take you to an interface like the screen shot below. At present its a bit rough around the edges but you can see the direction they are going.
Currently within .net services you have access to 3 components:
The examples provided in the SDK take you through the basics of how these work. There is an example of a chat application that sends messages via the service broker. What is impressive is the speed of it, no noticable delay at all. There is also another example application to demonstrate the security features )(a calculator app). This threw an security exception when I tried to run it about token being valid 10 seconds after it was requested?!
Security is defined by an input claim e.g. a specific username which is then matched to Output claims (e.g. in the included example give the ability to multiply).
Some of the examples are a bit cryptic at present and I would suggest brush up on your WCF and Workflow as these concepts will certainly be used.
It all looks really promising so far and I cant wait to learn more about it.
Having said this it does look interesting from the point of view of:
DataContext objCon = new DataContext(System.Configuration.ConfigurationSettings.AppSettings.Get("ConnStr"));
Tablelt;BlogEntryCommentgt; objBlogEntryCommentTable = objCon.GetTablelt;BlogEntryCommentgt;();
var query = from b in objBlogEntryCommentTable
orderby b.CommentDate
where b.BlogEntryID ==BlogEntryID
select b;
return query.ToList();
Perhaps the best option if you just want a single value back is to use a format called JSON in conjuction with JQuery.
JSON stands for Javascript object notation and is a very lightweight format to return a simple object. For example a stock quote result might look something like this:
{Symbol:"MSFT",Value:"4.4"}
I think we can all agree thats a lot less data than your average SOAP call and its pretty readable making JSON less heavy on bandwidth and probably quicker to process than XML (needs confirming!). Libraries such as JQuery understand JSON is an object which makes it very easy to work with e.g:
alert(objMyResult.Value);
Which is much preferable to processing XML from SOAP results etc...
But how do you use this with ASP.net?
Currently ASP.net and JSON support is pretty ropey (however nothing to stop you returning JSON formatted strings). In the MVC framework there is some nice inbuilt functionality for dealing with JSON posts in controllers. I decided to add the ability for users to comment on my blog posts and decided to implement this with MVC. The client side code is below and can be seen in action by commenting on any of the blog posts. Note you will need JQuery to use this code and currently the Json result class is only included in MVC projects (System.Web.MVC).
Client side code:
function submit()
{
nbsp;
var strName = $("#txtName").val(); $.ajax({
var strEmail = $("#txtEmail").val();
var strComment = $("#txtComment").val();
var strSpamCheck = $("#txtSpamCheck").val();
var rand1=window.rand1;
var rand2=window.rand2;
type:
nbsp;
"POST", });
dataType: "json",
url: "lt;%=Application["URLRoot"].ToString() + "BlogEntryComment/Submit?id=" + objBlogEntry.BlogEntryID.ToString() %gt;",
data: { Email: strEmail, Name: strName, Comment: strComment, SpamCheck: strSpamCheck, Rand1: rand1, Rand2: rand2},
success: function(result) {
$("#CommentEntry").fadeOut("slow");
setTimeout(redirect,2000);
},
error: function(error) {
alert('error ');
}
}
nbsp;
Then server side I use this code in my controller class for processing BlogEntryComments:
public JsonResult Submit(string Email, string Name, string Comment, int SpamCheck, int Rand1, int Rand2)
{
if (SpamCheck != (Rand1 + Rand2))
{
return Json(new { message = "SPAM" });
}
if (Comment == "")
{
return Json(new { message = "SUCCESS" });
}
if ("" + Name.Trim() == "")
{
Name = "Anon";
}
DataContext objCon = new DataContext(System.Configuration.ConfigurationSettings.AppSettings.Get("ConnStr"));
Tablelt;BlogEntryCommentgt; objBlogEntryCommentTable = objCon.GetTablelt;BlogEntryCommentgt;();
BlogEntryComment objBlogEntryComment = new BlogEntryComment();
objBlogEntryComment.IP = System.Web.HttpContext.Current.Request.UserHostAddress.ToString();
objBlogEntryComment.BlogEntryID=Convert.ToInt32(Request.QueryString["id"]);
objBlogEntryComment.CommentDate = System.DateTime.Now;
objBlogEntryComment.Name = "" + Name;
objBlogEntryComment.Email = "" + Email;
objBlogEntryComment.Comment = "" + Comment;
objBlogEntryComment.Approved = 0;
objBlogEntryCommentTable.InsertOnSubmit(objBlogEntryComment);
objCon.SubmitChanges();
return Json(new { message = "SUCCESS" });
}
If you want to adapt this for you own use couple of things to note:
]]>
let a=1 let b=(a+a) let c=(a+b*2)
http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx
]]>A number of things come to mind:
It doesnt take too much imagination to see the problems with the above. The bozos who designed this system would do well to read a book called Dont Make me think by Steve Krug (http://www.amazon.co.uk/Dont-Make-Think-Usability-Circle-Com/dp/0789723107/ref=sr_1_2?ie=UTF8amp;s=booksamp;qid=1224192586amp;sr=8-2)
Steve considers when people make decisions they make not necessairly the smartest but the easiest decision possible (with no problems).
This has implications for user interface design the ideal being the user should make the decisions without having to think about them. I think you can see this with a well designed site like Amazon or StackOverflow where you just feel drawn to the right button etc. You can help or hinder this process by adhearing to well known standards and ui elements.
After covering basic concepts and web standards Steve takes a number of websites, shows the current design and alters them (some times very slightly to improve the usability). Every developer should be made to read this book. It took me about 2-3 hours to read cover from cover and it was an entertaining read. Every developer should read this book.
Belows the code I used to convert an imagr to greyscale. I have commented out brightness adjustment (just add to each value) and some other stuff I was playing with.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
public class Imaging
{
public string ExportDir = "";
public string ModifyImageProperties(string Mode, string FilePath, int RedModify, int GreenModify, int BlueModify, int Lighten, int Darken)
{
int intStride = 0;
int intBrightness = -150;
System.IntPtr Scan0;
Bitmap objBitmap = new Bitmap(FilePath);
string strNewFileName = "" + Guid.NewGuid().ToString() + ".jpg";
BitmapData objBitmapData = objBitmap.LockBits(new Rectangle(0, 0, objBitmap.Width, objBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
//For 24 bit formats (RGB) stride=imageWidth * 3 (note if this isnt a number divisible by 4 an offset will be added to make it so)
//For 32 bit formats (RGB) stride=imageWidth * 4
intStride = objBitmapData.Stride;
Scan0 = objBitmapData.Scan0;
unsafe
{
//Pointer to start of image
byte* p = (byte*)Scan0;
//Calculate offset
int nOffset = intStride - (objBitmap.Width * 3);
int nWidth = (objBitmap.Width * 3);
int intRed = 0;
int intGreen = 0;
int intBlue = 0;
for (int y = 0; y lt; objBitmap.Height; ++y)
{
for (int x = 0; x lt; objBitmap.Width; ++x)
{
intRed =p[2];
intGreen =p[1];
intBlue = p[0];
if (Mode == "RGB")
{
intRed = intRed + RedModify;
intGreen = intGreen + GreenModify;
intBlue = intBlue + BlueModify;
}
if(Mode=="INVERT")
{
intRed = 255 - p[2];
intGreen = 255 - p[1];
intBlue = 255 - p[0];
}
if (Mode == "GREY")
{
intRed = (byte) (.299 * intRed + .587 * intGreen + .114 * intRed);
intGreen = (byte) (.299 * intRed + .587 * intGreen + .114 * intRed);
intBlue = (byte)(.299 * intRed + .587 * intGreen + .114 * intRed);
}
if (Lighten gt; 0)
{
intRed = intRed + Lighten;
intGreen = intGreen + Lighten;
intBlue = intBlue + Lighten;
}
if (Darken gt; 0)
{
intRed = intRed - Darken;
intGreen = intGreen - Darken;
intBlue = intBlue - Darken;
}
if (intRedgt; 255) intRed = 255;
if (intGreen gt; 255) intGreen = 255;
if (intBlue gt; 255) intBlue = 255;
if (intRed lt; 0) intRed = 0;
if (intGreen lt; 0) intGreen = 0;
if (intBlue lt; 0) intBlue = 0;
p[2] = (byte) intRed;
p[1] = (byte) intGreen;
p[0] = (byte) intBlue;
//++p;
p += 3;
}
p += nOffset;
}
objBitmap.Save(ExportDir + strNewFileName, ImageFormat.Jpeg);
objBitmap.UnlockBits(objBitmapData);
return strNewFileName;
}
}
}
I found a few links which helped me put this together the codeproject was very helpful (although not the most readable):
http://www.bobpowell.net/lockingbits.htm
http://www2.sys-con.com/ITSG/virtualcd/Dotnet/archives/0104/brown/index.html
http://www.codeproject.com/KB/GDI-plus/csharpgraphicfilters11.aspx
In relation to standard ASP.net
MVC doesnt make use of standard view state so some scenerios may be more difficult than classic ASP.net. The application uses the url and http verbs to map to the views e.g /products/GetList is automatically mapped to GetList view
The main advantage of using MVC are that:
After the MVC session we watched a talk on optimizing ASP.net performance from the front end.
The main conclusions were:
The other session I atteneded was given by Mike Taulty on how Silverlight can interact with the page.
This was very impressive:
After meeting up with Howard just outside the exhibition hall the day began with an excellent key note speech given by Bill Buxton ( usability and industrial design expert) Bill has written an interesting looking book called Sketching user experiences which I purchased.
Bill argued that in many places the design phase occurs after the product development and that it was a mistake to let non experts be too involved in design (e.g. the FD on a project being involved to the level of screen design). He argued that good design was dependent on many aspects citing Apples Ipod. Prior to this Apple had been in decline. At this time a number of key personnel Jonathan Ive had been at Apple some time but the Ipod wouldnt become a success until a combination of events such as:
After this we attnded 2 sessions by Scott Gu on Silverlight. I have spent some time with Silverlight lately and would highly recommend the video tutorials. Scott said that Silverlight 2 was due to be released shortly (somewhat non committal!). Other items that looked interesting were IE 8 which includes a javascript profiler and useful looking development tools, Visual studio intellisense support for javascript frameworks such as prototype, about 50 new silverlight controls including graphing components coming.
We then saw a session on Sql data services (astoria). Astoria is basically a REST api to query sql server. I am not sure what I would use this for but it may be useful for example in a silverlight situation to avoid writing a web service interface for every crud query.
The final session was on Visual Studio IDE tips given by Sara Ford. This was very interesting and contained several time saving tips. I suggest you look at her blog which has a tip a day http://blogs.msdn.com/saraford/default.aspx
After we left this session I managed to talk to Scott Gu. One of the great things about Remix was how accessible all the presenters were. To have the chance to talk to Microsoft's VP was pretty cool.

I asked Scott about whether we should be using Web sites or Web application projects (a contentious issue in our company). Scott suggested web application projects where the dll is built is the better way to go. This was due to better performance and the ability to produce unit tests as a dll is built.
After the main sessions I had a few beers with Howard and had a chance to look at Microsoft Surface. There was an excellent demonstration given which had a virtual earth map. You could rotate it at any angle and even zoom into and walk inside buildings. At $13000 per unit they dont come cheap through.
I am looking forward to the MVC session tomorrow (finding out what exactly it is!)
So always practice safe threading or refrain..
]]>
Public Class Ben
Public Sub AddTwoNumbers()
Assert.AreEqual(1 + 1, 2)
End Sub
Public Sub MakeTea()
Throw new system.exception("Ben doesnt make tea")
End Sub
End Class
lt;TestFixture()gt; _
Public Class Ben
lt; test()gt; _
Public Sub AddTwoNumbers()
Assert.AreEqual(1 + 1, 2)
End Sub
lt;test()gt; _
Public Sub MakeTea()
Throw new System.Exception(“Ben doesn’t make tea”)
End Sub
End Class
lt;test()gt;_
Public Sub IsGoogleWorking()
Dim objIE As New IE("http://www.google.com")
objIE.TextField(Find.ByName("q")).TypeText("Hicom")
objIE.Button(Find.ByName("btnG")).Click()
Assert.IsTrue(objIE.ContainsText("Hicom"))
End Sub

But the real killer is that when you change pages the entire screen flashes which is really irritating. Why with all the effort that has gone into the rest of it would you do this.
Nice try Sony but I dont think its there yet...
On the whole not a bad book and if you think you need to wise up to some of the non technical issues well worth a read.
]]>But why would you want to do this?
Perhaps the only problem with CruiseControl.net is the documentation which you are going to have to do a bit of searching around. However CruiseControl.net is a popular application so there are quite a few tutorials.
CruiseControl.net has 2 parts the application itself and a web front end. The web front end is okay however you can modify various bits yourself through XSL files.
Using CruiseControl.net
1) Download NUnit from: http://sourceforge.net/project/downloading.php?groupname=nunitamp;filename=NUnit-2.4.8-net-2.0.msiamp;use_mirror=osdn (not strictly necessary but this tutorial will be integrating NUnit tests in the build)
2) Download CruiseControl.net from: http://sourceforge.net/project/showfiles.php?group_id=71179amp;package_id=83198
3) Check you have IIS amp; .net 3.5 installed
4) Install NUnit amp; CruiseControl.net
5) This will create a short cut on your desktop click this to run it you should see a dos window with a load of messages similar to this:
Create Project to build
Now what we need to do is create a sample project for CruiseControl to build.
I have created a new blank solution called cctestapp and added a console application to it. My solution file is at E:\wwwroot\Testing\cctestapp\cctestapp.sln and the application is at E:\wwwroot\Testing\cctestapp\cctestapp\.
Once you have created your console application add a reference to Nunit.framework.dll (by default this is at: C:\Program Files\NUnit 2.4.8\bin)
Add the following code to your console application:
using System;
using NUnit.Framework;
namespace MonitoringApplication
{
[TestFixture]
public class Program
{
[Test]
public void AlexTest()
{
Assert.AreEqual(1, 1);
}
public static int Main(string[] args)
{
//My program
return 0;
}
}
}
Check the application compiles okay.
Now we need to tell CruiseControl.net we want to build this project. To do this we need to alter an xml configuration file. This XML configuration file contains all the projects that are to be built. The configuration file contains a reference to a program called MsBuild. When you compile a project in visual studio behind the scences MsBuild is used to create the final output.
1) Open ccnet.config in notepad (by default its at C:\Program Files\CruiseControl.NET\server).
2) Modify it so it looks like this config file. This config file automates a build on Mondays and Wednesdays at 18:00 and runs NUnit tests.
3) Remember to alter the various paths to where you have created your project. I think these are fairly self explanatory. e.g assembly, executable, working directory, project file and logger.
4) If you now open up a web browser and go to http://localhost/ccnet/ you should see the main build screen like below:
5) Click the Force button to run the build.
6) You can then click refresh status to see if it built correctly if it did under the build status it should say Success.
7) To look at more details about whether your project built properly click the project name you can then view the build report and see the results of any tests.
8) If the project didnt build properly check your file paths are correct in ccnet.config.
You will probably want to install the CruiseControl tray application this notifies you of failures and allows you to kick of builds etc. This you can install by opening the web application and clicking the download CCTray link on the left.
Further reading
These tutorials helped me to get this running:
http://johnnycoder.com/blog/2008/01/29/getting-started-with-cruisecontrolnet/
http://weblogs.asp.net/jdanforth/pages/How-to-Hook-Up-a-VS.NET-2005-Solution-With-CruiseControl.NET-in-a-Few-Minutes.aspx
