Archive

Posts Tagged ‘.NET’

Microsoft Visual Studio 2010 Release Candidate

February 12th, 2010 No comments

It seems every year life just keeps getting busier ūüôĀ Anyway, here’s a bit good of news, the Visual Studio 2010 Release Candidate is available for download now. You can also get one chunky ISO if that tickles your fancy.

Compared to Beta 2, its a smooth and quite enjoyable experience and I’m very much waiting for the final. The performance of this release is insanely good and finally fixes some annoying performance issues we noticed in WPF in Beta 2 (lets forget Beta 1).

Don’t forget to try some of the cooler features of .NET 4.0 too.

{lang: 'en-GB'}
Share

Some changes in .NET BCL 4.0

November 21st, 2009 1 comment

I’ve been porting a few products to .NET 4.0 and came across some cool new additions in .NET 4.0 which will be quite useful for developers.

Strings

Streams

Remember writing this before to copy one stream to another?

public static void CopyTo(this Stream input, Stream output)
{
byte[] buffer = new byte[2048];
while (true)
{
int read = input.Read (buffer, 0, buffer.Length);
if (read <= 0)
return;
output.Write (buffer, 0, read);
}
}

Now you don’t need to, just use the Stream.CopyTo() method.

inputStream.CopyTo(output);

Checking for 64bit-ness

Previously to detect a 64bit operating system you would either P/Invoke out and call the IsWow64Process in Kernel32, looked at the “PROCESSOR_ARCHITECTURE” environment variable or even easier (and completely managed code) way of checking the size of a Pointer.

public static bool IsWin64
{
return (IntPtr.Size == 8);
}
public static bool IsWin32
{
return (IntPtr.Size == 4);
}

Now you can simply use the Environment class that comes with two new properties.

WPF 4.0 Improvements

There are simply too many to list, see the article on ScottGu‘s blog about WPF4 and VS2010/.NET 4.0.

One very important tweak are the Text Rendering improvements that TextBlock‘s now have a new TextOptions.TextFormattingMode that greatly improves the quality of text rendering.

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<TextBox TextOptions.TextFormattingMode="Ideal" FontSize="11">ThushanFernando.com - Ideal</TextBox>
<TextBox TextOptions.TextFormattingMode="Display" FontSize="11">ThushanFernando.com - Display</TextBox>
<TextBox TextOptions.TextFormattingMode="Ideal" FontSize="16">ThushanFernando.com - Ideal</TextBox>
<TextBox TextOptions.TextFormattingMode="Display" FontSize="16">ThushanFernando.com - Display</TextBox>
</StackPanel>
</Grid>
</Window>

Here’s a pretty picture showing the difference between using Ideal and Display. The difference is noticable for text sizes below 15.

MainWindowAlternatively you can place it in the Window so all child controls will render nicely.

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow - Display" Height="350" Width="525"
TextOptions.TextFormattingMode="Display">
<Grid>
<StackPanel xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<TextBox FontSize="11">ThushanFernando.com</TextBox>
<TextBox FontSize="16">ThushanFernando.com</TextBox>
</StackPanel>
</Grid>
</Window>

There are LOTS more coming in .NET 4.0 that will make anyone doing .NET development today just wet their pants over, just read the article on MSDN by Justin Van Patten about Whats new in the BCL in .NET 4.0 and also posted on the BCL team blog.

{lang: 'en-GB'}
Share

QuickFix: jQuery $.getJSON() fails in IE6 & IE7

October 27th, 2009 15 comments

Had a nasty issue with jQuery + jSON + IEx just now – still at work because of it!

This bit of code works perfectly fine on Firefox and Chrome:

function onUnitsModified() {
            $.getJSON("<%=Url.Action("GetTotalUnitCount", "ProjectReaper")%>", null, function(result) {
                if(result > 0)
                  // Do stuffs here
                }
            });
            return true;
}

