Profil von philPhil Harvey's .NET SpaceBlogListen Extras Hilfe

Blog


    04 Oktober

    Talking about: Allocation Profiler

    This tool is great at working out why your tiny .NET utility is using 80MB of memory! It lets you graphically see what objects have been allocated and quickly see where your memory leaks are.

    Of course, the CLR should control this sort of thing, surely? Having to use this tool breaks any contract of trust a developer should have with the CLR. If you are having memory leak problems even after garbage collection then somewhere in your code you must have references to instances of objects that you have long forgotten about! Either that, or *anything* to do with unmanaged code (COM Interop, Win32)

    Quote

    GotDotNet User Sample: Allocation Profiler
    Allocation Profiler is a tool for visualizing and analyzing allocations on the GC heap. It presents the data from this log file in a variety of interesting and useful views. It can be used to verify program execution (e.g. ensure you've allocated only the objects you thought) and to detect possible memory leaks. Simply launch AP, point it at your EXE and click a button.
    16 Juni

    Develop Managed Outlook Add-ins with VSTO 2005

    Yes! Visual Studio 2005 has a decent way of creating managed Outlook Add-ins!! If only I had this stuff 12 months ago my life would be so much simpler. Still, at least the future looks bright for new Outlook projects I might undertake.

    Microsoft has unveiled VSTO (Visual Studio Tools for Office). Follow the link below to find out all about it.

    Quote

    Srinath Vasireddy - Online journal : Develop Managed Outlook Add-ins with VSTO 2005
    After several weeks of hard work, at TechEd we announced our latest work – Yes, you can now easily develop managed outlook add-ins with VSTO 2005.
    28 April

    Rick Strahl blogger genius

    Rick Strahl has one of the best .NET web logs around (RSS). Just to let you know. But if you didn't know that already, then shame on you. I like to read it when I'm bored, he has great technical insight into .NET issues we all understand.

    18 April

    Set file permissions from an Installer custom action

    A common task for using an Installer action in your Visual Studio deployment project would be to change the file access permissions on some of the files you have just installed. Currently, the .NET framework does not provide any mechanism for managing access rights on files - although this will change in version 2.0 (Whidbey). In the mean time, there's a download at gotdotnet.com called Win32Security (Download Now). This community library lets you manage file security attributes on NTFS file systems. 

    Download and build the project, and reference it to your Installer custom action class. The following code sample will add the "All Access" privilege to the ASPNET user on the web.config file.

    If you are new to installer custom actions I strongly suggest you read this article before trying to understand the code below.

    Note: You will need to pass the install directory to the custom action by setting the "CustomActionData" parameter of the custom action to /dir="[TARGETDIR]\".

    Installer custom action class to set the file permissions on the web.config file

    using System;
    using System.ComponentModel;
    using System.Configuration.Install;
    using System.Collections;
    using System.IO;
    using Microsoft.Win32.Security;

    namespace InstallDemo.Installer
    {
      /// <summary>
      /// Sets the permissions of the web.config file.
      /// </summary>
      [RunInstaller(true)]
      public class WebConfigInstaller :
         
    System.Configuration.Install.Installer
      {
         
    public WebConfigInstaller()
          {
          }

          /// <summary>
          /// Gets the file name of the web.config file.
          /// </summary>
          protected string WebConfigFilename
          {
            get
            {
              return Path.Combine(this.Context.Parameters["dir"], "web.config");
            }
          }

          public override void Install(IDictionary stateServer) 
          {
            base.Install(stateServer);
      
            FileInfo configFile = new FileInfo(this.WebConfigFilename);

           if (configFile.Exists)
           {
             // Give "ASPNET" user full access
             SecurityDescriptor secDesc =
               SecurityDescriptor.GetFileSecurity (
                 configFile.FullName,
                 SECURITY_INFORMATION.DACL_SECURITY_INFORMATION);

             Dacl dacl = secDesc.Dacl;

             dacl.AddAce (
             new AceAccessAllowed (new Sid("ASPNET"),
             AccessType.GENERIC_ALL));

             secDesc.SetDacl(dacl);

             secDesc.SetFileSecurity(
               configFile.FullName,
               SECURITY_INFORMATION.DACL_SECURITY_INFORMATION);
          }
        }
      }
    }


     

    16 Februar

    Talking about .NET Tools: Ten Must-Have Tools Every Developer Should Download Now -- MSDN Magazine, July 2004

    James Avery points out a list of tools every .NET developer should have. I'm using a couple of them and will certainly will try and use a few more. Does anyone use NAnt? Why should I use it instead of Visual Studio to build my projects?

    Quote

    .NET Tools: Ten Must-Have Tools Every Developer Should Download Now -- MSDN Magazine, July 2004
    You cannot expect to build a first-class application unless you use the best available tools. Besides well-known tools such as Visual Studio .NET, there are a multitude of small, lesser-known tools available from the .NET community. In this article, I'm going to introduce you to some of the best free tools available today that target .NET development. I'll walk you through a quick tutorial of how to use each of them, some of which will save you a minute here and there, while others may completely change the way that you write code. Because I am squeezing so many different tools into this single article, I will not be able to cover each of them extensively, but you should learn enough about each to decide which tools are useful for your projects.
    01 Februar

    Unit Testing and Code Coverage

    Apologies for not posting over the past few weeks. I have been giving the blog a rest to see how google indexes and links to it. The results are interesting and I will comment on them at a later date.

    Recently I have got into Unit Testing in a big way. The idea behind Unit Testing is that you write code as individually testable functions and methods, and write a series of automated tests to guarantee they are working properly. If your tests all execute successfully, then your application should in theory work properly. You can then change the test environment, try about with different configurations, and make sure your automated tests consistently succeed.

    Unit Testing can be used to implement a test driven development methodology. When designing a class, you design a series of tests that the class should be able to perform. You then write the class to pass these tests.

    Testdriven.com has lots of information and resources on the test driven methodology.

    From their FAQ, the advantages of test driven development are:

    • Code that works.
    • Fast feedback: you begin to see the results of design decisions in minutes.
    • Flexibility: if you don't like what you see, you can change it on the spot.
    • A growing catalogue of regression tests if something you do today breaks something you did six months ago, you will know immediately.
    • Happy customers, because they can provide input as the code is being developed.
    • Satisfied programmers, because they can see that their code works and is what the customer wants.
    • Good, clean code, code that works. This is the first, last, and most important benefit.

    Tools for Unit Testing in .NET
    The tool you should download today is NUnit. NUnit is a testing framework for .NET. Its simple to use and has a nice graphical interface to see the results of your automated tests. Visit NUnit.org for more details.

     

    Code Coverage
    Code coverage is the percentage of your code that is tested. Good test based code should have 100% code coverage. To achieve 100% code coverage your tests must travel down every possible executing path in your code and check for the correct result.

    The tools for code coverage analysis in .NET are NCover and NCoverGui. The proper use of these tools is a complex topic and Howard van Rooijen has an excellent tutorial at his blog.

     

    I fully recommend test driven development. If you have never tried it, download these tools and try them out on a small project. Happy testing!

    21 Dezember

    C#/VB .NET Coding Guidelines From Iridium Software

    I found a good document over at Iridium Software discussing coding standards for both C# and VB.NET. At over 100 pages it covers a lot of ground, focusing on C# and VB.NET issues in equal depth. This is great because many other standards documents out there seem to focus much more on the C# side of things.

    It’s an easy read with straight-to-the-point bullets and easy to follow code samples. It’s more of a recommendation than a strict code of practice. I don’t agree with everything, as I’m sure neither will FXCop.

    If you or your company don’t have any specific coding standards to follow it’s a good place to start, and if you find a couple of hours over the Christmas break I’d definitely recommend the read.

     

    14 Dezember

    A .NET CPU

    A startup company has made a CPU with a tiny CLR and a subset of the .NET CF. Its looks pretty sweet. You can buy a pack which contains a CPU and an interface to hook it into Visual Studio for about 500 USD. I want one. I don't what I'd do with it. Probably turn various household appliances into autmoton battle-bots. Who wants to toaster-war, .NET style?

    Quote

    Teeny module runs new ".NET Embedded" software stack
    A small startup in Microsoft's backyard is poised to begin shipping a tiny, 32-pin chip-like computer module that runs ".NET Embedded," a new Microsoft embedded software platform developed for use in watches and other "smart personal objects." The module, developed by startup .netcpu Corp., incorporates portions of Microsoft's Smart Personal Objects Technology (SPOT) hardware and software.
    08 Dezember

    Cached Http Requests in .NET

    The WebClient class, found in the System.Net namespace in the .NET framework, is an easy way to get data from http servers into your .NET apps. Until recently I used it a lot for downloading configuration files and graphics for some smart client applications. However, it has a fatal flaw in which is it does not have a mechanism for caching data. This can make applications unnecessarily slow in certain situations.

    A solution to perform cached http requests in .NET is to use unmanaged calls to WinInet.dll. This library uses the same cache mechanism that Internet Explorer uses.

    The following class demonstrates how to download an http file in .NET using unmanaged calls to WinInet.dll.

    Imports System.Text
    Imports System.Runtime.
    InteropServices
    Imports Microsoft.VisualBasic.
    ControlChars
    Imports System.
    IO

    Public Class WinInetTest
        Implements IDisposable

       
    ' WinInet constants.
        Private Const INTERNET_ACCESS_TYPE_DIRECT =
    1

       
    ' Member constants.
        Private Const USER_AGENT =
    "IE"
        Private Const HEADER As String = "Accept: */*" & Cr &
    Cr
        Private Const CONTEXT As Integer =
    0
        Private Const FLAGS As Integer =
    0

       
    ' Member variables.
        Private _handle As IntPtr

       
    ' Import WinInet.dll functions.
        <DllImport("WinInet.dll", _
        EntryPoint:="InternetOpenA", _
        CharSet:=CharSet.Ansi, ExactSpelling:=True, SetLastError:=True)> _
        Private Shared Function InternetOpen( _
        ByVal agent As String, _
        ByVal accessType As Int32, _
        ByVal proxyName As String, _
        ByVal proxyBypass As String, _
        ByVal flags As Int32) As IntPtr
        End
    Function

        <DllImport("WinInet.dll", _
        EntryPoint:="InternetOpenUrlA", _
        CharSet:=CharSet.Ansi, ExactSpelling:=True, SetLastError:=True)> _
        Private Shared Function InternetOpenUrl( _
        ByVal session As IntPtr, _
        ByVal url As String, _
        ByVal header As String, _
        ByVal headerLength As Int32, _
        ByVal flags As Int32, _
        ByVal context As Int32) As Int32
        End
    Function

        <DllImport("WinInet.dll", _
        EntryPoint:="InternetReadFile", _
        CharSet:=CharSet.Auto, SetLastError:=True)> _
        Private Shared Function InternetReadFile( _
        ByVal handle As Int32, _
        <MarshalAs(UnmanagedType.LPArray)> _
        ByVal newBuffer() As Byte, _
        ByVal bufferLength As Int32, _
        ByRef bytesRead As Int32) As Int32
        End
    Function

        <DllImport("WinInet.dll", _
        EntryPoint:="InternetCloseHandle", _
        CharSet:=CharSet.Ansi, ExactSpelling:=True, SetLastError:=True)> _
        Private Shared Function InternetCloseHandle( _
        ByVal hInternet As Int32) As Int32
        End
    Function

        Sub New
    ()
           
    ' Open an internet session.
            _handle = Me.InternetOpen(USER_AGENT, _
                                        INTERNET_ACCESS_TYPE_DIRECT, _
                                        vbNullString, vbNullString, FLAGS
    )
        End
    Sub

       
    ' Read a file from a url.
        Public Function GetHttpFile(ByVal url As String) As Byte
    ()
            Dim bufferLength As Int32 = 1024
    ' Size of buffer to read into.
            Dim bufferStream As New MemoryStream
    ' Stream to read buffer into.
            Dim bufferStreamWriter As New BinaryWriter(bufferStream
    )

            Dim session As Int32
    ' Http request session handle.

           
    ' Open http request.
            session = Me.InternetOpenUrl(Me._handle, url, _
                                            HEADER, HEADER.Length, _
                                            0, CONTEXT
    )

            If session <= 0
    Then
               
    ' Open session failed.
                Throw New Net.WebException(Marshal.GetLastWin32Error
    ())
           
    Else
                Dim newBuffer() As
    Byte
                Dim bytesRead As Int32
                Dim response As
    Boolean

                Do
    ' Read bytes from http stream until all are read.
                    ReDim newBuffer(bufferLength - 1
    )
                    response = Me.InternetReadFile(session, newBuffer, _
                                                        bufferLength, bytesRead
    )
                    If Not response
    Then
                       
    ' Read failed.
                        Throw New Net.WebException(Marshal.GetLastWin32Error
    ())
                   
    Else
                       
    ' Write bytes read to response stream.
                        bufferStreamWriter.Write(newBuffer, 0, bytesRead
    )
                    End
    If
                Loop While response And bytesRead >
    0
            End
    If
            Me.InternetCloseHandle(session
    )

           
    ' Get buffer bytes.
            Dim bufferBytes As Byte() = bufferStream.
    GetBuffer

           
    ' Close streams.
            bufferStreamWriter.Close
    ()
            bufferStream.Close
    ()

           
    ' Return return bytes read.
            Return bufferBytes
        End
    Function

        Private _disposed As Boolean =
    False

        Public Sub Dispose() Implements System.IDisposable.
    Dispose
           
    ' Close the internet session.
            If Me._disposed Then Exit Sub
    ' Abort if already disposed.
            Me.InternetCloseHandle(_handle.ToInt32
    )
            Me._disposed =
    True
        End
    Sub

        Protected Overrides Sub Finalize
    ()
            MyBase.Finalize
    ()
           
    ' Dispose, only if not done already.
            Me.Dispose
    ()
        End
    Sub
    End
    Class

    The following code shows how to use the WinInet class to perform an http request.

    Dim httpReader As New WinInet
    Dim bytesRead As Byte()
    bytesRead = httpReader.GetHttpFile("http://spaces.msn.com/members/dotnetspace/")
    MsgBox(System.Text.ASCIIEncoding.ASCII.GetString(bytesRead))
    httpReader.Dispose()
    httpReader = Nothing 

    02 Dezember

    Get current method details via reflection

    Sometimes its handy to know details about the current executing method. For example, you may want to pass the current method name to a logging procedure without hardcoding it. System.Reflection.MethodBase.GetCurrentMethod gives you that detail! 

    Dim current As System.Reflection.MethodBase = System.Reflection.MethodBase.GetCurrentMethod
    System.Diagnostics.Debug.WriteLine(current.Name)
    System.Diagnostics.Debug.WriteLine(current.DeclaringType.Name)
    System.Diagnostics.Debug.WriteLine(current.DeclaringType.Namespace)