Tuesday, June 08, 2004

To or not to unit test provate methods?


PrivateObject Unit Tester



AndrewSeven was kind enough to direct me to a blog by James Newkirk briefly introducing the PrivateObject class available at part of the VS Team System framework.


I was intrigued enough to start investigating and ended up implementing what I think is a close interpretation of this class, shown below.


The primary interface is the constructor which accepts an assembly qualified type name as the first parameter (used by Type.GetType()).  The second parameter is optional and is passed as the arguments to instantiate the type; these arguments determine the constructor signature to choose.


As documented in the Type.GetType() method, the qualifiedTypeName should be of the form MyNamespace.MyClass,MyAssemblyBaseName.


Here's the code:

using System;
using System.Reflection;
using System.Security.Permissions;

 

#region .
/// <summary>
/// This utility class uses reflection to wrap an instance of a

/// class to gain access to non-public members of that class.

/// This is an internal utility class used for unit testing.
/// </summary>
#endregion
public class PrivateObject
{
    private const BindingFlags bindingFlags

= BindingFlags.Instance | BindingFlags.NonPublic;


    private Type type;                  // type of class to manage
    private object instance;            // managed instance of type
    private ReflectionPermission perm;  // for non-public members


 

    #region .
    /// <summary>
    /// Initializes a new instance wrapping a new instance of the

/// target type. One PrivateObject manages exactly one instance

/// of a target type.
    /// </summary>
    /// <param name="qualifiedTypeName">The qualified name of the type.

/// This should include the full assembly qualified name including

/// the namespace, for example "MyNamespace.MyType,MyAssemblyBaseName"

/// where MyNamespace is the dotted-notation namespace, MyType is the

/// name of the type and MyAssemblyBaseName is the base name of the

/// assembly containing the type.
    /// </param>
    /// <param name="args">An optional array of parameters to pass to

/// the constructor. If this argument is not specified then the

/// default constructor is used. Otherwise, a constructor that

/// matches the number and type of parameters is used.
    /// </param>
    #endregion
    public
PrivateObject (string qualifiedTypeName, params object[] args)
    {
        perm = new ReflectionPermission(PermissionState.Unrestricted);
        perm.Demand();


        type = Type.GetType(qualifiedTypeName);


        Type[] types = new Type[args.Length];
        for (int i=0; i < args.Length; i++)
        {
            types[i] = args[i].GetType();
        }


        instance = type.GetConstructor(bindingFlags,null,types,null).Invoke(args);
    }


 

    #region .
    /// <summary>
    /// Gets the instance of the managed object.
    /// </summary>
    #endregion
    public object Instance
    {
        get { return instance; }
    }


 

    #region .
    /// <summary>
    /// Gets the value of a non-public field (member variable) of the

/// managed type.
    /// </summary>
    /// <param name="name">The name of the non-public field to

/// interrogate</param>
    /// <returns>A value whose type is specific to the field.</returns>
    #endregion
    public object
GetField (string name)
    {
        return type.GetField(name,bindingFlags).GetValue(instance);
    }



    #region .
    /// <summary>
    /// Gets the value of a non-public property of the managed type.
    /// </summary>
    /// <param name="name">The name of the non-public property to

/// interrogate.</param>
    /// <returns>A value whose type is specific to the property.</returns>
    #endregion
    public object
GetProperty (string name)
    {
        return type.GetProperty(name,bindingFlags).GetValue(instance,null);
    }


 

    #region .
    /// <summary>
    /// Invokes the non-public method of the managed type.
    /// </summary>
    /// <param name="name">The name of the non-public method to invoke.</param>
    /// <param name="args">And optional array of typed parameters to pass to the
    /// method.  If this argument is not specified then the routine searches
    /// for a method with a signature that contains not parameters.  Otherwise,
    /// the procedure searches for a method with the number and type of parameters
    /// specified.
    /// </param>
    /// <returns>A value who type is specific to the invoked method.</returns>
    #endregion
    public object Invoke (string name, params object[] args)
    {
        Type[] types = new Type[args.Length];
        for (int i=0; i < args.Length; i++)
        {
            types[i] = args[i].GetType();
        }


        return type.GetMethod(name,bindingFlags,null,types,null).Invoke(instance,args);
    }


 

    #region .
    /// <summary>
    /// Sets the value of a non-public field (member variable) of the managed type.
    /// </summary>
    /// <param name="name">The name of the non-public field to modify.</param>
    /// <param name="val">A value whose type is specific to the field.</param>
    #endregion
    public void
SetField (string name, object val)
    {
        type.GetField(name,bindingFlags).SetValue(instance,val);
    }


 

    #region .
    /// <summary>
    /// Sets the value of a non-public property of the managed type.
    /// </summary>
    /// <param name="name">The name of the non-public property to modify.</param>
    /// <param name="val">A value whose type is specific to the property.</param>
    #endregion
    public void SetProperty (string name, object val)
    {
        type.GetProperty(name,bindingFlags).SetValue(instance,val,null);
    }
}


 

Sunday, June 06, 2004

Marked:


.NET Tool/Control vendors/creators: new directory site: www.developerfood.com!




A good friend of mine, Scott Wallace, has created a new .NET tool/control directory site: http://www.developerfood.com! If you are a tool / control vendor or a freeware/open source tool/control programmer, feel free to add your tool/control to the directory. The site is free, doesn't sell the controls / tools it lists nor is it affiliated with a tool/control vendor.



I think it is a great initiative and it takes just a few minutes to get your tool/control enlisted. One for the bookmarks!

Wednesday, June 02, 2004

SQL Server Developer Center:


SQL Server Developer Center



This is nice:



Microsoft has launched a SQL Server Developer Center. [by way of Scott Swigart/Early Adopter]


Looking forward to some very good resources from this site.

Windows Media Play 10 Public Beta is available:


href="http://www.microsoft.com/windows/windowsmedia/mp10/default.aspx#download">http://www.microsoft.com/windows/windowsmedia/mp10/default.aspx#download

Monday, May 31, 2004

Gmail is in trouble

Gmail is in trouble:






