Latest Media Work for the 'District 9' Movie in Silverlight 3

tangentux

Click here to watch

Please Subscribe to watch in iTunes, etc.

Subscribe to our Podcast

 

What we do: We empower your content with amazing user experience while helping you manage and publish to the widest possible audience with minimal effort.

Cloud computing has made this all possible and we leverage it to the max

  • By using Media RSS we can now deliver on the true promise of the highest quality and easiest user discovery
  • For example only one Media RSS stream is driving everything you see as content here. We handle integrating with all of the complex metadata to seamless 'just work' in almost any environment.
  • We are one of the first to support all existing HD and non-HD formats as well as the emerging and compelling Smooth Streaming formats including Deep Zoom navigation (click to see what the Hard Rock Cafe achieved)
  • We are the first company to deliver this for complex media. See our example here
  • With our single stream we are driving media to iTunes podcasts, Cooliris, Zinc, and even the mass market locations like YouTube.We do all of this with the latest high definition support and just one source.
  • Expect EXPONENTIAL speed improvements (via the cloud-integrated Content Delivery Network)
  • High Definition is now possible for anyone at the levels previously reserved for a handful (Amazon-Google levels we bring to anyone)

Unexpected freedom and immediate access to all this with no special contracts or incremental effort

You do not have to pay a cent up front. You immediately upgrade for free and then pay as you go starting weeks later.

We integrate content encoding, Podcast management and distribution, CDN deployment for amazingly fast consumer speeds, streaming media formats, new content creation, live presentation services, Synchronization - such as presentations with PowerPoint slide integration.

We get you to global best-practices in media With minimal effort or cost

Right now

Just explore what we publish such as our District 9 and DeepZoom examples. And we are not a content provider (!).

Imagine how fast and easy we can improve your exposure at nearly zero cost.

codeplex

Update Cloud Deployed Silverlight 3 Media Server Location

 http://media.tangentux.com/index.htm

 One of the most compelling real-time deep-zoom integrated media engines on the planet (if not the only?).

 

 

New Silverlight 3 Release - HD Media Platform for Universal Broadband Streamed over Cloud Channels

 

http://media.tangentux.com/index.htm

 

 

For your enjoyment. Here is a demo of our recently released media framework for all things High Definition, smooth streamed, zoomed and synced in real-time at the highest quality and speed.

 

 

 

 

Silverlight 3 Beta Really Does Play Adobe Video Content

 

Things just got vastly more interesting on the RIA front, especially for HD Video and Digital Media in general. Why?

http://www.tangentux.com/

 

Adobe has no reason to ignore Silverlight now…They do that at their own peril and eventual harm.

Silverlight 3 beta is out.


Hardware Accelerated
Silverlight 3 Adobe Video
Media Player

Oh and also Windows Media including the
latest Smooth Streaming from IIS 7.

I’ve become a kind of hyper-specialized developer, the kind I used to say were outdated due to the need for ‘everyone to know everything’ as teams are so much smaller..