But in IE we’ve come to realise that the first hit is successful, future json requests ones are not hitting the ASP.NET MVC actions (I put a breakpoint). You could append a time stamp to get rid of this annoying caching bug, but alternatively you can use the ajaxSetup options to disable caching.

function onUnitsModified() {
            $.ajaxSetup ({ cache: false}); 
            $.getJSON("<%=Url.Action("GetTotalUnitCount", "ProjectReaper")%>", null, function(result) {
                if(result > 0)
                  // Do stuffs here
                }
            });
            return true;
}

Darnit! Hope someone else doesn’t waste their time trying to fix this now ūüôā

{lang: 'en-GB'}
Share

Visual Studio 2010 Beta 2 is out!

October 21st, 2009 No comments

Microsoft has just released VisualStudio 2010 Beta 2 to MSDN Subscribers – aka Rosario.

msn_visual_studio_2010

I’m not sure why they’re going with the ULTIMATE moniker for Visual Studio, I still prefer the VS6 style Standard, Professional, Enterprise. Meh.

  • Microsoft Visual Studio 2010 Ultimate with MSDN
    The comprehensive suite of application lifecycle management tools for software teams to ensure quality results from design to deployment.
  • Microsoft Visual Studio 2010 Premium with MSDN
    A complete toolset for developers to deliver scalable, high quality applications.
  • Microsoft Visual Studio 2010 Professional with MSDN
    The essential tool for professional development tasks to assist developers in implementing their ideas easily. (Note: Visual Studio 2010 Professional will also be available without MSDN subscription)

Some of the more exciting things that are coming with Visual Studio 2010 are documented on MSDN or a better one would be Vikas Goyal’s post and also his .NET 4.0 coverage.. Personally the Parallel extensions are the most exciting bits for me. The new Java 7 work is concentrating heavily on concurrency and its good to see both camps pushing the boundaries.

{lang: 'en-GB'}
Share

Learning Scala from a Java perspective

October 1st, 2009 No comments

I’ve been reading up and keeping abreast of both the .NET world and Java world this year, both have some mighty exciting advancements coming – teaser: its all about the Pentiums! I’ll try and cover some of my research into parallel work later.

One of the other areas I’ve been keen on (after hearing from the leader of our pack, Mr Wolfe) was Scala and came across a incredibly useful resource by Daniel Spiewak on looking at Scala from a Java developers perspective.

The linked article is a ’roundup’ of the many posts he’s done on the topic and covers the many facets of Scala and gives it in a Java developers perspective. Highly recommended reading if your just starting out in understanding Scala and functional programming general. I have to admit, Scala is growing on me.

F# is the key functional programming language in .NET and whilst I’ve seen them being compared quite frequently, I feel they target to different areas. From a n00bish-functional-programming perspective, it feels like Scala is all about the OO and F# is more about writing in a functional perspective. But here’s an article from 2007 that may give you a better idea or Brandon Werner‘s article comparing the functional languages.

By the same token, there’s a great introduction to F# that will cover the historical and core language.

I remember messing about 10 years ago with Delphi, VB, Java, C/C++ and thinking this is RAD, but the world seems to be morphing into the functional programming paradigm now.  What better time to start musing with it?

{lang: 'en-GB'}
Share

InvokeRequired with anonymous delegates for threading in WinForms!

September 12th, 2009 2 comments

Here’s a little cookie from the cookie jar. To quote the legendary Jon Skeet from Threading with Windows Forms:

There are two different ways of invoking a method on the UI thread, one synchronous (Invoke) and one asynchronous (BeginInvoke). They work in much the same way – you specify a delegate and (optionally) some arguments, and a message goes on the queue for the UI thread to process. If you use Invoke, the current thread will block until the delegate has been executed. If you use BeginInvoke, the call will return immediately. If you need to get the return value of a delegate invoked asynchronously, you can use EndInvoke with the IAsyncResult returned by BeginInvoke to wait until the delegate has completed and fetch the return value.