Anti Gmail Legislation



California Senate Passes Watered Down Anti-Gmail Bill 


So the California state government is passing legislation controlling an as-yet-unreleased technology service. I don’t think I’ve ever heard of such a thing before.



 

Rob Howard is leaving MS:
Via Dino. Rob is on the news today


Rob Howard, one of  brains behind the excellent provider model in ASP.NET 2.0 (sure, not just that...) leaves MS. I want to wish all the best of luck (and why not, a LOT of fun) to Rob for the new venture: Telligent Systems. As of today, the Web site contains just a GIF but I wonder which technology are they using to build the site. Maybe JSP? <g>


PS: I also wondered why Telligent Systems and not, a more natural for me, Intelligent Systems. Elementary, Dr. Watson! Intelligent Systems already exists; both with .com and .net. It doesn't exist as .it, but who cares :-)

Saturday, May 29, 2004

Yahoo's new toolbar can stop spy ware and ad ware. It's a very neat feature to many users. What will MS ang Google do with this?-)
Nice Saturday. Will meet my friends tonight.

Tuesday, May 25, 2004

Recommended by Scobleizer, a cool rss reader:


Sauce Reader, another RSS aggregator to try



Wow, another cool news aggregator was released over the weekend: Sauce Reader.


It also has integration with the Windows Messenger client (not yet the MSN one). I have that on my desk at work, so will try it there.


Nice WSE 2.0 Tracing tool:


WSE 2.0 Tracing Utility








With the release of the Web
Services Enhancements 2.0 (go here href="http://msdn.microsoft.com/webservices/building/wse">http://msdn.microsoft.com/webservices/building/wse
for a download) I thought I’d publish my efforts at providing a secondary
tracing utility. WSE 2.0 has tracing facilities that can be switched on via the
configuration file which traces messages to a text file but I wanted something
that looked a little bit more like the SOAPTrace tool that shipped with he SOAP
toolkit so that I can more easily use it for demos and so on.

 

So, I wrote something. I’m sure it
has flaws but if it’s of use to other people then that’s great and I’ll share it
here – the usual caveats apply around not being intended for any particular
purpose and coming without warranty implied or explicit.

 

This href="http://mtaulty.com/downloads/WSE2_Tracing_V1.zip">http://mtaulty.com/downloads/WSE2_Tracing_V1.zip 
is the URL for download – I’ve not included the source at this point but I can
do that if someone’s keen to get it.

 

Essentially, what I wrote uses
WSE2.0 SOAP messaging to trace WSE2.0 messaging (be that ASMX or SOAP
messaging).

 

So, naturally, your messaging slows
down a bit because whenever you send/receive a message if you’ve switched on
tracing I then go and send a copy of your messages over the SOAP.TCP protocol to
the tracing client.

 

The tracing client looks like
this;

 

src="http://mtaulty.com/blog/Images/traceclient.jpg" align=baseline
border=0>

 
So, to work the client
you use File->Start/Stop tracing to start the client listening for messages
and then File->Clear to clear the traces captured and the tree view will
display messages that it has traced going in or out of each process and
application domain that you have configured tracing for. You can configure
tracing to be for incoming or outgoing messages or both.

 

By default, the tracing client
listens on soap.tcp://localhost:9999/SoapTracer. If, for some reason you don’t
want this you can change it using the Tools->Options dialog box which looks
like this;

 

align=baseline border=0>

 

And should allow you to pick a
different endpoint to listen on for those trace messages.

 

That’s pretty much it for the
tracing client – note that it’s actually persisting the XML to disk in order to
use Internet Explorer to display the XML which is not very clever but was a
quick “win” for me.

 

So, how do you configure your
applications in order to get their WSE2.0 messages traced to the tracing
client?

 

Essentially, you modify the
configuration file for the application that you want tracing for. A sample
configuration file is shipped within the MSI and looks like this (except the
real file has more comments in it);

 

<?xml version="1.0"
encoding="utf-8"?>

 

 size=2><configuration>

 

  <configSections>

    <section
name="microsoft.web.services2"
type="Microsoft.Web.Services2.Configuration.WebServicesConfiguration,
Microsoft.Web.Services2, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" />

    <section
name="WSETraceSettings" type="WSETracingConfig.ConfigHandler, WSETracingConfig,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=1c1f2f7177e1ff79"
/>

  </configSections>

 

  <WSETraceSettings
xmlns='urn:wsetrace-mt-com'>

    
<hostname>127.0.0.1</hostname>

    
<port>9999</port>

    
<endpoint>SoapTracer</endpoint>

  </WSETraceSettings>

 

 
<microsoft.web.services2>

 

    <filters>

       
<output>

size=2>           
<add type="WSETracingFilter.WSEOutputFilter,WSETracingFilter,
Version=1.0.0.0, Culture=Neutral,
PublicKeyToken=1c1f2f7177e1ff79"/>

size=2>           
<add type="WSEReorderPipelineFilter.WSETracingReorderOutputFilter,
WSETracingReorderPipelineFilter, Version=1.0.0.0, Culture=Neutral,
PublicKeyToken=1c1f2f7177e1ff79"/>

       
</output>

       
<input>

size=2>           
<add type="WSETracingFilter.WSEInputFilter,WSETracingFilter, Version=1.0.0.0,
Culture=Neutral, PublicKeyToken=1c1f2f7177e1ff79"/>

size=2>           
<add type="WSEReorderPipelineFilter.WSETracingReorderInputFilter,
WSETracingReorderPipelineFilter, Version=1.0.0.0, Culture=Neutral,
PublicKeyToken=1c1f2f7177e1ff79"/>           

       
</input>

   
</filters>    

  </microsoft.web.services2> 

</configuration>

 
face=Verdana color=#000080 size=2>

So, the way that the tracing filter is implemented is as a filter for
the WSE 2.0 pipeline so if you want tracing to occur you need to configure it
into that pipeline. This is done through the;

 

       
<filters>

color=#000000>               
<output>

color=#000000>                       
<add>

       
<filters>

color=#000000>               
<input>