What I mean is all I do is Silverlight, and even more specifically the latest bleeding edge crazy HD video synced to Deep Zoom back to live broadcasts… I was wrong about generalization. Instead we went the other way, with an insane positive bias on those of us making pretty things on the screen (the economy makes other ‘cannot see’ work perhaps much less able to secure funding….

Anyway I dove in with Silverlight 3.. Big time. Check out this Adobe video player in Silverlight (the first I have ever seen and believe me I looked hard)…

 

 

 


Digg This
Advanced Bidirectional Silverlight 2.0 to ASP.NET Integration – Part 1

kick it on DotNetKicks.com

Digg This

Silverlight_Logo_2

This is the first post covering techniques for both sending data into your Silverlight environment from ASP.NET as well as getting data out of Silverlight without resorting to a lot of new elements in your architecture. The goal is to use what you already have with the least fuss.

You may think you need to resort to ‘pushing’ all data from Silverlight into say a service using WCF but that is not the case in many scenarios.

For example, you may have activity which the user creates inside Silverlight 2.0 that results in visual elements you want to send out to ASP.NET for persistence in your ORM environment (where Silverlight has no involvement).

From ASP.NET to Silverlight 2.0

First, let’s quickly review the easiest way to pass information into your Silverlight control.

InitParamaters

Here is the on-line help:

If parameters are included, they are typically in comma-delimited pairs and are available as a dictionary object in a Silverlight 2 startup event. These parameters are not used in a Silverlight 1.0-based application.

If an action on an .aspx page causes a postback to occur, the Silverlight plug-in will start again with its content specified in the Source property. The current value of the InitParameters property is sent to the Silverlight plug-in. This enables you to change the InitParameters property before a postback occurs.

The Silverlight 2 application specified in the Source property can access the initialization parameters specified in the InitParameters property in the StartupEventArgs parameter of the Silverlight Application Startup event.

We will walk through an entire example of this, including some content that will make sense in how we can move data back out of Silverlight 2.0 to ASP.NET.

Code for this Scenario

We will be using a web UserControl (.ascx) as our control in this example, because as you will see, we need more than just the Silverlight control to make this work.

ASCX Host

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SilverlightInt.ascx.cs"
  Inherits="SilverlightInt" %>
<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
    TagPrefix="asp" %>
<asp:Silverlight ID="SilverlightView" runat="server" Source="~/ClientBin/AspNetIntegration.xap"
    MinimumVersion="2.0.31005.0" />
<asp:TextBox ID="SilverOutput" runat="server"   Style="display: none"></asp:TextBox>

ASCX Code Behind

    public partial class SilverlightInt : UserControl
    {
        [Browsable(true)]
        public String InitialText { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            SetSilverlightInitParamaters();
        }

        void SetSilverlightInitParamaters()
        {
            // Note: We need the client ID for later...
            var InitParams = new Dictionary<String, String>
                             {
                                 {
                                     "outputcontrol",
                                    SilverOutput.ClientID
                                     },
                                 {
                                     "InitialText",
                               InitialText ?? "Hello World"
                                     }
                             };

            SilverlightView.InitParameters =                   InitParams.ToSilverlightInit();
        }
    }

You might notice the extension method ToSilverlightInit(). Here is the code:

 public static class SilverlightIntegrationExtensions
    {
        /// <summary>
        /// Parse the dictionary into Silverlight format
        /// for InitParams
        /// </summary>
        /// <param name="target">The target.</param>
        /// <returns></returns>
        public static String ToSilverlightInit(                 this IDictionary<String, String> target)
        {
            if (target == null)
                throw new ArgumentNullException("target");

            var stringBuffer = new StringBuilder();

            foreach(var kvp in target)
            {
                if (stringBuffer.Length > 0)
                    stringBuffer.Append(",");

                // Eliminate case sensitivity
              stringBuffer.Append(kvp.Key.ToLower() +                    "=" + kvp.Value);

            }

            return stringBuffer.ToString();

        }

    }

This is hosted in a normal ASPX page as follows (surrounding detail omitted):

  <form id="form1" runat="server" style="height: 100%;">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <asp:Image Width="300px" ImageUrl="Silverlight_Logo_2.png"
           runat="server" />
        <br />
        <asp:Literal ID="sentText" runat="server" /><br />
        <hr />
        <integrate:SilverlightInt ID="SilverlightInt1"
           runat="server"     InitialText="This is a Test" />
    </div>
    </form>

Here is what it looks like:

image

Silverlight Code for Initialization

 public partial class App : Application
    {
        public App()
        {
            Startup += Application_Startup;
            UnhandledException += Application_UnhandledException;
            InitializeComponent();
        }

        void Application_Startup(object sender, StartupEventArgs e)
        {
            var PassedInArguments = e.InitParams;
            RootVisual = new SilverlightView(PassedInArguments);
        }

The interesting parts are that we are accessing the InitParams off the Startup’s ‘e’ object. This is a Dictionary<String,String> which is what prompted the ASP.NET design.

Also, we do not use a paramaterless constructor on the initial RootVisual. Instead this is the code:

Silverlight View

<UserControl x:Class="AspNetIntegration.SilverlightView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid HorizontalAlignment="Left" VerticalAlignment="Top"
       x:Name="LayoutRoot" Background="Gray">
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition Height="30" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="150" />
        </Grid.ColumnDefinitions>

        <TextBlock HorizontalAlignment="Center"            VerticalAlignment="Center"
             Grid.Row="0" Text="Inside Silverlight" />
        <TextBox LostFocus="SendResultBackToAspNet" Grid.Row="1"
          BorderThickness="2" BorderBrush="Black"                 x:Name="initialText"  />

    </Grid>

</UserControl>

Code Behind

public partial class SilverlightView : UserControl
    {
        readonly IDictionary<string, string> _initParamaters;
        string _initialText =                "Nothing was Passed In - initialtext was empty";

        public SilverlightView(              IDictionary<string, string> passedInArguments)
        {
            _initParamaters = passedInArguments;
            InitializeComponent();
            Loaded += OnLoaded;
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            SetInitialText();
        }

        void SetInitialText() {

            if (_initParamaters.ContainsKey("initialtext"))
            {
                _initialText = _initParamaters["initialtext"];
            }

            initialText.Text = _initialText;
        }

        void SendResultBackToAspNet(object sender, RoutedEventArgs e)
        {

        }
    }

Notice the ‘SendResultBackToAspNet’ is empty.. That is coming next and is the tricky part.

Coming Next

The code will all be available for download and the much more interesting aspect of sending data back the other way will be presented.

Damon

Digg This
C# Delegate Shortcut – No more null testing on events for subscribers

kick it on DotNetKicks.com

This is fairly well known but I realized I hadn’t seen it blogged about (sorry if already covered).

Your likely used to doing this:

  public event EventHandler<AnimationImageEventArgs> AnimationImageClicked;

       


 private void OnClick(object sender, AnimationImageEventArgs e)
     


   {
        


    if (AnimationImageClicked != null)
      


          AnimationImageClicked(sender, e);
     


   }

No need for that null check. I for one tend to forget them in the bowels of my teams code. What is better then eliminating the issue!

This is a way to ‘always have one subscriber’ which you can consider a sort of ‘null object’ pattern implementation for delegates. Checking for null just sucks and I love this kind of ubiquitous removal of it.

The first person I saw doing this was Juval Lowy, the master craftsman for basically all things .NET but known recently for utter mastery of WCF in his books and at his firm IDesign. Highly recommend all his writing, code samples and thoughts.

 public event EventHandler<AnimationImageEventArgs> AnimationImageClicked = delegate { };

        


private void OnClick(object sender, AnimationImageEventArgs e)
      


  {
     


           AnimationImageClicked(sender, e);
     


  }

Damon

Deep Zoom in 3D? See it here

Long story short, this is an effort to bring RIA to the SharePoint world.

But not just RIA style usability, I believe we pushed the envelope even further by incorporating not only DeepZoom (SeaDragon) for ‘zoom in to the pixel’ resolution, but the 3D extensions not present by default

(you have the essentials but only the amazingly talented people behind the Hard Rock Memorabilia site (vertigo) have shown this style of combined zoom/3d that we have seen in any largely deployed sample).

click.me

SharepointZoom3d

Click the image here to launch the Silverlight 2.0 cross-platform goodness.

NOTE: A prize goes to the first person to email us at: innovate@domaindotnet.com the exact number of seconds it would take to complete the ‘applying attributes’ to the .gif file (you need to see the demo to understand).

Related Posts

from tag wcf

from tag WCF

from tag silverlight

from tag SOA

from tag sharepoint

from tag Linq

(more..)

SharePoint MOSS 3D

a PowerPoint document in our breakthrough navigation and discovery technology

Damon Wilder Carr
domain.dot.net team labs
Live Proof of Concept: Core Engine for Sharepoint Taxonomy Navigation with Silverlight & WPF/XAML Deep Zoom in 3D

 

Click here to see it live


For the Video Version (above requires .NET 3.5 SP1 Client Subset at least) click here

  image

 

This proof of concept gets us around a few hurdles we were struggling with to deliver a ‘Google Earth’ style view but into a ‘company as the earth’. In our opinion, you can navigate to almost any spot on the planet so why is it so hard to find documents?

For those invested in document management, categorization and meta information addition (part of building the taxonomies) the piece we found missing was a ‘modern’ way to navigate, discover, filter, pattern match, etc. all that semi-structured data.

    

 

Digg This
Use JQuery. It’s Officially Supported Now!

http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx

The jQuery intellisense annotation support will be available as a free web-download in a few weeks (and will work great with VS 2008 SP1 and the free Visual Web Developer 2008 Express SP1).  The new ASP.NET MVC download will also distribute it, and add the jQuery library by default to all new projects.

We will also extend Microsoft product support to jQuery beginning later this year, which will enable developers and enterprises to call and open jQuery support cases 24x7 with Microsoft PSS.

Going forward we'll use jQuery as one of the libraries used to implement higher-level controls in the ASP.NET AJAX Control Toolkit, as well as to implement new Ajax server-side helper methods for ASP.NET MVC.  New features we add to ASP.NET AJAX (like the new client template support) will be designed to integrate nicely with jQuery as well. 

We also plan to contribute tests, bug fixes, and patches back to the jQuery open source project.  These will all go through the standard jQuery patch review process.

Impressed am I.


Technorati Tags: ,
del.icio.us Tags: ,
Digg This
Expose New Linq Operations from the Screaming HashSet<T> Collection

 

Linq is not just about databases. It’s about reading the registry, your hard-disk, or even a list of function pointers to be invoked. Linq is about more even then sets (collections). It’s about making tasks easier in many cases and vastly more powerful (and most importantly your code more readable and maintainable at the same time).
premature_optimization

It’s astounding just how fast the HashSet<T> collection is.

This post will show how to gain additional power that is fully supported from Microsoft which is often overlooked, yet it can solve some of the hardest problems (especially around performance however don’t prematurely optimize!).

 
There are tons of cases where we need a real powerhouse to manage super-large sets (in this example we will use the registry). An entire part of the registry actually.

Here is the API we want to use to query the HKLM part of our registry:

            var FindFontsColors = from rk in RegistryServer.Hklm
                                  where
                                          rk.Name.Contains("VisualStudio") &&
                                          rk.Name.EndsWith("FontsAndColors") &&
                                          rk.ValueCount > 0


                                  select rk.Name;

    • The core win here is 'ease of development and maintenance’ without the typical trade-off
      in performance. The entire equation is shifted actually so the tradeoff becomes irrelevant.
    • Sure you could do this with a lot more code perhaps even a few ms faster. But at what real cost over the life of your code?
    • The entire point of this post is the far greater win in maintenance and ease of understanding, without the assumed loss of things like performance.

 

When there is no intelligence available on a ‘back-end’ to parse your requests, yet you need the power of finding complex conditional results and much more, there is one recently introduced superstar that is often not described in terms of Linq:

HashSet<T>

Let’s start with some code. You know you can call ToList, ToArray, ToDictionary & ToLookup on your collections (we’ll call them Sequences to stay in line with Linq terms).

  • You will see ‘sets’, ‘collections’ & sequences used together in documentation today. The differences are mostly academic, however the HashSet does illustrate some of those semantic differences which we point out.

We are going to add an extension method to provide us a ToHashSet capability off any IEnumerable<T> (in exactly the same implementation style Microsoft used internally).

Here is how we gain access to this type in the easiest way:

    using System;
    using System.Collections.Generic;

    /// <summary>
    /// This extension method class will add a ToHashSet<typeparamref name=">"/> 
    /// in exactly the same way it is provided by the others:
    /// 
    /// ToList(), ToArray(), ToDictionary().. Now ToHashSet() is available
    /// </summary>
    public static class HashSetLinqAccess
    {
        public static HashSet<T> ToHashSet<T>(this IEnumerable<T> fromEnumerable, 
            IEqualityComparer<T> comparer)
        {
            if (fromEnumerable == null)
                throw new ArgumentNullException("fromEnumerable");

            if (comparer == null)
                comparer = EqualityComparer<T>.Default;

            return !typeof(HashSet<T>).IsAssignableFrom(fromEnumerable.GetType())
                           ? new HashSet<T>(fromEnumerable, comparer)
                           : (HashSet<T>)fromEnumerable;
        }

        public static HashSet<T> ToHashSet<T>(this IEnumerable<T> fromEnumerable) {

            return ToHashSet(fromEnumerable, EqualityComparer<T>.Default);
        }
    }

Ok so what are we going to do with the HashSet<T> and why?

The benefit comes when we have in-memory large sequences to deal with. I will be using the following code as the ‘server’ here. This is code that provides a ‘Registry Server’ to our application. We will populate up a HashSet<T> with RegistryKey instances and then see just how fast it is.

In the next post we will cover all of the additional methods the HashSet<T> exposes.

Here is the code for our Registry Server. NOTE: Please do not try to modify this to change your registry unless you know what you are doing. This is an immutable (read-only) projection from the registry for a very good reason: You can thrash your machine otherwise.

 

------------------------------------------------------------

namespace domaindotnet.LinqToRegistry {
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.CompilerServices;
    using System.Threading;
    using Castle.Core;
    using LinqToCore;
    using Microsoft.Win32;

    /// <summary>
    /// Provider immutable projections from the registry
    /// of the machine, as well as events for status and errors
    /// via a singeton wrapper on the .NET Registry
    /// singleton.
    /// Here we are only exposing the HKLM area
    /// subkey but you can see it is easily extensible
    /// </summary>
    public class RegistryServer : IEqualityComparer<RegistryKey>, IInitializable,
                                  IEnumerable<RegistryKey> {
        // IInitializable is from Castle.Core Contractually
        // saying we need a call on our Initialize() method
        // before we can be given out as a service to 
        // others

        private static readonly RegistryServer _instance;
        private static int iCounter;
        private HashSet<RegistryKey> allKeys;
        private PopulateProgressEventArgs eventArgStatus;
        private bool isInitialized;
        private PopulateProgressDelegateError populateError;
        private PopulateProgressDelegate populateEventOk;

        static RegistryServer() {
            _instance = new RegistryServer();
        }

        private RegistryServer() {}

        public static long Count {
            get {
                if (!_instance.isInitialized)
                    throw new InvalidOperationException(
                            "Please initialize the backing store first");

                return _instance.allKeys.Count;
            }
        }

        public static RegistryServer Hklm {
            get {
                if (!_instance.isInitialized)
                    throw new InvalidOperationException(
                            "Please initialize the backing store first");

                return _instance;
            }
        }

        #region IEnumerable<RegistryKey> Members

        public IEnumerator<RegistryKey> GetEnumerator() {
            if (!isInitialized)
                throw new InvalidOperationException(
                        "Please initialize the backing store first");

            return allKeys.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        #endregion

        #region IEqualityComparer<RegistryKey> Members

        /// <summary>
        /// If either contains a null, the result is false (actually it is
        /// null be we do not have that option. It is 'unknown and indeterminant'.
        /// An emptry string however is treated as 'known to be empty' 
        /// where null is 'could be anything we have no idea'.
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool Equals(RegistryKey x, RegistryKey y) {
            return x.Name != null && y.Name != null && x.Name == y.Name;
        }

        /// <summary>
        /// For null names here we will calculate a funky random number
        /// as null != null
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int GetHashCode(RegistryKey obj) {
            return obj.Name != null
                           ? obj.Name.GetHashCode()
                           : RuntimeHelpers.GetHashCode(new object());
        }

        #endregion

        #region IInitializable Members

        void IInitializable.Initialize() {
            Initialize();
        }

        #endregion

        public static event PopulateProgressDelegate PopulateProgress {
            add { _instance.populateEventOk += value; }
            remove { _instance.populateEventOk -= value; }
        }

        private void InvokePopulateProgress() {
            var PopulateProgressDelegate = _instance.populateEventOk;
            if (PopulateProgressDelegate != null) {
                eventArgStatus.ItemCount = Interlocked.Increment(ref iCounter);
                PopulateProgressDelegate(this, eventArgStatus);
            }
        }

        public static event PopulateProgressDelegateError PopulateProgressItemError {
            add { _instance.populateError += value; }
            remove { _instance.populateError -= value; }
        }

        private static void InvokePopulateProgressItemError(PopulateProgressEventArgs args) {
            var PopulateProgressDelegateError = _instance.populateError;
            if (PopulateProgressDelegateError != null)
                PopulateProgressDelegateError(_instance, args);
        }

        public static void Initialize() {
            Initialize(Registry.LocalMachine);
        }

        private static void Initialize(RegistryKey RegistryStartKey) {
            if (_instance.isInitialized)
                throw new InvalidOperationException(
                        "Already Initialized. Cannot perform twice");

            _instance.eventArgStatus = new PopulateProgressEventArgs();

            _instance.allKeys = GetAllSubkeys(RegistryStartKey, "").ToHashSet(_instance);

            _instance.isInitialized = true;
        }

        private static IEnumerable<RegistryKey> GetAllSubkeys(RegistryKey StartkeyIn,
                                                              String NodeKey) {
            _instance.InvokePopulateProgress();

            if (StartkeyIn != null) {
                RegistryKey SubItemRoot;

                if (TryOpenSubKey(StartkeyIn, NodeKey, out SubItemRoot)) {
                    yield return SubItemRoot;

                    foreach (var sub in

                            SubItemRoot.GetSubKeyNames().SelectMany( // Recursion back into this method
                                    s => GetAllSubkeys(SubItemRoot, s)))

                        yield return sub;
                }
            }
        }

        private static bool TryOpenSubKey(RegistryKey StartFrom, String Name,
                                          out RegistryKey itemOut) {
            var bIsOK = false;
            itemOut = null;

            try {
                itemOut = StartFrom.OpenSubKey(Name,
                        RegistryKeyPermissionCheck.ReadSubTree);
                if (itemOut != null)
                    bIsOK = true;
            }
            catch (Exception ex) {
                InvokePopulateProgressItemError(new PopulateProgressEventArgs(-1,
                        ex.Message + Environment.NewLine + "Key=" + StartFrom.Name + " failed trying " + Name));
            }

            return bIsOK;
        }
                                  }

    public delegate void PopulateProgressDelegateError(
            object sender, PopulateProgressEventArgs args);

    public delegate void PopulateProgressDelegate(
            object sender, PopulateProgressEventArgs args);
}
 
namespace domaindotnet.LinqToRegistry {
    using System;

    /// <summary>
    /// Simple EventArg for the two progress events
    /// 
    /// NOTE: There will typically be some errors
    /// which is fine as some parts of the Registry are
    /// not accessible with standard security
    /// </summary>
    public class PopulateProgressEventArgs : EventArgs {
        
        private readonly string _keyName;

        public PopulateProgressEventArgs(int itemCount) : this(itemCount, null) {}

        public PopulateProgressEventArgs(int itemCount, String KeyName) {

            ItemCount = itemCount;
            _keyName = KeyName;

        }

        public PopulateProgressEventArgs() : this(-1, null) {}

        public string KeyName {
            get { return _keyName; }
        }

        public int ItemCount { get; internal set; }
    }
}

 

Although not required, if you want to use this Registry Server (it makes a fantastic ‘mock’ server – although not really a Mock at all) put all the code above in a separate assembly for ease of use.

It’s great for trying our many variants of Linq queries over objects (as we do here) as the Registry – although a bit dangerous to muck about with – is a nice hierarchical source with enough interesting turns to make it fun.

In practice we rarely need to change the registry but if we did, it would be though this (we would carefully evolve it so it could perform controlled updates).

 

The Regression Tests

 

So we are using xUnit because we like it. Use whatever you want. The code shown next is the abstract base class our real test cases will use:

 

namespace LinqToORMValidation {
    using System;
    using domaindotnet.LinqToRegistry;

    public abstract class BaseTestContext {


        private static void RegistryServer_OnPopulateProgress(object sender, PopulateProgressEventArgs args)
        {
            //Console.WriteLine("Processed " + args.ItemCount + " items");

        }

        private static void RegistryServer_OnPopulateProgressError(object sender, PopulateProgressEventArgs args)
        {
            Console.WriteLine("Error : " + args.KeyName);
        }
        protected BaseTestContext() {

            RegistryServer.PopulateProgress += RegistryServer_OnPopulateProgress;
            RegistryServer.PopulateProgressItemError += RegistryServer_OnPopulateProgressError;
            RegistryServer.Initialize();

            Console.WriteLine("Initialization Complete. Total Records = " + RegistryServer.Count);
        }

    }
}

NOTE: Un-Comment the Console.WriteLine in the OnPopulateProgress to view the status as it runs.

The main area to see is the protected constructor. It’s clear that the Singleton is exposing a separate Initialize() method (we did this on purpose as it can take a little while for all those keys to get inside the HashSet<T> and debugging things if they go wrong in say a static constructor is harder then making a long-running initialization explicit. In general a good design decision we believe.

 

So the final part of code for this post at least is the first test which indeed shows the exact query from the beginning working:"

namespace LinqToORMValidation {
    using System;
    using System.Diagnostics;
    using System.Linq;
    using domaindotnet.LinqToRegistry;
    using Xunit;

    public class RegistryServerValidation : BaseTestContext {


        /// <summary>
        /// As a Linq IEnumerable<T> result
        /// if anything changed, the
        /// underlying HashSet<T> would not change. However if this
        /// were a direct reference to the HashSet the values ARE
        /// changeable. The idea is to project out immutable results
        /// from the Registry server and indeed treat all the data 
        /// as read only
        /// </summary>
        [Fact]
        public void should_prove_basic() {

            // Find the registry key(s) that have 
            // VisualStudo in the name and end in
            // 'FontsAndColors' that also have at least
            // one value defined inside they key


            var sw =Stopwatch.StartNew();

            var FindFontsColors = from rk in RegistryServer.Hklm
                                  where
                                          rk.Name.Contains("VisualStudio") &&
                                          rk.Name.EndsWith("FontsAndColors") &&
                                          rk.ValueCount > 0


                                  select rk.Name;

            var countMatched = FindFontsColors.Count();
           
            sw.Stop();
            
            Console.WriteLine("Total Records Matched = " + countMatched);
            Console.WriteLine("Search Took : " + sw.ElapsedMilliseconds + " ms");
            
            // Assert it took less then one second
            Assert.True(sw.ElapsedMilliseconds < 1000);
            ObjectDumper.Write(FindFontsColors);
        }

 
    }
}

 

 

For this test cases we are very specifically finding any keys across any in HKLM matching the conditions:

  • The key name ‘VisualStudio’ somewhere.
  • The key ends with 'FontsAndColors’
  • The key has at least one value inside (you’ll see why in the next post when things get harder)

We also introduce a time to show off the speed of the HashSet<T>.

 

Here I am making the assumption that the name of the key holds identity, and if null, we use standard null semantics (as defined in relational algebra).

The only few interesting points are the use of the static RuntimeHelpers class from .NET as the fact we are using the singleton static instance as the Equality instance.

 

Running the Code

 

image

As expected we received a few errors, but they make sense as they are protected areas of the registry.

So we matched across 233142 instances of RegistryKey with three conditions in 746ms. Try that in RegEdt32!!

 

MSDN Facts

The HashSet<T> class provides high performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

The capacity of a HashSet<T> object is the number of elements that the object can hold. A HashSet<T> object's capacity automatically increases as elements are added to the object.

The HashSet<T> class is a set collection that implements the ICollection interface and the ICollection<(Of <(T>)>) generic interface.

Set Collections

In mathematics, a set is a collection of distinct objects that is usually defined by a rule that determines whether an element is a member of a particular set. For example, a set could be defined to contain "all the odd numbers between 1 and 21" or the numbers "1, 3, 5 and 7".

The HashSet Class

The HashSet<(Of <(T>)>) class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary<(Of <(TKey, TValue>)>) or Hashtable collections. In simple terms, the HashSet<(Of <(T>)>) class can be thought of as a Dictionary<TKey, TValue> collection without values.

A HashSet<(Of <(T>)>) collection is not sorted and cannot contain duplicate elements. If order or element duplication is more important than performance for your application, consider using the List<(Of <(T>)>) class together with the Sort method.

HashSet<(Of <(T>)>) provides many mathematical set operations, such as set addition (unions) and set subtraction. The following table lists the provided HashSet<(Of <(T>)>) operations and their mathematical equivalents.

HashSet(Of T) operation

Mathematical equivalent

UnionWith

Union or set addition

IntersectWith

Intersection

ExceptWith

Set subtraction

SymmetricExceptWith

Symmetric difference

In addition to the listed set operations, the HashSet<(T> class also provides methods for determining set equality, overlap of sets, and whether a set is a subset or superset of another set.

 

So far this has only set a baseline for the next exploration into these new methods provided in the HashSet<T> you might not have been aware of which we can now easily use:

 

HashSet(Of T) operation

LINQ equivalent

UnionWith

Union

IntersectWith

Intersect

ExceptWith

Except

Not Provided

Distinct

SymmetricExceptWith

Not Provided.

Overlaps

Not Provided.

IsSubsetOf

Not Provided.

IsProperSubsetOf

Not Provided.

IsSupersetOf

Not Provided.

IsProperSupersetOf

Not Provided.

SetEquals

Not Provided.

 

Digg This
Linq to Financial Markets : Optimizing Provider to Real-Time Quotes, Analytics, and Silverlight-WPF Visualization

Announcing a new Optimizing Linq Provider

Technorati Profile

Linq to Financial Markets

The Linq to Financial Markets provider

An easier way to consume, visualize, understand and quantify just about any information you can imagine from the world of global financial services.

  • Real-Time stock quotes to Complex Analytics of Multi-Asset Class Portfolios
  • Monte-Carlo simulation with Optional Quantitative Add-Ins
  • Efficient frontier Optimization based on Constraints you Set
  • User defined heuristics from strategic rebalancing to day-trading

Thanks to Microsoft's Linq technology (introduced in the .NET 3.5 platform), the code in the image above is 100% real. It's well established that by making things easier and more 'declarative' overall productivity goes up, quality improves and most importantly overall maintenance and future extensibility can get the attention they often lack once the non-strategic work is made unnecessary.

In the case above we get the items in our portfolio now priced (using a real-time feed) below their 90 day moving average. You can 'inject' added information as we do above for history. Another option would be to inject some 'predictive' numbers using a simulation technique.

There are many Linq providers, however most are 'technology focused' such as dealing with protocols or platform APIs. We have always been the most interested in solving the harder problems driven from the business perspective. Although there are many technologies involved here, the larger difficulty is making it available in whatever way you would like to see it, across a broad set of dimensions well beyond any technology constraint.

We support more then just 'detail' information, You can use aggregate style commands (say you want to to get you assets for a pie chart that displays asset class holdings in percent). If you then wanted to drill-down, you could use the same asset class information in a 'where' clause to limit the detail to just what you own in that class. But moving well beyond 'SQL' type logic, you can set up monitoring alerts that take action if/when a trigger is met.

The key is the same simple syntax is used for all data providers across all levels of information, including full-text scans and a new feature we're working on now for a future release incorporating an even easier natural language syntax.

This platform is not a fundamentally new way to calculate or retrieve this information. We've had access to many frameworks, API's, data providers, etc. for a long time now.

What this Linq provider does however, it change the dynamics of complexity, time to market, assumed costs in maintenance and testing, and much more. This offering's goal is to make problems in this domain become utterly trivial. Our goal is to empower your team to make trivial what was previously arduous.

You're about to 'declare' what you want, rather then describe each step in the process. If your thinking it looks a lot like 'SQL' you're 100% correct. However SQL could never achieve what Linq provides.

Comparing SQL to what Linq is capable of is like comparing your ability to easily retrieve information from accounting to easily retrieving information from 'anything that is information'.

Due to the nature of the access to this information, we are still working out the details for the open-source version we plan to offer soon. The world of the owners of this data has not caught up to the philosophy we have for transparency and shared value. Send us an email for updates or simply register for the site feed. Also if your in the industry and have an interest we are looking for innovative early adopters. Also, we'll be posting on many of the challenges we faced and a few innovative solutions we applied to the emerging and highly strategic domain of intelligent Linq Parser development.

 

Technorati Profile
Framework API Development Best Practices using C# 3.0

PART 1

image

This content assumes you have an introductory knowledge of C# 3.0 language features in .NET 3.5 and mastery of legacy C# 2.0 Generics, Generic Type Constraints, Anonymous Delegates and related material.

I use a 'pair programming' approach with continued refactoring as this is how I would discuss it if you were coding with me, with an unfortunate one-way delivery.

The Brief Strategic View

Microsoft has slowly been moving C# in a very productive direction (this is not new, as these features existed in 2.0 although not nearly as well integrated) to provide 'Functional Language' features. If you don't know or care about language semantics, just know that Linq and especially Lambada Expressions are about empowering you to use executable code like a variable, aka to leverage the power of functional programming. For more on this, read this MSDN article by Joel Pobar (former CLR Team) or read the next set of posts (part 2 onward) as I will go into the depths of this.

I think of Lambadas as an incredibly focused and powerful domain specific language for delegates.

In this sense they are quite similar to Regular Expressions in that they are really good at their focus area.

What do I mean by good?

  • Terse yet Understandable / Maintainable
  • Syntax tailored to the need, not the other way around.
  • Highly effective for problems that are orders of magnitude more difficult without them (a simple 10% improvement would not cut it)

 

 

 

Painless Intro

 

I'll start with a fairly trivial, yet important example (I use it every day). Many times when comparing Strings I want to ignore case and culture (the InvariantCulture). This is provided by an overload as such as you likely know:

[Test,Category("BaselineCore")]
public void shouldAsserStringCloneInvokeEqual() {

var baselineString = "This is a TEST CASE to IgnOrE Casing";

var stringUpper = baselineString.ToUpperInvariant();

Assert.IsTrue(baselineString.Equals(stringUpper,
                                     
StringComparison.InvariantCultureIgnoreCase));

The test results are shown above. Pass. Ok so I really like short, concise code that is understandable at a glance. Also it's a pain to always (even with ReSharper) use this (and I have seen people use RegEx for this! RegEx is awesome but overkill for this issue).

Refactoring

  • Create an extension method on String
  • Decide on a good name for the method (this is SO important and for most an afterthought!)

I've settled on calling this new method on String 'EqualsCore' as that is what we are doing, making the conditions for a match 'simpler' and seeing 'just the core values' are the same (anyway it makes sense to me)., I suppose this could be 'EqualsRelaxed' or whatever..

Here is the test case (no code yet):

[Test, Category("BaselineCore")]
public void shouldAsserStringsEqualUsingExtension() {
var baselineString = "This is a TEST CASE to IgnOrE Casing";
Assert.IsTrue(baselineString. EqualsSimple(baselineString.ToUpperInvariant())); }

Now we write the code. Here is the container for the extension method:

public static class StringExtensions {

public static bool EqualsSimple(this string sTarget, string compare) {

return sTarget.Equals(compare, StringComparison.InvariantCultureIgnoreCase); }

}

Indeed they both pass:

image25

 

 

 

 

 

Since every type inherits from Object, and Equals is defined on Object, all instances should support this approach, and I could be early bound by using Generics.... Hmm...

I tried this (note: I gave it a new new 'EqualsThis' to separate them.

public static bool EqualsThis<TTarget>(this TTarget sTarget, TTarget compare){



return sTarget.Equals(compare);


}

Functionally not that interesting at all, but a test. So I typed in the following and wow... It works from Intellisense's view... Ok it compiled! Wait.....FAIL! But why:?

OK here is the new test:

[Test, Category("BaselineCore")]

public void shouldAsserANYTHINGEqualUsingExtension() {

const String baselineString ="This is a TEST CASE to IgnOrE Casing";

var sb = new StringBuilder(baselineString);

Assert.IsTrue(sb.EqualsThis(new StringBuilder(sb.ToString())));

}

Interesting...

Here is the documentation for what Equals means by default from Microsoft:

Returns: true if objA is the same instance as objB or if both are null references or if objA.Equals(objB) returns true; otherwise, false.

So our code fails using the extension yet this returns true:

[Test] public void shouldAssertStringBuilderExplicit() {

const String baselineString = "This is a TEST CASE to IgnOrE Casing";

var sb = new StringBuilder(baselineString);

var sb2 = new StringBuilder(baselineString); Assert.IsTrue(sb.Equals(sb2));

}

So Reflector to the rescue once again. I could see in Reflector what I believed the issue was. Indeed the StringBuilder class has an overloaded Equals, and even making the extension method cast to the generic type directly was a no go.

So what do you think? Why would this compile fine with absolutely no problems (and that is correct it turns out), but FAIL at runtime on the assertion when the same line above passes? Skip ahead and reply with the answer if you know it....

This exposes one of the dangers that we must be incredibly careful with. It has always been poor design in my opinion to encourage developers to override common methods such as ToString() and Equals(object X) with their own behaviors as you force consumers of the API to understand IMPLEMENTATION. You cannot ensure your OK simply from a contract. This is known to be evil....

Of course this is a legacy style and will be slowly phased out.

Spin up reflector and look at the code for the OVERLOAD that StringBuilder has:

public bool Equals(StringBuilder sb){

if (sb == null) return false;

return (((this.Capacity == sb.Capacity) && (this.MaxCapacity == sb.MaxCapacity))
&&
this.m_StringValue.Equals((string) sb.m_StringValue));

}

Of course! How else could a StringBuilder claim to be 'Equal' to another... In fact it is perfectly reasonable but again shows the danger of late binding, making assumptions about how any 'object' type will perform.

So there was no real way for our extension to call the 'correct' equals. It called the base definition given above which is obvious now why it failed.

So how do we fix this for the general case?

Here is the test case which I got working.. If your not familiar with this style of code,

This is the foundation we build layer after layer on and illustrates the core of this post.

[Test] public void shouldAsserANYTHINGEqualUsingExtension() {

const String baselineString = "This is a TEST CASE to IgnOrE Casing";

var sb = new StringBuilder(baselineString);

var sb2 = new StringBuilder(baselineString);

Assert.IsTrue(sb.EqualsThis(x => x.Equals(sb2)));

}

Lambadas are like an incredibly focused and powerful domain specific language for delegates. In this sense they are quite similar to Regular Expressions in that they are really good (and to quantify good, I mean clear yet precise, not overly verbose yet highly effective for problems that are more difficult without them).

So what about the implementation? Here it is:

public static bool EqualsThis<TTarget>(this TTarget sTarget,

        
Predicate<TTarget> EqualsDelegate) {

                             return EqualsDelegate.Invoke(sTarget);

}

It's all about Expressions! Think of them as varied ways to receive executable code that you can 'invoke' literally, that must meet the contract you define.
This is so basic after we cover what the really useful applications are. However remember this has nothing to do with the examples, only the concepts they represent.


 
  1. Combine Generics and Generic Constraints to your Extension Methods but BE CAREFUL and ensure you are covered by unit tests
  2. Try to always think a level of abstraction above where your immediate need is to see if your solution indeed has wider and perhaps far more valuable contribution.
  3. Hide complexity behind your Framework API, and focus on crafting work that others will easily consume.
ReSharper 4.01 RC1 Released : See the Team Here as Well

Download it (or when this is outdated, later releases) from:



Build #: 922 VERSION 4.0.1 RC1

  • photo Sergey Anchipolevsky
  • photo Igor Alshannikov
  • photo Alexander Anisimov
  • photo Dmitry Avdeev
  • photo Sergey Baranov
  • photo Yury Belyaev
  • photo Natalia Belyaeva
  • photo Dave Booth
  • photo Elena Bukreeva
  • photo Jana Charif
  • photo Nikolay Chashnikov
  • photo Alexander Chernikov
  • photo Roman Chernyatchik
  • photo Sergey Coox
  • photo Sergey Dmitriev
  • photo Ilia Dumov
  • photo Michael Gerasimov
  • photo Sergey Golovachev
  • photo Alexey Gopachenko
  • photo Peter Gromov
  • photo Dmitry Jemerov
  • photo Maria Khalusova
  • photo Valentin Kipiatkov
  • photo Cyril Konopko
  • photo Anna Kozlova
  • photo Mikhail Kropotov
  • photo Alexey Kudravtsev
  • photo Olga Lobacheva
  • photo Dmitry Lomov
  • photo Vyacheslav Lukianov
  • photo Anton Makeev
  • photo Egor Malyshev
  • photo Maria Marakulina
  • photo Kirill Maximov
  • photo Sasha Maximova
  • photo Irina Megorskaya
  • photo Lucie Morawiecova
  • photo Alexander Morozov
  • photo Maxim Mossienko
  • photo Ekaterina Musienko
  • photo Ann Oreshnikova
  • photo Eugene Pasynkov
  • photo Vaclav Pech
  • photo Alexey Pegov
  • photo Marie Pejcharova
  • photo Eugene Petrenko
  • photo Irina Petrovskaya
  • photo Mikhail Pilin
  • photo Konstantin Polonsky
  • photo Julia Repina
  • photo Elizaveta Revyakina
  • photo Ilya Ryzhenkov
  • photo Andrew Serebryansky
  • photo Ilya Sergey
  • photo Maxim Shafirov
  • photo Tatiana Slavina
  • photo Olesya Smirnova
  • photo Konstantin Solomatov
  • photo Oleg Stepanov
  • photo Pavel Sher
  • photo Ekaterina Shliakhovetskaja
  • photo Oleg Shpynov
  • photo Gregory Shrago
  • photo George Udov
  • photo Sergey Vasiliev
  • photo Natalie Yaremych
  • photo Yegor Yarko
  • photo Timur Zambalayev
  • photo Sergey Zhukov
  • photo Eugene Zhuravlev
  • photo Alexander Zverev
Page view counter