Here’s a simple, uncluttered version you can utilise and reuse – this example just adds a list item to the listview.

        public void Add(ListViewItem item)
        {
            if (m_ListView.InvokeRequired)
            {
                m_ListView.BeginInvoke(new MethodInvoker(() => Add(item)));
            }
            else
            {
                m_ListView.Items.Add(item);
            }
        }

First we check whether we’re executing on the GUI thread or not (InvokeRequired), then execute a delegate thats parsed into the MethodInvoker calling itself using a lambda expression. This code is VS2008 compatible (.NET 2.0 +).

For a non lambda version:

      
        public void Add(ListViewItem item)
        {
            if (m_ListView.InvokeRequired)
            {
                m_ListView.BeginInvoke(new MethodInvoker(delegate
                                                             {
                                                                 Add(item);
                                                             }));
            }
            else
            {
                m_ListView.Items.Add(item);
            }
        }

The advantage of using an anonymous delegate is that by design, delegates are able to use local variables and parameters scoped in the containing method. Therefore we didn’t need to create a custom delegate with the signature to pass onto the method.

{lang: 'en-GB'}
Share

ANTS Memory Profiler 5.1 Review

September 7th, 2009 No comments

I recently took a look at the ANTS Memory Profiler 5.1 from RedGate software and posted my thoughts on it at the DeveloperFusion market place. Having toyed with several profilers in the past – DevPartner from Compuware (who’s now someone else who now owns the product) being my primary love since I first came across their .NET version wayyy back in 2002 when I was writing for Australian Developer – see ‘ASP .NET and the Web: Optimising Application Performance’ (who became International Developer who are now no longer around!).

ANTS Memory Profiler Summary

If anyone’s serious about their software you ought to have atleast one profiler (ProfileSharp’s free!) with you to catch those nasty leaks and ANTS MP seems to be the best of the bunch right now. While your at it, take a look at NDepend to add to your arsenal.

I love the fact that I can take a few snapshots, go to the Class list and filter by ‘Disposed objects which are still in memory’ and get a quick list, then drill in to find the sources. Give it ago.

{lang: 'en-GB'}
Share

Quick Tip: Converting an Enum from a string using C# Generics

August 3rd, 2009 No comments

Here’s a quick tip for you. Converting a string back to an Enum using Generics in C#.

private static T ToEnum<T>(string value)
{
	return (T) Enum.Parse(typeof(T), value);
}

Nice and easy, here’s an example usage – very lame I know.

// Original enum
UriFormat uriFormat = UriFormat.SafeUnescaped;
// Persisted value
string uriFormatText = uriFormat.ToString();
// Back to the enum from the persisted value
UriFormat uriFormatParsed = ToEnum<UriFormat>(uriFormatText);

Console.WriteLine(uriFormat);
Console.WriteLine(uriFormatText);
Console.WriteLine(uriFormatParsed);

Another juicy tidbit is coming, hang in there.

{lang: 'en-GB'}
Share

.NET Tools: NDepend static analysis tool, leave T-Pain behind.

June 1st, 2009 5 comments

The release of Visual Studio 2008 brought along Code Metrics to the IDE‘s ‘out-of-the-box’ functionality (I’ve been overusing that phrase thanks to our resident CRM Consultant at work!). This was a major boon for .NET developers to get a clear idea of health of what they write, Visual Studio 2005 gave FxCop integration that provided much needed static code analysis for .NET assemblies. Together these tools provide a peek into the deep depths of the project your working on, it benchmarks the correctness, performance and security implications, localisation, design issues amongst other metrics. Damn useful if you’ve inherited – as I often do in my consultancy life – someone else’s code base with little or no documentation. They say code is the best documentation right? (oh gosh, not one of those projects!)

Whilst both the metrics in VSNET and FxCop give you a low level understanding of your code – based on framework guidelines, what if you want more in depth understanding of what your ‘working with’ rather than how you use the .NET framework? How many methods derive from a certain control – remember we’re doing static analysis here, no Resharper loving! Or how maintainable the assemblies are. What are the methods with more than 30 lines of code? (hint: need to refactor!)

This is where NDepend comes in. NDepend is a static code analysis tool on steroids – and I’m not exaggerating here. You will love NDepend long time as I do right now.

Load up NDepend, point to your assemblies, then let NDepend think a little and it will spit out a plethora of information for you to take in.

The NDepend UI – VisualNDepend

There is however one caveat, the first time you use it – and I know this will happen to the majority of users, you’ll probably get overwhelmed with what you’ll be displayed with:

NDepend Paint.NET Analysis

NDepend Paint.NET Analysis

So you can reproduce this with the trial of NDepend, I’m looking at the latest Paint.NET release. But once you get over your initial sense of wonder and disbelief you can start to demystify the UI and the beauty of NDepend. Dont worry, theres plenty of documentation and help to get you on your way, I’ll cover those later ūüôā

First, we have a Class Browser to the left that lists all the assemblies that are being anaylsed – this includes the assemblies you selected (black!) and the assemblies that were added automajically by NDepend as dependencies (blue).

To the right of the class browser is our Metrics visual representation (those black balls actually mean something – Marty!). We can tell NDepend to show us (visually via the Code Metrics display) the top 10,20,50-5000 methods. Double click on any item in the view and it will automatically jump to the source (in the working VS.NET instance if available) for you to inspect further. Theres also deep integration with Visual Studio too – again later!

Underneath the Metrics window we have the Dependency Graph on the left and the Dependency Matrix on the right. This view gives us an idea of the coupling between the assemblies in our list.

The World of CQL

Then we have – what makes me get jiggy wif it, the CQL Query window. CQL is Code Query Language, and its just as your thinking, its SQL for Code. Armed with a basic understanding of CQL you can get some really useful information about your project – infact the report that gets generated by NDepend already contains a bunch of metrics for you and comes with over 85 metrics to begin with in a heavily documented specification – with examples. Writing a simple bit of CQL like the one below, will give you a representation of all public methods that contain more than 30 lines of code.

SELECT METHODS WHERE NbLinesOfCode > 30 AND IsPublic

Neat huh? Thats only an example from the features page, there’s lots more. We can even setup a constraint to notify us when we exceed a threshold.

WARN IF Count > 0 IN SELECT METHODS WHERE NbILInstructions > 200 ORDER BY NbILInstructions DESC

This will warn us when we have methods that exceed 200 IL instructions. You can even combine a bunch of them and workout a metric to benchmark which methods you need to refactor, heres one from the report that gets autogenerated by the VisualNDepend tool:

WARN IF Count > 0 IN SELECT TOP 10 METHODS /*OUT OF "YourGeneratedCode" */ WHERE 

                                           // Metrics' definitions
     (  NbLinesOfCode > 30 OR              // http://www.ndepend.com/Metrics.aspx#NbLinesOfCode
        NbILInstructions > 200 OR          // http://www.ndepend.com/Metrics.aspx#NbILInstructions
        CyclomaticComplexity > 20 OR       // http://www.ndepend.com/Metrics.aspx#CC
        ILCyclomaticComplexity > 50 OR     // http://www.ndepend.com/Metrics.aspx#ILCC
        ILNestingDepth > 4 OR              // http://www.ndepend.com/Metrics.aspx#ILNestingDepth
        NbParameters > 5 OR                // http://www.ndepend.com/Metrics.aspx#NbParameters
        NbVariables > 8 OR                 // http://www.ndepend.com/Metrics.aspx#NbVariables
        NbOverloads > 6 )                  // http://www.ndepend.com/Metrics.aspx#NbOverloads
     AND 

     // Here are some ways to avoid taking account of generated methods.
     !( NameIs "InitializeComponent()" OR
        // NDepend.CQL.GeneratedAttribute is defined in the redistributable assembly $NDependInstallDir$\Lib\NDepend.CQL.dll
        // You can define your own attribute to mark "Generated".
        HasAttribute "OPTIONAL:NDepend.CQL.GeneratedAttribute")

Whats more, because NDepend is language neutral you can query any managed assembly. Theres so much goodness you can get from CQL, most of your needs are already documented in the specifications.

Healthy coder == healthy code right?

NDepend also gives us a representation of what state the code is in with the generated report.

Paint.NET Abstractness vs Stability

Paint.NET Abstractness vs Stability

This metric – based on Robert C Martin’s Abstractness vs Stability paper. To quote the paper’s Abstract directly:

This paper describes a set of metrics that can be used  to measure the quality of an object-oriented design in terms of the interdependence between the subsystems  of  that design.   Designs which are highly interdependent tend to be rigid, unreusable and hard to maintain.
Yet interdependence is necessary if the subsystems of  the design are to collaborate.  Thus, some forms of dependency must be desirable,
and other forms must be undesirable.   This paper proposes a design pattern in which all the dependencies are of the desirable form. Finally, this paper describes a set of  metrics that measure the conformance of a design to the desirable pattern.

In the case of Paint.NET we can see that we’re all over the bottom corner of the image. What does this mean?

First we have the two ends of the scale.

  • Y – Abstractness
    This measures how abstract the assembly is, can it be extended without recompiling? Lots of interfaces and base classes help here.
  • X – Instability
    Measures how much this assembly is utilised by its public interface. For most third party component (from vendors) they’ll fall into the less instability area, so you have to ensure that any changes are properly managed to avoid breaking clients.

Then we have two zones.

  • Zone of uselessness
    This is when an assembly is very abstract and extensible but no-one uses it you’ll find it closer to this area.
  • Zone of Pain
    This is when an assembly is referenced (or have lots of dependants) and is not very extensible – no abstract implementations.

One thing to note though, the words ‘Pain’ and ‘Uselessness’ may be a bit harsh in its wording. If you – like me – have a core ‘framework’ that you write have it locked down and reference it muliple projects then they should indeed fall into the ‘Zone of Pain’ assuming that you have ensured its stability and realise the consequences of breakages later on. Most third party products will fall into here – we’re talking your UI Controls, Sharp components etc.

Ideally you’d want to be hovering in the green area cosey with the line in the middle for your core product.

Would you like Documentation with that?

As mentioned earlier, NDepend comes with lots of help, firstly we have – what I used, the Getting Started screencasts, tutorials, CQL Documentation with *actual* usable examples.

Scott Hanselman has also released a nice cheatsheet for NDepend that will go well hanging next to your PC.

Integrating NDepend to Integration Server

At home (and at work) we use Jetbrains TeamCity, you can easily integrate NDepend into TeamCity by following Laurent Kempé directions.

If you use CruiseControl.NET, you’ll find Robin Curry‘s guide on integrating NDepend to NAnt and CruiseControl.NET useful.

Integration with your favourite tools

NDepend fully integrates with Visual Studio and Reflector.

NDepend Options Integration

NDepend Options Integration

The integration in Reflector – which reflect that of Visual Studio integration.

NDepend Reflector Integration

NDepend Reflector Integration

Gives you one click access to some common metrics.

Conclusion

If you want to get a good understanding of your project – or someone elses, metrics will help you greatly to give you an impression of the health of the project and NDepend will come in quite handy for you. We only _barely_ scratched the surface with this blog post, I’ve spent a good chuck of a week using NDepend and find it ubber useful in my work life – partly because it involves reparing the mess others have left – but it also serves as a good reminder of how you should write code.

References

Fine Print: Full Disclosure

I was offered a license to NDepend by Patrick Smacchia and given the chance to write my thoughts on this product, I was not paid to review this product – feel free to send some moola if you want to though ūüėČ

{lang: 'en-GB'}
Share

Hot Booty: Visual Studio 2010 Beta Launches!

May 19th, 2009 No comments

Quick note from Somasegars blog that Visual Studio 2010 Beta 1 along with .NET Framework 4.0 Beta 1 is shipping. Take a look at the Visual Studio 2010 Home Page for more information or if you have MSDN grab it from your subscriber downloads.


{lang: 'en-GB'}
Share