color=#000000>                       
<add>

 

 

Elements that we have in the configuration file above. Note that you do not
need to have both input and output tracing – it’s entirely up to you. Note that
if you do want filtering then you have to include both add lines in each case
(explanation to follow).

 

Note that the section within the

 

       
<WSETraceSettings>

 

element is entirely optional and is only necessary if you have changed the
tracing tool (via Tools->Options) to listen on a new endpoint. If you have
done that then you need to configure that endpoint here as well or the trace
messages will not reach the tracing client. It’s important to note that if you
do include this <WSETraceSettings> element then you also need to include
the;

 

       
<configSections>

color=#000000>               
<section name=”WSETraceSettings” …

 

in order that the <WSETraceSettings> section can be understood.

 

That’s pretty much it. I’m keen to take feedback and/or share the source
with people if anyone wants it. Happy to fix bugs for people or rework it
completely if someone spots a fundamental flaw.

Source: CSS2 Intellisense for Visual Studio .Net

CSS2 Intellisense for Visual Studio .Net
Thanks Scott for the link !

Read this article and download the required metadata file to bring CSS2 to VS.Net.

When will MS release the Longhorn?-)


Objectspaces, WinFS and MBF all in Longhorn



I've been watching - and reading - the recent debate over the announcement to postpone the launch of Objectspaces to Longhorn by aligning it with WinFS.


Barry Gervin has a report from TechEd on this issue that ties together this decision with MBF also being moved to the Longhorn timeframe. I think it makes sense to make every effort possible to make sure that when we [MSFT] decide to put out a new data-access API, we can say that we have done everything possible to make sure that it is aligned across all layers that will build on it, and that it will provide a stable programming model for many years forward.


I don't think it is prudent to dismiss WinFS as "Just a Filesystem" that does not have anything to do with data-storage. It represents a paradigm shift in terms of connecting structured and unstructured storage, database and filesystem, and provides an object-relational model for data access - That, combined with the need to support the requirements for data access that ObjectSpaces and MBF bring to the marriage will help make WinFS suited to be the data-access platform for the future. For MBF this partnership will surely mean that we can now rely on a strong underlying persistance platform that will also be the data-storage platform of choice for Longhorn generation apps.

Slides about Avalon:


Talking Avalon at WinHEC



Earlier this month I had the opportunity to present the overview of Avalon at the Windows Hardware Engineering Conference (WinHEC).  The conference attendees are typically independent hardware vendors, designers, and folks writing software at the software/hardware interface level.  As such, there's less interest in the higher level aspects of Avalon, but there was a lot of interest in the entire graphics and media stack.  So my talk focused on that.  General WinHEC session information and materials can be found here.


