UberDemo

  • Gestalt 1.0 and Gestalt Widget Pack Launched!

    MIX Online has released a major update to the Gestalt project. Gestalt has now been incorporated directly into the Dynamic Language Runtime (DLR).

     Joshua Allen writes: Included ... are our sample video and audio widgets, which come with the Gestalt Widgets pack.  By adding a <script> tag to the top of your HTML file, you can automatically enable use of HTML5-compatible video and audio tag syntax:

    <html>  
      <head>   
        <script type="text/javascript"
          src="http://mschnlnine.vo.llnwd.net/d1/dlr-20091120.js"></script>   
        <script type="text/javascript"
          src="http://mschnlnine.vo.llnwd.net/dlr/dlrmedia.js"></script> 
      </head> 
      <body>   
        <audio autoplay="false">
    <source src="foo.mp3" type="audio/mp3"></source>
    </audio> 
      </body>
    </html>
  • Oomph: A Microformats Toolkit

    Mix Oline presents their newest project: Oomph2: A Microformats Toolkit. This new version adds support for the hMedia format, plus a lot of other enhancments/improvements. Check it out at: http://www.visitmix.com/Lab/oomph/.

    "Microformats are about enhancing the web, representing data in HTML and moving that data around. Oomph: A Microformats Toolkit is for web developers, designers and users, making it easier to create, consume, and style Microformats. Oomph makes consuming and producing content for the web just a little easier, more efficient, more fun. Now featuring Oomph2!"

  • Circumventing an IE/Flash Display Issue in the WPF WebBrowser control on x64 machines

    Recently I wrote some code with the intent to display an embedded YouTube Flash video in Window Presentation Foundation’s WebBrowser control. I ran into an interesting problem. Internet Explorer displayed a broken object icon on some machines, but not others. After some investigation it appeared that the Flash video was displaying properly on x86 machines and failing to appear on x64 machines. Apparently the x64 build of the WPF application spawns an x64 instance of IE. The Flash object does not display, since IE attempts to load the x64 version of Flash, which incidentally does not yet exist for x64 versions of Windows.

    To solve the problem, set the compiler to explicitly compile the app to x86, and it becomes a non-issue. The downside is that the app can no longer take advantage of x64 capabilities, but for many cases this is probably fine.

    Incidentally here is the code that I used:

    private string embedded = "<html style=\"margin:0 0 0 0; background-color:Black; overflow:hidden\">" +
    "<script event=onload for=window>document.body.scroll=\"no\"</script>"+ "<object width=\"425\" height=\"344\">" +
    "<param name=\"movie\" value=\"http://www.youtube.com/v/{0}&hl=en&fs=1\"></param>" +
    "<param name=\"allowFullScreen\" value=\"true\"></param>" + "<param name=\"allowscriptaccess\" value=\"always\"></param>" +
    "<embed src=\"http://www.youtube.com/v/{0}&hl=en&fs=1\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"425\" height=\"344\"></embed>" +
    "</object></html>";

    WebBrowser wb = new WebBrowser();
    wb.Width = 425;
    wb.Height = 344;
    wb.NavigateToString(string.Format(embeded, passInPathToVideo));

  • Using Custom Namespaces at the Root of a XAML File

    Here’s something I didn’t know about Silverlight, and I did not find any documentation on it. It’s possible to create custom namespaces at the root of a XAML file. I always knew that you could insert namespaces inline in XAML, but apparently when you define a namespace attribute in XAML it also applies to the root. Here’s a simple example:

    <myType:TreeMapPanelItem

    x:Class="MIXOnline.Descry.Controls.CustomTreeMapItem"

    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

    xmlns:myType="clr-namespace:MIXOnline.Descry;assembly=Inaugural" >

    <TextBlock Text="Hello" />

    </myType:TreeMapPanelItem>

    This allows replacing of custom elements programmatically as was done in the CPP Custom Treemap sample in Descry which needed to inherit from a base TreeMapPanelItem class to pick up some of its default properties and methods. This could not have been done with a standard Silverlight class since they cannot inherit from custom classes. See the CPP TreeMap sample in Descry for an example and look to the CustomTreeMapItem class for an example of an implementation. Note the assignment of the PanelItemType property in the Page.xaml.cs file which lets the TreeMapItem know which class to use for rendering.

  • Glimmer Released!

    The Mix Online_ team has just released their latest work: Glimmer. Glimmer is a WPF tool that generates jQuery so that you can easily create effects for your website! Check it out at http://www.visitmix.com/lab/glimmer

    Get Microsoft Silverlight
  • Regular Expression support in Visual Studio 2008

    Since I write a lot of Silverlight and WPF applications, I make heavy use of Visual Studio, and when I work with large XML files it is very time saving to know how to use Visual Studio’s Regular Expressions search support. Every time I use it  though I invariably forget how to write RegEx searches, since I use it so seldom. So as the proverb goes: the weakest ink is better than the best memory. Perhaps you may get some use out of it.

    Regular Expression search is not on by default. To turn it on you need to expand the options section in the Find and Replace dialog. RegEx search cannot be on by default since certain RegEx characters have completely different meaning that the literal characters and so would cause conflict if both were enabled.

    SearchReplaceRegExCA1Z6T88

    The Complete Character List is conveniently linked off the menu shown when clicking the arrows to the right of the find and replace Textboxes. I tend to learn much more quickly by example, and this page does provide *some* examples, so while useful, it doesn’t contain as many as I’d like. So here are two more for now:

    \<xdate\>(.*)

    Finds and selects the following node to the end of the line: <xdate>11/14/2008</xdate>

    This is handy if you need to remove or modify an XML node. Note that the angle brackets are escaped with backslashes. The parentheses' group the period which allows any character and the asterisk which signifies zero or more characters before the carriage return.

    \n~((.+)\n)

    Finds and selects carriage returns that have empty lines following them. This is handy if you want to compact empty vertical space. Essentially the logic is: Find a carriage return, but only one that precedes a line with a blank carriage return. This search will not find a line if it has spaces contained in the empty line, so you would need to modify it.

     

    I only provided two examples, but if you know of any good RegEx resources please provide a link in the comment, or you can tweet me on twitter.

  • MIX09’ing it up with a Tetris Version of Flotzam

    clip_image002

    For MIX09, our team decided to create a new look for Flotzam that was to be shown prior to the keynotes. We’d thought about possibly creating a Vegas slot machine version, but we ended up choosing Tetris, since it was very much in line with the #MIX09 theme. It sounded like an exciting project, so I jumped on it! Tim Aidlin designed the user experience and the look and feel, and Karsten Januszewski modified the data object model to support binding a single data template type to any one of the available Flotzam data sources collected from the various feeds: Twitter, Flickr, RSS, etc.

    We brainstormed about what we wanted it to do, and settled on creating a somewhat simplified version of Tetris that avoided rotating the blocks. Flotzam Tetris needed to specifically target the 16x9 format used in the MIX09 keynote screens. This translated into 1280px by 720px dimensions, a fairly low resolution by today’s standards, which forced us to experiment with shape sizes. We needed to keep a careful balance between ensuring readability of the text in the back row of the keynote sessions while looking esthetically pleasing; the less blocks on screen, the less compelling it appears.

    The Tetris logic itself was simple enough; I found several samples on the web to draw from. I chose to borrow some ideas from the CodePlex WPF Tetris that Karsten showed me, but this only got us about halfway. Absent was how to programmatically solve which Tetris blocks should fall based on the pieces that had already fallen. There are probably a few ways to solve this problem. I chose to take a commonly used game approach of using a buffer for the Tetris shapes defined as an array of integers, which I’ll call a table. Zero represents an empty space, and a one represents a space occupied by a block, the fundamental unit that makes up Tetris shapes. It turned out to be convenient to use integers since it very was handy to add up columns and rows for calculating when a row was full or calculating the total height of a stack of shapes for a particular column.

    The shapes are defined in the TetrisShape class. The individual blocks that compose a shape are represented in a Point array offset from a (0,0) origin. The TetrisShape class also contains a Position property that maintains the absolute position of a TetrisShape shape in the table.

    There are two other interesting parts to the TetrisShape class. The first is a Weight property that allows us to define how important the shape is, so that we can get a better spread of shape usage. It’s used in determining the probability that it will be chosen as the “next” shape to be dropped. The second is the ShapeSignature() method which returns a series of numbers, as a string, that define the “signature” of the bottom of a shape. So for example a 2 x 2 square would have a signature of “00”, or a 3 x 2 Tee shape would have a signature of “101”. The numbers represent the distance to the bottom block from an imaginary line running under the shape. This reason that this signature is returned as a string is so that string operators can be used to match the signature of a shape to the signature of all the other shapes settled in the table.

    clip_image004 clip_image006

    Fig. 1: Example of the signature of a Square shape vs. a Tee shape.

    The GetShapeNeededInTable() method returns the signature of entire width of the bottom of the table. This is a function that examines the height of the columns of the settled shapes in the table to obtain the signature. Once we have this, we can see if a shape can fit in the table by simply calling: ShapeNeeded.Contains(ts.ShapeSignature()). If the call returns true it’s a suitable shape and the shape is stored it in a temporary list that gets sorted based on the TetrisShape Weight property. If there’s more than one shape in the temporary list it randomly chooses one of the shapes with the two highest weights and returns the chosen shape.

    The shape chosen then gets bound to the data source and gets added to the VisualTree and displayed on screen. When a row is completed it causes all the “settled” shapes to drop down one level. If a shape drops below the bottom threshold it gets removed from the VisualTree and also the table shape list to prevent a memory leak.

    The main loop is the RunTetrisFlotzam() method, which is called at regular intervals by a timer (.7 seconds in by default.) This method contains a method that determines whether a shape can drop down or whether it is “settled” it also calls a function that animates the shapes from one position to the next in a programmatic manner. We wanted the animation to have easing, but it would take a bit of reorganization of the code to make this happen.

    You’ll find the source code for Flotzam and Tetris Flotzam here. This was a fun project and perhaps you can make some interesting modifications to it. If you do, be sure to let us know!

  • A VirtualizedStackPanel Control in Silverlight 2.0

    When putting together the code for the Descry - Social Timeline visualization, I quickly discovered that when I subscribed to FriendFeed friends that contained large numbers of items, I eventually encountered performance issues. Scobleizer’s feed was a great acid test, since he had about 13K+ subscribers. We needed the Social Timeline to display, at a maximum, 3 months of subscriber data. I found as the total number of FriendFeed items approached 10K, scrolling and animating databound StackPanels became unacceptably slow. My opinion is that quick response time not only is a critical determining factor in user satisfaction, but also contributes to faster user feedback time and continuity, so that user can make better informed decisions.

    It can be argued that what I was attempting to do was an architectural design flaw, since we were attempting to use StackPanels to represent one days’ worth of stacked FriendFeed items; a total of 93 StackPanels for 3 months of data. However, we wished to retain the resizing and scaling properties of the StackPanels’ parent Grid control and it’s ColumnDefinitions, so that we would could avoid writing messy sizing/positioning logic, that the Grid control, conveniently, already has built-in. As a result we would need to find another method to gain performance. We ended up choosing control virtualization, since the sheer number of FriendFeed items is what was causing the slowness.

    So, what do I mean by “virtualized control?” A virtualized control is one that utilizes resources efficiently. You might ask: “Shouldn’t all controls utilize resources efficiently?” The answer to that is yes, but there are performance and behavior tradeoffs between a typical control and a virtualized control. Non-virtualized controls have all the databound UI already in memory. Virtualized controls are specialized controls geared for managing large amounts of data that need to bind UI on the fly, and they take a performance hit when doing this. Also, you’ll note that when scrolling the content of the virtual StackPanel control in this project that it does not smoothly scroll up a pixel as a time as a normal ListBox does, instead it scrolls up one item at a time. This is not a limitation of a virtualized control, but rather a limitation of this implementation. To implement this would take a bit more thought.

    In other words, when a typical Silverlight control is databound to a data source that contains ten’s of thousand objects, it will literally contain ten’s of thousand UI elements in its’ visual tree; potentially using a vast amount of resources. The visual tree is maintained in memory (in addition to the original data source) whether the visual tree is onscreen or off! Conversely, a virtualized control while having access the to the data source in memory, would only contain the elements that need to be physically displayed within the viewable area of the control, resulting in a dramatically smaller set of items in the visual tree.

    This sample shows a virtualization technique for creating a scalable and performant ListBox-like control. There are two key classes: the VirtualizedStackPanel and the VirtualizedItemsControl. The source for this simple virtualized control is here.

    VirtualizedStackPanel Role

    The VirtualizedStackPanel is a control that simply limits the number of children contained in its visual tree to only the items in the viewable area.  This control alone is unable to display the data properly, since a scrollbar is needed to manage the position of the currently viewable area; the VirtualizedItemsControl takes care of that need.

    The VirtualizedStackPanel behaves as a normal StackPanel until a data generator is attached. The IDataGenerator implemented in the custom VirtualizedItemsControl lets the VirtualizedStackPanel know what children are currently in the active viewable area, based on control size and scrollbar position settings. As soon as the size of the control, or scrollbar position changes, the MeasureOverride method is called, and the control recalculates which children are to be added or removed from the visual tree. A ContentPresenter is acquired from the assigned data generator, so that a common DataTemplate can be used to define item UI. When the ContentPresenter Content property is set, the data is bound to the UI defined in the DataTemplate.

    The main logic in the VirtualizedStackPanel is in the MeasureOverride method, creates new containers if they are needed when the control height increases, or reuses containers if no new ones are needed, and also removes unnecessary containers of the control height decreases. The ArrangeOverride simply positions all the children in the StackPanel vertically.

    VirtualizedItemsControl Role

    The VirtualizedItemsControl’s role is to act as a container for one or more Virtualized StackPanel’s. It manages the data source, a common DataTemplate that children use, and it also manages the Scrollbar positioning logic. The VirtualizedItemsControl implements the IDataGenerator interface that assists in communicating with its VirtualizedStackPanel children. This sample shows a single VirtualizedStackPanel child for brevity. But you may refer to the VirtualizedTimelineItemsControl in the Social Timeline project on CodePlex for one that contains multiple children.

    Incidentally, the VirtualizedItemsControl’s content is defined in the projects /Themes/Generic.xaml file, it could have been just as well defined procedurally, but it uses an external resource file for better designer / developer workflow. It is critical that this file exist in the project in the Themes folder, and note that this file needs to be defined as a resource in the project to avoid errors. I made the Silverlight 2 newbie mistake of not doing this, and I literally spent days trying to figure out why I couldn't get the project to work.

    Resources

    I found that writing a virtualized control wasn’t quite as complex as I had anticipated, after I broke down a much more complex sample. There is a good example of a full Implementation of a VirtualListBox in the Silverlight Extensions project on CodePlex. Another related WPF VirtualizedCanvas sample by Chris Lovett that I found useful is located here.

    Descry and Codeplex

    Visit CodePlex to download a more fully developed version of a virtualized control that supports mouse drag animation with physics, plus a VirtualizedListBox as well. And visit here to get the entire Descry project source!

     

  • Descry

    “Ever wonder what goes into building an effective visualization? Look no further. We decided to roll up our sleeves and explore the topic. We're calling it Project Descry.”

    Descry is the new culmination of our “Innovative Web” teams efforts! It’s worth a check!

  • Announcing MIX ONLINE!

     

    My team members have been working on a entirely new version of the VisitMIX site for the past couple of months. There's going to be some very interesting activity around this site.

    image MIX Online is a community site for web designers and developers who are building and believe in the innovative web. In the past, the site has given a varied perspective of what is happening on the web, a view into our conference called MIX, and interviews with amazing people with incredible ideas and stories on how designers and developers can take advantage of the web. MIX Online has always been a year-round companion to the event. [more...]

  • hCard

    Hans Hugli
    Microsoft
    1 Microsoft Way
    Redmond WA , 98052
    USA
    425.882.8080
  • Capturing a WebCam stream to a WMV file from within a WPF application

    I was asked to help out with a demo, my assignment was to capture some video from a WebCam that was to be used for the Cirque du Soleil demo for MIX08. There were a few ways to do this, none which were obviously attractive. There are many 3rd party tools that capture video and output to a file, but none I found were extendable and usable from within an application. Another thought was to use the DirectX API’s to do the capture, but this required some fairly involved interop. Windows Media Encoder was not an obvious choice, but to my delight ended up being perfect for the job. I was satisfied with the results. Windows Media Encoder Series 9 has type libraries that expose its COM API’s and can be added to a Visual Studio project directly as references. Visual Studio automatically generates Runtime Callable Wrappers for them.

    This is a not a production quality sample, but I thought it still lhad some value getting it out there, since I spent quite some time finding out how to go about this.

    A few things to mention up front

    · The Windows Media Encoder Series 9 (WME9 from here on) has a bug on Windows Vista that requires a hotfix to be installed. It needs to be installed as an Administrator of the machine. You can run it as a non-Admin, but the hotfix will not install properly and will not report errors. If you find that anytime you access WME9 code (on Vista) and the application crashes without error, you can be sure that the hotfix is not installed properly.

    · This sample shows at a basic level how to access audio level information via a Managed DirectX API (Microsoft.DirectX.DirectSound is the DLL referenced) and so requires installing some managed DLL’s. I happened to find these DLLs in the Microsoft LifeCam install, so that’s how I installed them, instead of installing the entire Managed DirectX SDK. There may be a faster/better way to install these DLL’s but I haven’t taken the time to look around for it. If you decide not to install this software, you will need to comment the relevant code.

    · You will need a WebCam that functions on your PC to run this sample. This means that you need to install your WebCam’s software and ensure that it works outside of the context of this sample. I myself used the a Microsoft Vx6000 LifeCam, but I’ve tested this app with two other WebCams without issue. The application detects and lists the WebCam in a ComboBox on application launch.

    · This application was built in Visual Studio 2008, and will also open properly in Expression Blend 2.0 Beta (February). A DesignTimeHelper class has been added to make it easier to see some of the application elements in the designer at design-time.

    · To run this project in Visaul Studio you will need to uncheck the “Loader Lock” thrown checkbox due to the audio level code. To get to this dialog choose Debug -> Exceptions from the Visual Studio menu and expand the “Managed Debugging Assistants” node.

    clip_image002

    Installing and running the sample

    1. Install WME9 from: http://www.microsoft.com/downloads/details.aspx?FamilyID=5691ba02-e496-465a-bba9-b2f1182cdf24&DisplayLang=en

    2. [optional] Install the WME9 SDK from: http://www.microsoft.com/downloads/details.aspx?FamilyID=000a16f5-d62b-4303-bb22-f0c0861be25b&DisplayLang=en (The WME9 SDK ended up being very helpful, although I found that the samples in the “samples” directories were not as helpful as the actual content in the CHM file. There are complete samples hidden in the text of the CHM files that were enlightening.)

    3. [required for Windows Vista only] Copy the WME9 hotfix locally from: http://download.microsoft.com/download/0/3/d/03d35c05-67da-40e0-9e45-3ea0ca6329a4/windowsmedia9-kb929182-intl.exe (Right-click and choose “Run as Administrator” to install)

    4. Install the Microsoft LifeCam Software from: http://download.microsoft.com/download/1/9/5/195512A9-1C1E-4429-BFF0-613D8D92E122/LC14.exe

    5. Copy the sample project bits from http://www.hugli.org/code/videoencoder/videoencoder.zip expand it and place the VideoEncoder directory in a directory of your choice. Typically I place content in a c:\users\public\demos directory, since this directory is accessible from all profiles without security issues.

    6. Install any necessary software for your WebCam and plug it in.

    7. Launch the project in Visual Studio 2008.

    8. Modify the OUTPUT_PATH to be a directory that your identity has write access to. The path c:\users\public is the default and will work on Vista, however for XP you will need to modify this path.

    9. Press F5. After the application launches you should see two ComboBox’s and a clickable image.

    10. Choose your WebCam from the “Video Source” Combobox and use the default profile (384 Kbps.)

    11. Click on the image and a video dialog will fade/animate in.

    12. Press “Begin Recording.” There will be a slight delay and a video preview will appear on the video dialog. Note that there are also crosshairs, recording status and progress bars to indicate audio level that overlay the video.

    13. Press the “Record” button and you will see timecode start advancing in the video overlay.

    14. Press the “Save” button and the video strean will be closed and saved to disk in the directory specified in OUTPUT_PATH.

    15. The video is then added to a WrapPanel as a MediaElement

    16. End Sample.

    How was sample done?

    Now I’m going to cover the application and some of its hidden subtlties. I wrote this sample in a couple of days since the demo had to be put together in short order. If I had more time, I’d break out the audio related content into its own class and spend some time cleaning up the VideoEncoder class that wraps up all the encoding logic. Another thing that I would do is break out the VideoWindow code into its own UserControl. UserControls cannot draw outside of its own bounds so you would need to allow the UserControl to span the width/height of the entire application to allow for the video fadein animation. There are some problems in the code at present. The most troublesome is that sometimes I find that when capturing video the encoder captures only blank video, and I haven’t found the cause of it yet.

    WME9 archiving

    One thing that confused me about WME9 initially was that as soon as the Encoder was started the video started capturing to disk and it was only then that a a preview would show up in the preview drawing surface (both happened simultaneously). What I really wanted instead was to see the video preview *before* I began capturing the video, so that I could center my WebCam on my subject, and then and only then start the video capture to disk. Well, it turns out that when the Encoder is started, the video starts capturing (Archiving as they refer to it) immediately, by default. To change the behaviour to what I wanted, i.e. to see a preview before the video captured begins, I needed to set the Encoder.EnableAutoArchive property to false (from its default true), and then start the Encoder. At this point the preview begins displaying in the application, and then we can optionally start the video capture by clicking on the “Begin Recording” button with this call:

    Encoder.Archive(WMENC_ARCHIVE_TYPE.WMENC_ARCHIVE_LOCAL, WMENC_ARCHIVE_OPERATION.WMENC_ARCHIVE_START);

    Encoder.PrepareToEncode(true);

    and end the video capture with this call:

    Encoder.Archive(WMENC_ARCHIVE_TYPE.WMENC_ARCHIVE_LOCAL, WMENC_ARCHIVE_OPERATION.WMENC_ARCHIVE_STOP);

    It’s also good to know that if you want to capture to an entirely new “archive” file, you will need to stop the encoder, redefine the capture file info and then restart the encoder.

    Interop

    To get the Video to display in a WPF application took some simple interop. It was interesting for me to find out that you can get a Handle from all WPF elements using IntPtr handle = ((System.Windows.Interop.HwndSource)myElement).Handle so that I could have the video draw on a specific element, but all elements returned the same Handle (the parent windows Handle.) This wasn’t very useful since the video ended up being drawn inside the entire Window no matter which element I chose. To workaround this, I instead created a WindowsFormsHost element and added it to the VisualTree. I then added a System.Windows.Forms.Panel as a child to that WindowsFormsHost (note it is important that the WindowsFormsHost has a child, since the WindowsFormHost element itself gives you the handle of the parent Window, which again is not what we want. The differentiating factor is that System.Windows.Forms controls have a Handle property which makes it very convenient to get the Handle. All System.Windows.Forms.Panel controls are Windows themselve’s. This makes it easy to grab a handle and draw within the bounds of the panel. It should be noted that having all controls be windows can lead to resource and performace problems for large numbers of children, this is not an issue in WPF. The Handle property returns a System.IntPtr which we then pass directly to the Preview.SetViewProperties method along with the video stream itself. Doing this draws on the panel.

    When you draw directly on a surface using this technique, there is a side-effect in a WPF application; you no longer can see WPF elements residing on top of this drawing surface anywhere in the VisualTree. I call it a “black hole”, since it obscures or cuts a hole into any window-less elements you try to place on top of it, whether a child element or an element with a higher z-order. This is essentially because the OS can only address something with a handle (a Window in this case) and so it draws the video after all the other elements in the WPF window are drawn.

    Video overlay

    So how then was the video overlay done? It was accomplished by placing yet another Window on top of the video. The WPF Popup element just happens to be a Window with its own handle. There is a side-effect to this technique: if the parent window is moved, you will find that the Popup doesn’t move along with the parent. This can be remedied by subcribing to the Window.LocationChanged event and in that event modify the position of the Popup. Another side effect is that when the parent Window loses focus, the popup ends up on top of other applications. Again this can be remedied by subscribing to the proper focus events, both of these issues are beyond the scope of this writing.

    Animation

    Note that the video preview Grid (videoCaptureGrid which also contains the Popup) are not part of the animated videoWindow Grid. I found that trying to animate an element that contained the video rendered through interop performed poorly and drew improperly, so I simply hid videoCaptureGrid until the videoWindow Grid finished fading and animating in.

    Possible Exercises

    1. Try to get a Thumbnail of a video. I spent some time on trying to do this and ended up falling back to having a media element display the video for lack of time. Two potential ways to do this are: Use RenderTargetBitmap or grab the Thumbnail that Windows itself generates. The code for using RenderTargetBitmap is in the project in the RasterizeVisualAt96dpi method, but is not used at present. I found that it was tricky to grab the thumb of the video since the first frame(s) of the video tend to be black. Grabbing a video thumbnail from Windows will require the use of interop. I’m not sure if this is possible or feasible.
    2. WME9 is able to capture the desktop of your computer. Create a WPF application that runs in your systray that captures your desktop to a WMV file.
    3. Calibrate the audio levels. Right now the Audio levels are cosmetic and gratuitous. They seem to be a bit delayed and levels seem higher than they should appear. Experiment to get the indicators working properly.
    4. Modify the Popup position when the application is moved or loses focus.
  • Debug Monitoring Tool

    In Building a recipe application using Vista and .NET 3.0 (Part IV: ThumbnailProvider interface) I reference the DBMon.exe tool, and state that it is located in the Windows SDK, however, as of the lastest Windows SDK: Microsoft® Windows® Software Development Kit Update for Windows Vista™ (released 3/22/07), DBMon no longer ships in the SDK. I was unable to find it in any other Microsoft release.

    In my search I found this tool that very nicely replaces DBMon: DebugView v4.74 (by SysInternals.) This tool has the same basic functionality, plus many, many more features, such as the abilty to connect to remote machines, persisting sessions to disk, filter entries, and capture from many debug sources.

    It is available here on the Microsoft.com TechNet site: (published 11/27/07)

  • Security Integration of SharePoint 2007 and Community Server 2007

    Although I'm certainly not a SharePoint expert, MSDN just posted an article I authored that shows how to cleanly integrate the security model between these two platforms using ASP.NET Roles. I put this together for the Office team from something that came out of a need for our team: http://msdn2.microsoft.com/en-us/library/bb892784.aspx.
  • “Linkifying” a String

    I had a need to create a string “Linkify” function for a web site that I am working on; a function that takes a string, parses it for URL’s, and replaces those URL’s with HTML anchors. The end result is when the string is passed to a web client it would allow the user to browse to the URL.

    I started out thinking that it could be done with some simple string manipulation, but quickly realized that finding the end of a URL was not trivial. It then occurred to me that Regular Expressions would solve the problem from my experience with Perl. Regular expressions are exceedingly powerful, but with its’ power comes complexity.

    The .NET framework has a namespace dedicated to Regular Expressions: System.Text.RegularExpressions. The RegEx class has a constructor that takes a pattern and options as parameters. The RegEx.Matches(string) method takes a string as an input and returns a MatchCollection, which contains a lot of buried information. For my purposes I was able to avoid having to drill down deep into the collections contained within the object, but it’s good to know that it has the ability to capture the individual groups that a pattern returns.

    The trickiest part for me, was recalling how to construct a pattern for this type of query. RegEx pattern syntax is a language of its own, that takes me time to wrap my head around every time I need to work with Regular Expressions, which is not all too often.

    So how did I overcome my cerebrally-challenged problem? In searching on Live.com… incidentally in Windows Vista, by default, hit the Windows key, type your search word(s), press the down arrow and press enter…  I came across a free 3rd party tool  Regular Expression Designer by Rad Software, (this tool is not endorsed by Microsoft) that helped me to quickly construct and try out the pattern that I needed. It also has a handy quick reference to show the meaning of the esoteric symbols used in RegEx patterns.

    Construction of the pattern

    Anything within parentheses in a RegEx pattern is called a “group.”  In this application want 3 groups; the first: the protocol, the second: the domain, and the third: the path. For the protocol group we want to find an occurrence of http or and ftp. The | operator indicates an Or, followed by the literal ://. The domain group is one or more matches + that do not contain a forward slash, a carriage return, a close paren, or a quote mark [^/\r\n\")], note that some are escaped by preceding backslashes, and the path group needs to have zero or more matches * that begin with a forward slash , but not a carriage return, close paren or a quote mark [^\r\n)\"], and lastly we want to find *all* matches in the string with a ?

    Putting it all together we arrive at this:   "(http|ftp)://([^/\r\n\")]+)(/[^\r\n\")]*)?"

    We could have given the groups friendly names as in: "(?<protocol>http|ftp)://(<?<domain>[^/\r\n\")]+)(?<path>/[^\r\n\")]*)?", if we had wanted to access the individual values by name, for some other purpose. Without assigning names, by default, the groups are numbered in order of occurrence within the pattern starting with 0.

    Following is a method call that wraps it all up:

    using System.Text.RegularExpressions;

    /// <summary>

    /// This method takes a string and looks for URL’s within it.

    /// If a URL is found it makes a HTML Anchor out of it and embeds it

    /// in the output string. This method assumes that we are not passing

    /// in HTML. This method would have to be revised to support that.

    /// </summary>

    /// <param name="input"></param>

    /// <returns>Clickified String</returns>

    public static string LinkifyString(string input)

    {

         Regex regex = new Regex("(http|ftp)://([^/\r\n)\"]+)(/[^\r\n)\"]*)?", RegexOptions.IgnoreCase);

         MatchCollection mc = regex.Matches(input);

         foreach (Match m in mc)

         {

              string url = m.Value;

              string link = Globals.CreateAnchorTargetBlank(url, url);

              input = input.Replace(url, link);

         }

         return input;

    }

    public static string CreateAnchorTargetBlank(string href, string description)

    {

         return string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", href, description);

    }

    MSDN has some RegEx examples that may be worth taking a look at.

    Be advised that this LinkifyString function will corrupt HTML if you pass an HTML’ified string to it, since we are not checking for anchor elements surrounding the URL’s. To do this one would have to add additional groups that ignore matches inside anchors. i.e. <a href=” http://www.foo.com”>http://www.foo.com</a>.

    -Hans Hugli

More Posts Next page »

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker