Galin Iliev's blog

Software Architecture & Development

WeakReference ?!? Do we have strong one ?!

Have you used WeakReference class? I am sure you, probably, have in connection to GC and Memory Management in .NET (MSDN Magazine Article: Part1 and Part2). Especially if you have written complicated cache mechanisms. ASP.NET cache uses it internally.

It is very convenient because you can have the reference to some object and still allow this object to be collected by Garbage Collector (another description here) or in other words (according MSDN) "Represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection."
Here is one example from MSDN Magazine;

   1:  void Method() {
   2:     Object o = new Object();    // Creates a strong reference to the
   3:                                 // object.
   4:   
   5:     // Create a strong reference to a short WeakReference object.
   6:     // The WeakReference object tracks the Object.
   7:     WeakReference wr = new WeakReference(o);
   8:   
   9:     o = null;    // Remove the strong reference to the object
  10:   
  11:     o = wr.Target;
  12:     if (o == null) {
  13:        // A GC occurred and Object was reclaimed.
  14:     } else {
  15:        // a GC did not occur and we can successfully access the Object 
  16:        // using o
  17:     }
  18:  }
  19:   

Here is another example how can be used.

But how does it work? Here is good explanation.

To fully understand how weak references work, let's look inside the managed heap again. The managed heap contains two internal data structures whose sole purpose is to manage weak references: the short weak reference table and the long weak reference table. These two tables simply contain pointers to objects allocated within the managed heap.
Initially, both tables are empty. When you create a WeakReference object, an object is not allocated from the managed heap. Instead, an empty slot in one of the weak reference tables is located; short weak references use the short weak reference table and long weak references use the long weak reference table.
Once an empty slot is found, the value in the slot is set to the address of the object you wish to track—the object's pointer is passed to the WeakReference's constructor. The value returned from the new operator is the address of the slot in the WeakReference table. Obviously, the two weak reference tables are not considered part of an application's roots or the garbage collector would not be able to reclaim the objects pointed to by the tables.

Hope you find it helpful.

P.S. Here are some explanations how can resurrect objects in .NET.

MS SQL Server 2008 Webcast for devs

Here are some interesting webcasts for MS SQL Server 2008 as a platform for application development. These casts could help you to ramp up with the latest stuff around new version of the popular DB server from Microsoft.

  • Building Spatial Applications with SQL Server 2008
    SQL Server 2008 delivers new Spatial data types that enable you to consume, use, and extend location-based data through spatial-enabled applications. Attend this webcast to learn how to use spatial functionality in next version of SQL Server to build and optimize Spatial queries.
    Audience: Mid-Level
    Focus: Spatial Data
  • Entity Framework for Database Administrators
    The Entity Framework is a new data technology from Microsoft that may particularly interest database administrators (DBAs). Watch this webcast to see how this technology can radically change the development of applications from a DBA perspective, and also change access patterns on servers.
  • XML Tools in Visual Studio 2008
    Did you know that the Microsoft Visual Studio development system has great tools to help developers work with XML? Join the XML tools team in this session to learn about the XML tools available today in Microsoft Visual Studio 2005 and the many changes that we are making for Microsoft Visual Studio 2008, in addition to some of our longer term projects.
  • New T-SQL Programmability Features in SQL Server 2008
    View this webcast on new T-SQL programmability features in Microsoft SQL Server 2008, an extension from last year's presentation on top Microsoft SQL Server 2005 T-SQL features. We cover exciting new features such as: New data types (i.e. date/time, filestream, HierarchyID, large UDT, sparse columns), dependency management for database objects, and much more.
  • Programming SQL Server 2008
    Microsoft SQL Server 2008, code name "Katmai," introduces a significant amount of new or improved functionality, including new data types, in addition to performance and security enhancements. In this webcast, we discuss how you can easily take advantage of the new functionality available in SQL Server 2008 within your application development.
  • Microsoft SQL Server 2008: Beyond Relational
    As the data your applications work with changes from “words and numbers” to “sights and sounds”, we are evolving our data platform to go beyond relational data, beyond OLAP, to truly support all of the digital data types of the future. We will strive to deliver the best platform for integrated storage, and advanced applications such as spatial data, while also making it dramatically easier for you to build data-driven applications, without needing to invest significant resources in bridging the gap between data and programming language data structures. Come learn about the new enhancements in SQL Server 2008 that will help you manage all types of data.
    Audience: Mid-level
  • Data Programmability and SQL Server 2008
    A comprehensive data programmability platform enables developers to build data-centric solutions that target desktops, mobile devices, online Web servers, and enterprise servers using a variety of products, programming frameworks, Web services, and data connectivity technologies that work together to access and manage data. Join this webcast as we discuss the new data programmability features that are supported by Microsoft SQL Server 2008.
    Audience: Technical

 

Full list can be found here.

Sample databases can be found on CodePlex

Note: Do not forget - you have to install patches to Visual Studio 2005 and even Visual Studio 2008.

ADO.NET Data Services CTP is released!

ADO.NET Data Services aka Project "Astoria" December CTP is released. Mike Flasko (PM @ Astora team) posted some key points:

The following features are in this CTP:

  • Support to create ADO.NET Data Services backed by:
    • A relational database by leveraging the Entity Framework
    • Any data source (file, web service, custom store, application logic layer, etc)
  • Serialization Formats:
    • Industry standard AtomPub serialization
    • JSON serialization
  • Business Logic & Validation
    • Insert custom business/validation logic into the Request/response processing pipeline
    • simple infrastructure to build custom access policy 
  • Access Control
    • Easily control the resources viewable from a data service
  • Simple HTTP interface
    • Any platform with an HTTP stack can easily consume a data service
    • Designed to leverage HTTP semantics and infrastructure already deployed at large
  • Client libraries:
    • .NET Framework
    • ASP.NET AJAX
    • Silverlight (coming soon)
  • For more information see ADO.NET Data Services official site.

    Meet Microsoft Live Labs Volta

    Here is another codename project from Microsoft that aims at Web UI experience - meet Microsoft Live Labs Volta:

    The Volta technology preview is a developer toolset that enables you to build multi-tier web applications by applying familiar techniques and patterns. First, design and build your application as a .NET client application, then assign the portions of the application to run on the server and the client tiers late in the development process. The compiler creates cross-browser JavaScript for the client tier, web services for the server tier, and communication, serialization, synchronization, security, and other boilerplate code to tie the tiers together.

    Developers can target either web browsers or the CLR as clients and Volta handles the complexities of tier-splitting for you.  Volta comprises tools such as end-to-end profiling to make architectural refactoring and optimization simple and quick. In effect, Volta offers a best-effort experience in multiple environments without any changes to the application.

    Programming model:

    In essence Volta is a recompiler. Volta works on MSIL rather than on a textual source language. Volta rewrites MSIL into any number of target languages, including, today JavaScript and MSIL itself. Rewriting, as a general technology, lets us delay permanent decisions about architecture, execution platform and browser until after our code is basically working. Furthermore, it frees us from having to express all these irreversible decisions in your source code. The result is a programming model that enables us to easily reshape a working application, and finally realizes the promise of one application running anywhere.

    Volta effects recompilation through 3 general capabilities: refactoring, retargeting, and remodulating. Refactoring converts single-tier code into distributed, concurrent code as directed by user-supplied annotations. Retargeting converts MSIL code into code for other virtual machines. Remodulating tailors a single piece of code for multiple browsers. The next 3 sections explain in more detail.

    See detailed architectural and fundamental description here.

    Links:

    "Internet Explorer cannot open the Internet site", "Operation aborted"

    If you're web developer and write JavaScript/AJAX-driven web sites you probably have seen such message (in IE of course)... If you haven't seen it yet just save this as html file and open it in IE:

    <html>
    <head>
        <script type="text/javascript">
        function appendToBody() {
            var span = document.createElement('span');
            document.body.appendChild(span);        
        }
        </script>
    </head>
    <body>
        <form>
            <script type="text/javascript">
                appendToBody();
            </script>
        </form>
    </body>
    </html>
    
    

    The code is taken from blog post Dealing with IE "Operation Aborted". Or, how to Crash IE.

    So as a rules of thumb for DOM manipulations inside browsers:

    • The problem is you can't append to the BODY element from script that isn't a direct child to the BODY element.
    • Do not place script inside <table> tags.
    • Do not try to manipulate with element in Javascript which are not loaded yet! (e.g div placed on the very bottom at the page and not loaded by browser at the time when JS function is executed).

    These rules can save you many hours of guessing what's wrong...

    IIS7 Administration and Customization talk

    My talk yesterday went well and I think people found it interesting so I've decided to post slides and demo as well as some useful links

    From presentation:

    • Slides - PowerPoint 2007 - (2.4 MB)
    • Demo - VS 2008 project (961 KB)

    Some resources:

    IIS7 talk @ SofiaDev UG

    I am giving a talk this Thursday in front of SofiaDev .NET User group at local Microsoft office at 18:30 local time.

    In the presentation I will show:

    1. New tools in IIS7 as well as new administration options
    2. New tracing and diagnostics options
    3. New integration pipeline
    4. Deep example that:
      • use custom IIS module written in C#
      • extend IIS configuration schema
      • extend IIS Manager by adding UI component

    If this sounds interesting to you and you want to attend write to branimir _ at _ sofiadev dot org

    See you there!

    SQL 2005 Database mirroring

    I had interesting case last week - I had to setup SQL 2005 database mirror. First it sounded as piece of cake - I had to follow steps and recommendations as described in SQL Server Books Online (and here). My goal was to setup DB mirror of type High safety with automatic failover (synchronous).

    I had to prepare SQL Instances as:

    1. Create a user (called SqlService in my case) with same password on all machines that will participate in the mirror. Give it enough rights to it. (I put it in Administrators group and denied local login. Later I set more granular security to it)
    2. Setup instances to run in this user context
      image
    3. Set trace flag 1400 as startup parameter to SQL instance
      image

     

    Then I followed How to: Prepare a Mirror Database for Mirroring (Transact-SQL) and when it came to setup DB Mirror it was created... But although I had witness server I was unable to test automatic failover. More precisely I set a connection string of type (

    "Data Source=myServerAddress;Failover Partner=myMirrorServer;Initial Catalog=myDataBase;Integrated Security=True;"

    ) to a simple web application but when I stopped the instance that hold Principal database the mirror database didn't became principal as expected.

    Note: This test was done on SQL 2005 Standard Edition with SP2 on Windows 2003 Standard with the latest updates.

    I decided to test this on SQL 2005 Standard (with no SP2) in Win2003. And it worked. I applied SP2 then and I as able to setup DB mirroring again and everything worked as expected - even automatic failover.

    Bottom line: Somehow SQL 2005 SP2 break DB mirroring if installed right after SQL Server installation. This was my experience and I if someone has another experience with this I would be grateful if we can discuss here

    Useful links:

    Hope this helps!