Other Avalon graphics and media sessions at WinHEC delivered by my colleagues can be found here:


  • Greg Schechter: Avalon Graphics Stack Overview [682 KB]  (mine, referenced above)
  • Joe Beda: Avalon Graphics - 2D, 3D, Imaging and Composition [284 KB]
  • Kerry Hammil: Graphics on the Windows Desktop [496 KB]
  • David Brown: Avalon Text [1.05 MB]

    Stay tuned for another post, hopefully soon, about 3D, for which WinHEC was our coming out party.

  • Note this for latter use:


    Reporting Services: How can I deploy my report without Visual Studio?



    To handle this,  there is a utility called rs.exe.  This utility allows the a developer to create a script utilizing Visual Basic.NET. 


    A sample script will follow soon.

    Monday, May 24, 2004

    Visual Studio 2005 Team System Technical Preview is published:
    Visual Studio 2005 Team System
    Connect IE and Mozilla FireFox:


    View in Firefox, courtesy of Raymond Chen



    Raymond Chen wrote up a post on extending the IE context menu in response to a comment I left on Brendan’s blog post of useful IE features.


    Reading Raymond’s post, it definitely is not hard to do, and I appreciate the fact that he didn’t nuke me. When I originally searched around with the “View in Firefox” idea in mind, I never found the article he links to. I think I had a problem with figuring out the right search terms, because it seems pretty obvious now. Be sure to check out the comments, there’s more cool tweaks there.


    Anyway, thanks Raymond.

    Sunday, May 23, 2004

    Good experience in VPC:


    Virtual PC Lesson Learned



    Yesterday I wanted to use a locally installed Virtual PC Windows 2003 Server
    to test an MSI file that needed to be built for the Crystal Reports Merge
    Module. We don't use the "shared folder" approach to deploying applications,
    rather, we let the FrontPage Server Extensions do the heavy lifting. It just
    works. My original problem was that the networking was terribly slow, though,
    and the process would time out.


    On reflection, that's easy to understand: both the OS (a Windows XP session)
    and the Virtual PC program were in a race to utilize the network interface. My
    fix?



    1. Power down and crack the case of the PC.

    2. Install a second NIC (I have a small cache of parts around for just such
      cases)

    3. Patch second NIC into hub, switch or what-have-you.

    4. Boot up, log in.

    5. Access the property sheet for the original NIC and unbind "Virtual
      Machine Network Services." Apply change.

    6. Access the property sheet for the new NIC and verify that the "Virtual
      Machine Network Services" binding is made.

    7. Run Virtual PC console. Update Virtual Server as needed.


    While I didn't actually measure the impact of this change, it felt like my
    Virtual PC session was making at least a 500% improvement in total network
    utilization.

    Scott is ready to fight with spams:0)


    Summer Project: Destroy Blog Spam



    The path of a righteous man is beset on all sides, by the inequities of the selfish , and the tyranny of evil men. blessed are those who in the name of charity and goodwill , shepherd the weak through the walley of darkness , for he is truly his brothers keeper and finder of lost children. and i will strike down upon thee whit great vengeance and furies anger those who attempt to poison and destroy my brothers. And you will know my name is the Lord , when i lay my vengeance upon thee. [Ezekiel 25:17]

    A little too dramatic? Probably. Blog spam has to go. Turning off comments is not an answer. No solution will be perfect. But hopefully, with the right set of tools/features, something can be done.

    Datetime gave me some trouble in my previous project as well.-(


    Even more on DateTime...



    I thought I’d promote some of the discussion from a recent blog entry to the main feed as others may find it interesting…  As Mark Treadwell says, it is a complicated subject. 


     


    Comment (Markus Reiner):


    Hello,
    we have also problems with DateTime because of using local time. IMHO DateTime should internally use always UTC. Only Parse() and ToString() (the methods converting it for interacting with a user who lives always relativ to local time) should ask the OS and convert it if needed.
    If someone persists a DateTime instance (to a file, to registry and so on) you will always get in trouble! Don't look only at serialization!
    It would be very helpful if we could have a patch for .NET 1.1.


     


    Response (Anthony Moore)


    Markus, thanks very much for the feedback. I have been working on some FAQ entries to answer these questions, which for now I have posed on the BCL Blog:

    http://weblogs.asp.net/bclteam/archive/2004/05/21/136918.aspx

    In short, it is not practical to make a change as substantial as you are recommending to DateTime, either in servicing or in future releases. Believe me, the options have been thoroughly explored, but it is not possible to get acceptable compatibility in terms of both functionality or performance. The first FAQ entry goes into the detail on this issue.

    However, it is possible to serialize DateTime without getting into trouble, so two of the FAQ entries are devoted to recommended ways to serialize DateTime in Binary and Text.

    Thanks very much for your response and I hope this is helpful.

    VS 2005 zone in WindowsForms stie:


    Windows Forms web site has launched a new section for Whidbey, which has a high-level review of Whidbey features.
    Spam in blog, too bad to Roy Osherove:


    Comment spam wave



    I'm getting comment spam (about 50 in the past two hours or so), and for some reason .Text won't let me disable my comments. Already mailed Scott about it but thought maybe anyone had a quick fix for this?

    Friday, May 21, 2004

    This would be helpful to SPS users:


    SharePoint Database/List Best Practices???



    Anyone out there have a reference to what the best practices for programming SharePoint are?  Specifically, how much normalization one should use in their database/lists?  Here's my scenario:


    I'd like to create a Time Off Request and Reporting application. It would have the following operation:



    • Employees would go to a form to request a period or day as PTO

    • Managers would be alerted to the request and either approve or deny it (which would then update the employee

    • When the scheduled day came, the manager would confirm that the employee did or didn't take the day off

    • Payroll would be able to run a report of the data to see who took what time off.  Managers could run the same report for their departments.  Employees could not.

    With a normal database application, I'd have 4 related tables: Employees, Departments, Administrators (but actually, this could be a boolean field for the employee table), and the  PTOData table.  However, I'm not sure if you can write all of these within the context of SharePoint lists.  Anyone have any ideas?  Should I just create separate tables, and only use SharePoint as a wrapper?  Let me know what you think!


    BTW - Dustin - I asked my manager if they'd send me to the dev training.  If I can go, this is something I'd like to cover.  For those of you who also would like to go, but are afraid of asking your boss for a few grand, I can send you my request document (the sucker was 2 1/2 pages long!) as a template.

    Visual Blogger 2004:


    Visual Blogger 2004 released



    Last night Robert McLaws released VisualBlogger 2004. It's getting good reviews from a bunch of blogs. Congrats Robert! I gotta try it out, I hear it works with Radio UserLand too.

    Bill Gates and blog (does he really know about blog?):)


    Gates tells CEOs to blog



    On a day when Bill Gates tells his CEO friends that blogs and RSS are cool, it seems appropriate to link to Dare Obasanjo's "history of blogging at Microsoft" post. Joshua Allen deserves the credit for being the first Microsoft blogger. He took a lot of hard knocks changing Microsoft's culture. Now it's popular to blog at Microsoft (and approved by our top execs). Three years ago that wasn't true at all. It's funny, I remember telling Joshua he was "the face of evil" -- it's interesting how tables have turned. Thanks Joshua!


    Here's the relevant links about Gates talk today:


    Mary Jo Foley: Gates pushes 'power to the people' message.

    Reuters: Microsoft's Gates touts blogging as business tool.

    Transcript and slides from Gates speech today (look for the Channel9 slide!)
    Guardian: It's the human touch that slicker official communications can't match.


    Oh, and BillG: when you gonna blog?

    This is cool!


    Online Book - A .net developer's guide to Windows security



    I "google stumbled" onto an amazing online book by Keith Brown - "a .net developer's guide to Windows security". The whole (in progress) book, including some sample code, is available online. There's even an rss feed with updates.


    This book is a great compliment to "Writing Secure Code". Writing Secure Code tells you how to avoid security mistakes of all types; Keith's book tells you how to work with the Windows security model from .NET. As Keith points out on the book's splash page, the .NET framework doesn't do a good job of abstracting the gory details of the Windows security model, and it can be pretty difficult to find .NET code that calls into the Windows security API's (hello, www.pinvoke.net!).


    So get down and dirty with the SIDs, tokens, profiles, impersonation, priveleges, ACL's, etc. Good stuff.


    And while you're at it, check out Password Minder 1.5 and his other cool security related utilities and samples here.

    Developers, check out these free .NET IDEs:


    Free .NET IDEs



    There has been a lot of talk about how expensive our favorite IDE, VS.NET is right now. Charles assured in one of the replies to the post that the issue is being discussed internally and will be addressed soon. Cool ! Actually, i don't know what stand to take on this issue. Is your productivity important or the one time benefit of buying VS.NET professional edition ? It really is very confusing ...


    Anyway, as our quest for a free .NET IDE continues, here's one to quench that ! Check out Eclipse for .NET ! Infact, i think i picked up this link from one of the replies, but not sure though... Eclipse as most of you would have heard is an awesome product which was developed by IBM and then later opensourced. I have heard quite a lot from fellow Java devs that the IDE is powerful compared to IntelliJ's IDE. Well i'm not the judge in either case but i definitely think that the plugin will help all those cribbing for a good IDE with C# support.


    Again, #develop as many of you already know, is a very flexible IDE completely written in C# which is opensource and freely available. There is rarely something extra needed apart from #develop and ASP.NET Webmatrix for developing WinForm and WebForm code in .NET. What more do you want ?


    And apart from all that, for the most hardcore developer who doesn't care for IDE features, there is one really cool app to write code in C#. Ofcourse it will not work at all for enterprise level apps but for smaller projects, definitely useful. Check out Textpad. FYI, its got syntax highlighting functionality for C# too .. Download the file here.


    I guess, this is a pretty decent list of free IDEs to work on .NET right now. I might have missed a lot of other ones here but these are the ones that stand out quite prominently, i should say :)


    Code on ...

    Wednesday, May 19, 2004

    Nice tip for T-SQL:


    [SQL] Cannot perform an aggregate function on an expression containing an aggregate or a subquery.



    Problem:


    select avg(count(ip)) from pagehits where [month] = 2 group by ip


    will give the following error: “Cannot perform an aggregate function on an expression containing an aggregate or a subquery.” MS SQL Server doesn't support it.


    Solution - use a derived table:


    select avg(ipcount) from (select count(ip) ipcount from pagehits where [month] = 2 group by ip) as sub


    I'm posting this because searches on the error message didn't return good results, so if someone else has this problem (read: when I forget this again) this may save some frustration.





    Tuesday, May 18, 2004

    Video for VB developers:


    101 VB.NET 2003 Videos Released onto MSDN



    Recently we launched a series of videos about VB.NET onto the Visual Basic Developer Center, releasing them only a few at a time... but now we've finished that process and all 101 of the videos are available on the site.



    Just a little note: If you experience problems watching these videos, you may wish to try installing the WMP9 codecs (or WMP9 itself, although that is not a requirement) or following the steps in this KB article.


    Monday, May 17, 2004

    .NET programming in Yukon:


    .NET programming in SQL Server 2005



    Last week, I delivered a session at TechEd Israel on the Yukon CLR.


    Basically, SQL Server 2005 will host the CLR which enables developers to:



    1. Write procedural code (stored procedures, user defined functions, triggers) using any mananged language for which the compiler generates verifyable IL.

    2. Extend SQL Server with User Defined Aggregates - you know, write your own min, max, avg - or user defined data types.

    Except for the user defined aggregates, I covered all of these and showed a simple demo. You can find slides and demo here: http://iw.microsoftwss.be/EYT/HansVBBlogDrops . Look for Dev402 content.


    Especially creating the user defined data type (demo 5) took me some time because I overlooked some simple details:



    1.  My first suggestion is to use Visual Studio to create a UDT. You get a nice template wich alrady implements the Inullable interface.

    2. Then add work on the ToString method and the Parse method but before you test whether this works, you should make sure that the IsNull property of the Inullable interface doesn't always return Null! Apparently this property is checked before the ToString method is called. If your IsNull property always returns null, you will never see the state of your stored instances.

    3. I have a method in method in my UDT called contains number which returns a SqlBoolean. Using this method in your select statements caused me some trouble. Was it because it was getting really late? I tried many things:


    • Declare @value int
      set @value = 42
      Select a::ToString() from demo5
      WHERE a::ContainsNumber(@value) 

    • Declare @value int
      set @value = 42
      Select a::ToString() from demo5
      WHERE a::ContainsNumber(@value) = True

    • Declare @value int
      set @value = 42
      Select a::ToString() from demo5
      WHERE a::ContainsNumber(@value) = 1

    Easy to say afterwards but only the last one worked. I can see why the second doesn't work. But I really thought the first one would have worked as well. Thinking about it a bit earlier on the day, maybe the following would have worked as well. I'm not going to fire up my VPC now, I have other work to do but I'll change this blog entry once I find out.



    • Declare @value int
      set @value = 42
      Select a::ToString() from demo5
      WHERE exists(a::ContainsNumber(@value))

    I'm really looking forward to Beta 2 when the product will be more complete and when there will be a much broader availability of the bits. I'm sure we will get a hot Yukon summer...


    This posting is provided "AS IS" with no warranties, and confers no rights.


     



    SharePoint site updated:


    SharePoint Site Updated on Office.Microsoft.Com



    Pulled this off one of our internal distrubution lists and wanted to share.

     


     

    We've moved a lot of the content that was on the home page to the tech library page, reorganized it a bit, and added some new content, such as:


    • End-user documentation and resources
    • Webcasts
    • Training links to partners that provide training
    • Links to KB articles. There are a lot of good "how to" KB articles out there - I've included them in the IT documentation and resources section - e.g., removing SharePoint Portal Server 2003 manually, renaming a SharePoint Portal Server 2003 computer, moving SharePoint Portal Server 2003 from MSDE to SQL Server.

    Big thanks to Emily Schroeder for making the changes happen!
    This is so cool!


    How to Install VS.NET 2005 Community Tech Preview on Longhorn 4074



    After having a look to the latest release of Longhorn, and wishing to test some of the new features of VS.NET 2005 CTP over the 4074 build, I realized that the installer of VS don't allow to install the CTP version in any version of Longhorn.


    I have been working with MSI files and some time ago used a tool from the Platform SDK  to modify an installation and allow it to install in any host OS. And that's just what I have done with the VS.NET 2005 Installer. I have removed the Launch Condition that checks for a version number different from Longhorn's one. Generated a new MSI file, tried it on my Longhorn 4074 VPC2004, and it perfectly run on it. Have a look to the screen capture:



    I used a patch utility to create an .exe file that will path the vs_setup.msi file of the CTP release. I have only tested that with my patcher, you can install the Visual Studio 2005 on any Longhorn build, but have not checked that it doesn't crashes the system files... So use it at your own risk. I have installed on my VPC, but previously made a backup of the Virtual Disk... :-P


    You can download here the Visual Studio 2005 CTP Patcher to Install on Longhorn


    Please, have a look to the readme.txt file, and enjoy it!!!

    Sunday, May 16, 2004

    Inprove your application performance even more!


    Performant XML: a practical guide



    Oleg mentions
    a must read document from the Patterns
    and Practices
    guys:
    Improving .NET Application Performance and Scalability
    . I'm glad I could
    contribute
     a couple ideas to the
    Improving XML Performance
    chapter.


    When you read
    Compile Both Dynamic and Static XPath Expressions
    section, you'll know
    it's all about 
    dynamic XPath expressions compilation
    and its
    follower enhance
    XPath execution performance with XPathCache
    , both applied and
    available through the Mvp.Xml
    project
    , downloadable from from
    SourceForge
    .

    Saturday, May 15, 2004

    One of the best racing games! :)


    Now, for the people with an XBox...




    ... have you seen the Gran Turismo 4 trailer already? If not, check it out here. As a PS2 and GT3 owner I already knew what kind of quality the name 'Gran Turismo' stands for, but after seeing this trailer... I'm beyond words... Unbelievable, how realistic it looks and acts. Can't wait!

    Note for using lately.


    SQL 101: record count for a procedure



    While I'm not on Skype, sometimes folks will IM me with questions. Just got done with one from Daniel in Germany.


    Question How do you get the number of records that a stored procedure would return without actually returning the result set to the user?


    Answer Answer: Cheat!


    Consider the following meager stored procedure:


    alter procedure dbo.GetBeers

    as

    select BeerID from dbo.Beers


    Here's the cheating bit. I'm actually going to execute that procedure and have the results pumped into a temporary table, which we can then query for the count.


    create table #beercount

    (beerid int)

    insert into #beercount exec dbo.getbeers

    select count(*) from #beers

    drop #beercount


    Brown Rice is, indeed, Ok.

    Friday, May 14, 2004

    Hot and fresh.0)


    Hottest ASP.NET 2.0 Features



    Hey Dino, what are the hottest features in ASP.NET 2.0 that we should consider when we plan upgrades to existing applications?


    All speakers would begin with "Thank you. This is definitely a great question and I'm happy to have a chance to discuss it publicly!" Usually, this sort of stock phrase serves the purpose of taking some time to think and decide where to start from.


    ASP.NET 2.0 counts two types of enhancements: those which require changes to the HTTP pipeline and the page handler and those which are just well-written wrappers around existing functionalities. In my recent Cutting Edge columns, I demonstrate just this. Specifically, personalization, themes, image generation, cache dependency, script callbacks. Paul Wilson and others demonstrated Master Pages.


    Here's my list of the hottest features that might lead you to consider an upgrade:



    • Master Pages

    • Data source controls

    • Session and Cache enhancements

    • Provider model

    • Rich controls

    One of the most frequently asked questions (for me, at least) is "what's the best way to quickly and effectively prototype hundreds of similar-looking pages?" Master pages is the answer. And is a great answer indeed. While master pages can be emulated in 1.x, or maybe implemented through a sort of visual inheritance pattern, in 2.0 you get a system-level solution optimized and integrated with the rest of the framework. And completely hassle-free.


    Data source controls provide a system-level bridge between data-bound controls and data providers. In the field, an extra intermediate layer backing data-bound controls proved necessary. Serious apps already have this custom layer, better yet if connected to a BLL. Again, you now have a system-level solution. And can maintain your BLL intact or just must change the signatures of the methods slightly.


    Session and Cache enhancements provide new features that were hard (not impossible) to accomplish with earlier versions. I'm talking about custom and database cache dependencies; and custom stores for session state. The provider model makes possible now to build robust Web apps with a single database. What if in 1.x you have to work with an Oracle database and need database storage of session state? No way: you must install SQL Server too.


    Rich controls: treeview, menu, wizard, multi-view, plus the family of data-bound view controls. They save you A LOT of boilerplate coding. Hard to believe? Try security controls (Login, password, user) and let me know. 


    PS: Stay tuned to the ASP.NET DevCenter. More on this coming up.

    Notes from Test Driven Development: By Example (Kent Beck)



    I have to admit that as much as I have done Test Driven Development, I have not read Kent Beck’s book all the way through. It certainly has not hindered me, but since I have the book to give away at an upcoming WeProgram.NET meeting on TDD, I figured I’d breeze through it in a couple of hours. Here are my notes, in case anyone finds them useful.


    Notes from Test Driven Development: By Example, Kent Beck



    • There are three methods of going forward when doing TDD: fake it, use an obvious implementation, and triangulation.


      • Fake it is where you just return the exact value you need. If your test expects a zero from a method, use a “return 0;” statement. Usually you use this when you cannot tell how to implement certain functionality, or your previous steps were too large and you cannot figure out what went wrong. Something that works is better than something that doesn’t work!

      • Use obvious implementation when you are pretty sure of the code you need to write, so write it and see if the test passes. The majority of the time you will use this method to move forward with TDD quickly.

      • Triangulation is where you want to generalize a certain behavior, but are not sure how to do it. So you start with fake it and add additional tests that force the code to be more generic along a certain dimension. This is how you test the code’s axes of variance (measure some code’s resilience to change along a specified dimension). For example, to test the money code’s axis of variance for different currencies, Kent added tests for Francs in addition to Dollars.

    • If you inherit code without unit tests, retroactively setup unit tests for the section of code you are working to make sure you don’t introduce any new bugs with your bug fix. Do not attempt to setup unit tests for the entire application.

    • Test Driven Development keeps the developer working at the fastest speed possible for the current conditions. Is the step size feeling too restrictive? Use obvious implementation to take bigger steps and accomplish more with each run of the unit tests suite. Are you getting surprised by red bars? Slow down and try faking it or triangulation and run the test suite more often.

    • Keep a test list. This list should contain three categories of items: new code, refactorings, and new tests. For example, if you think about an extension point (new code) for the code you are working on, write it down but keep working on what you are doing at this instant. Focus is the key.

    • A common mistake is to write tests that pass after the code is written. Don’t do this. Although Kent gives one, rather philosophical reason, my reason is that if it hasn’t failed, you haven’t proved the test works. The test should fail, you should add or change some code, and then the test should pass. This (almost) ensures that the code works and it works the way you think it works.
    This looks interesting. But have not tried yet.


    Q: How do yo change the size of one Winforms application from another in VB.NET?



    A:


            Dim p() As System.Diagnostics.Process


            p = System.Diagnostics.Process.GetProcessesByName("WindowsApplication2")


     


            If p.Length > 0 Then


                Dim res As Integer


                Dim rc As RECT


                GetWindowRect(p(0).MainWindowHandle().ToInt32, rc)


     


                res = MoveWindow(p(0).MainWindowHandle().ToInt32, rc.Left, rc.Top, 100, 100, True)


                System.Diagnostics.Debug.WriteLine(res.ToString)


            End If


     


     


    Where RECT, GetWindowRect, and MoveWindow are declared as:


     


     


        Public Declare Function MoveWindow Lib "user32" (ByVal hwnd As Integer, ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal bRepaint As Integer) As Integer


     


        Public Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Integer, ByRef lpRect As RECT) As Integer


     


        Public Structure RECT


            Dim Left As Integer


            Dim Top As Integer


            Dim Right As Integer


            Dim Bottom As Integer


        End Structure


     


     


    You will see a slight delay between the call and the actual resize.  This is because the amount of time it takes to pass the message to the message pump for the other application but it works just fine unless the 2nd app is overriding the WndProc and handling WM_WINDOWPOSCHANGING message. 


     


    You could also use SetWindowPos instead of MoveWindow if you wanted to get fancy and not have the window repaint or if you wanted to withhold the WM_WINDOWPOSCHANGING message, etc.  See SetWindowPos for more options.


     

    Halo 2 looks cool but sadly I have no XBOX.-(


    Halo 2 = November 9th



    From 1stUp, Halo 2 will be released November 9th. Mark your calendars, and prepare for a 1-2% drop in productivity. 


    There will also be a limited-edition version pre-order version: “Microsoft also confirmed that gamers will be able to pre-order a limited-edition version of the game. The special edition will come packed in a metal box with the game and an extra DVD of new content, including making-of documentaries, DVD-style featurettes on different aspects of the game's development, commentary from members of the development team, cinematics and characters that wound up on the cutting-room floor, and an art gallery.”


    Article on multiplayer Halo 2, Multiplayer videos

    Thursday, May 13, 2004

    ASP.NET Version Switcher, nice tool.


    ASP.Net Version Switcher



    Via Rob I found the ASP.Net Version switcher. Rob claims to use it at least once a day.  - Josh


    From the Official Site: http://www.denisbauer.com/NETTools/ASPNETVersionSwitcher.aspx


    The ASP.NET Version Switcher is a little utility that can be used to quickly switch the .NET Framework version that the ASPX pages are compiled against. This is helpful for developers who often have to test their web applications for compatibility with different version of the .NET Framework

    Internally, it uses the command line tool called ASPNET_REGIIS that is included in the Microsoft.NET Framework.

    Additional features:


    • toggle if only selected vroot should be version switched or child vroots recursively (-s or -sn command line parameter)
    • double click on node opens explorer in respective directory
    • quick link to IIS Manager
    Hot topic: Test Driven Development


    Test Driven Development Article - Applying to a model



    I've been playing around with TDD on our project and it works on some simplistic pieces, but I'm having a difficult time applying it beyond simple smoke tests due to our app. I came across a decent article in MSDN Magazine by Will Stott and James Newkirk last month, but I think the real world application is a little simplistic. I like the concept and the areas where I apply it are useful, but I'm struggling with some more complex situations.


    A large part of our application business objects produce output based on the existing state of the running plant.  What I submit on time(x) is very different than what is applied on time(y).  There is a big value in keeping a known state and testing from that point, however running a series of tests modify the state of that plant.  Therefore the test results aren't predictable due to the tests that ran before.  I'm really limited to doing smoke tests and testing the structure of the data than testing the data itself (i.e. using XSL to determine structural validity). 


    I'm curious if anyone has run into these situations or seen any articles dealing with this type of environment.  All the TDD articles assume, to some degree, a given knowable state that's easy to get back to over the course of testing. 

    I Love OneNote.

    I am using OneNote everyday at work and home. It's so nice for noting down everything I want. Good product from MS.
    About Robot.

    I am evaluating the Rational Robot for my company. There is a big problem confusing me is how to recongnize the non-standard .NET controls? I am looking for answer now. The others of the Rational Robot are okay.
    I've watched the show. Pretty cool!


    .NET Show: Longhorn Avalon




    There’s a new .NET Show on Longhorn Avalon:


    In this episode of the .NET Show David Ornstein and Pablo Fernicola discuss the purpose and benefits of the new graphical model for Longhorn. Later, Rob Relyea and Nathan Dunlap walk through some source code to show how the use of XAML in writing user interfaces for applications can create a better collaboration between designers and programmers. 

    The 802.11 devices may be attacked by the DoS!


    802.11 WiFi flaw discovered...



    The Queensland University of Technology today has announced the discover of a new flaw in 802.11 wireless protocol

    The vulnerability is related to the medium access control (MAC) function of the IEEE 802.11 protocol. Seems that an attacker using a low-powered, portable device such as an electronic PDA and a commonly available wireless networking card may cause significant disruption to all WLAN traffic within range, in a manner that makes identification and localisation of the attacker difficult.

    Not a good news for WiFi I think... a low-powered device can cause DOS problems to a WiFi network? Terrible...

    You can find more info here.

    Wednesday, May 12, 2004

    Cool tip for Adobe Acrobat.


    Adobe Acrobat plug-ins tip



    Here’s a tip from Chris Lieberman, who left a comment on my Make Acrobat Reader 6 load faster blog post:


    To temporarily disable loading of plug-ins in Acrobat 6 press shift key immediately after starting Acrobat.

    Testers are developers as well.


    Why Testers Should Care About Specs



    My team is still bogged down in Spec work, but we're getting close to being done. Over the past few weeks it's gotten pretty old. After all, this stuff isn't really all that fun. A lot of reading, a lot of nit-picky comments, a lot of discussions (sometimes arguments) in meetings. From time to time I wonder why I get so involved. I'm a tester, specs aren't my job right?


    Sure, they're not my primary focus but specs are very important to me in two distinct ways. The first is simple, commenting on and contributing to the spec process is my best chance to add my input into what we build. Later on in the process, when test traditionally gets involved, the direction is set - and won't be changed. But here, early, we're still figuring out what the program is going to do and I get to add my input. This adds a lot of job satisfaction for me. Think about it, I get to have a say in how we build software that hundreds of millions of people will use. Thankfully it's not a very large say and is tempered with lots and lots of other opinions. Otherwise I fear what kind of silliness we would build. The point is that by being involved early in the spec process I get to have personal investment in the product. We all know that in this industry test often isn't given the same respect as development or management teams (yes, this happens at Microsoft too - but trust me when I say it's much, much better here) and by involving myself in the design phase I help close that gap.


    But being involved in this phase is also important from a testing perspective. Here's the scenario: down the line development will be cranking away on some feature, then you'll load that code up and start testing it. You'll find something you think they did wrong and go talk to them, they'll say they did it right. You're now at an impasse. I guarantee this will hapen at least once in any product cycle you're ever involved in.


    The easiest way to solve this problem is to go look at the spec. If the spec is sufficiently clear and detailed (as it should be for any user exposed features) you can use it to settle the disagreement. If the spec isn't sufficiently clear and detailed things will get ugly - you'll need some meetings, and some mediation by your management teams, and all kinds of other badness. And like everything in software, solving these problems earlier (like when the spec is written) is much cheaper then solving them later. Plus, with good work on the spec up front you can prevent lots of these misunderstandings from even coming up in the first place.


    Developers should really be holding the line on this while the specs are being written. They should be in there demanding more detail. But in my experience they don't do this. In their heads they're already working on how to implement the feature. It gets hard to see the different ways something in the spec could be interpreted when you've already interpreted it yourself and started a plan for implementation. But it turns out testers are excellent at interpreting things all kinds of different ways, it's one of the things that makes us good at what we do.


    So as a tester my job in the spec writing process is to keep pushing for clarity and specifics. Keep asking hard questions to be sure everyone is interpreting things in the same way and there isn't room for ambiguity. The more specific the spec, the easier our lives are down the road, and our overall cost is cheaper. It's just a hard process, so when I'm in it I have to keep reminding myself why it's needed.


    With that, it's time to get back at it.

    Why your last software project failed? Learn from this:

    Software Estimation webcast notes



    Notes from the Software Estimation webcast.



    “The gap between the best software engineering practice and the average practice is… perhaps wider than in any other engineering discipline.”
    Fred Brooks



    Only 32% of projects were less than 20 percent late (including on-time). Average software project is 100 percent late (takes twice as long as expected).
    Standish Group


    Three parts to project success:



    • Good target setting – statement of real business need
    • Effective control – good project management controls
    • Accurate estimates – focus of the rest of the webcast

    Understanding an Estimate’s Value

    Why estimate?



    • Provides info on how many resources and how long it will take
    • Provides info on the risk/reward of a project
    • Insight into kinds project risks

    Estimate Value



    • Is a function of the potential gain if correct and potential loss if incorrect
    • Have to balance the investment you put into an estimate with the value you get back

    Average companies treat estimation as a black art. Best companies treat estimation as a specialized skill.


    Embracing Uncertainty

    Software developers generally need precision.


    “Perfect is the enemy of the good!”


    Just because it’s not precise does not mean it’s not valuable.


    Cone of Uncertainty


    Cone of Uncertainty


    Average company practices:



    • Give precise estimate/commitment
    • Estimate once and never change it
    • Spend too much time estimating early when little info is available

    Best company practices:



    • Provide estimates in ranges that reflect uncertainty
    • Use low-cost, low-fidelity methods at wide end of cone
    • Re-estimate as the cone narrows

    Learn to Think in Size

    How big is the project?


    Estimation Workflow



    • Size -> Effort -> Schedule
    • Test of estimate: would you be willing to risk your job?

    Size Measurements



    • Lines of code
    • Function points
    • Screens, reports, tables
    • Other (web pages, GUI components, classes)
    • What works best for you?

    SLOC (source lines of code) - has many faults, but can still be useful:



    • Easy to collect
    • Nearly all estimation tools are based on SLOC
    • Effort per SLOC roughly constant across languages

    Average companies:



    • Think in terms of effort and schedule, not size
    • Estimates based on gut feel than data
    • Create estimates that are hard to defend

    Best Companies:



    • Use multiple size measurements
    • Use tools to help think in size
    • Able to defend estimates with data based on size measurements (i.e., XL modules = 10,000 LOC, which then takes x amount of time)

    Collect and Use Historical Data



    • The use of historical data is the biggest differentiating factor between successful and unsuccessful estimation.
    • Use historical data to compute effort, then use historical data to compute schedule. An analytical process removes the emotion.
    • Productivity is an organizational characteristic that cannot be changed significantly from one project to another. Past performance is the best indicator of future performance.

    For each project, the following is the minimum:



    • Collect size measurements (SLOC, FP, etc.)
    • Effort (staff months)
    • Time (calendar months)
    • Defects
    • The key is to be consistent across projects!

    Can collect additional data that is more specific on each of the above.


    Haven’t collected any data? Go back and “mine” it or estimate it.


    Average companies:



    • Never collect historical data
    • Never learn from past experience
    • Repeat the same estimation errors over and over

    Best companies:



    • Collect historical data from every project
    • Analyze data to learn from it
    • Improve ability to estimate over time, and prove it

    Establish an Estimation Procedure


    Benefits



    • Encourage uniform results
    • Allows retracing steps in case of failure
    • Protects against biases
    • Ensures proper use of historical data
    • Aligns expectations between estimate producer and estimate customer

    Elements



    • Required and optional steps
    • Description of each step’s imprecision
    • Standard re-estimation points
    • How to combine multiple approaches (look for convergence)
    • Defines when an estimate becomes a commitment
    • Changes approaches depending on location in cone of uncertainty

    See presentation for a detailed description of a “best in class” example.


    For More Info


    This Blog Hosted On: http://www.DotNetJunkies.com/