Here comes just another JavaScript framework, well new complicated syntax, lots of new methods and lots of complex JavaScript files to manage? Certainly not, pain of JavaScript is real, and it is also the only option.

Mission of Web Atoms

  1. Not to Invent a New Language
  2. Use more Markup and Less Code (Less Script)
  3. Component Driven Development to increase reusability
  4. Help Existing Apache Flex developers to migrate to HTML5
  5. Integrate Features of Flex and Silverlight into JavaScript

Features

  • Declarative UI Bindings
  • Automatic UI Refresh (One way and Two way Binding)
  • Template Engine
  • Ready to use Business Controls
  • Command Chaining (Advanced MVC)
  • Private Scope Isolation for Components
  • Most Simple form of AJAX Ever (AtomPromise)

Simple Example

<div
    atom-type="AtomListBox"
    atom-items="{ AtomPromise.json('movie-list.json') }"
    atom-name="movieList"
    atom-auto-select-on-click="{ false }"
    atom-allow-multiple-selection="true"
    atom-value-path="MovieName"
    >
    <table>
        <thead>
            <tr>
                <th>
                    <input
                        type="checkbox"
                        atom-type="AtomCheckBox"
                        atom-is-checked="$[scope.movieList.selectAll]"/>
                </th>
                <th>
                    Movie
                </th>
                <th>
                    Category
                </th>
            </tr>
        </thead>
        <tbody
            atom-presenter="itemsPresenter">
            <tr atom-template="itemTemplate">
                <td><input type="checkbox" atom-type="AtomItemSelector"/></td>
                <td atom-text="{ $data.MovieName }"></td>
                <td atom-text="{ $data.MovieCategory }"></td>
            </tr>
        </tbody>
    </table>
</div>

The above code contains a List Box with set of attributes that customizes its behavior. The above sample fetches list of countries from given URL, and then it displays in the table format. Child element of List Box element is template which defines visual layout of List Box. Web Atoms evaluates expressions with $ sign and performs UI Data Binding against those items.

Binding Convention

  • A valid JavaScript Expression between curly braces {} is considered as One Time Binding and it is evaluated only once during initialization of component/element or control.
  • A valid JavaScript Expression between square brackets [] is considered as One Way Binding (UI refreshes when target data changes) and $ determines beginning of source of change.
  • A property path between square brackets [] prefixed with $ is considered as Two way binding in which Data Source is updated as well in response to user interaction.

Scope Isolation

Scope is an object store associated with UI Component or UI Control referred as AtomControl, which provides an isolated storage as per its position in UI Hierarchy. Every UI Control in Web Atoms has a property with name scope, appScope and localScope. Each property gives you access to scopes available at current Scope, Global Application Scope (Global Scope for every component to share data) and a private Local Scope. Scope and Global Scope are maintained by Web Atoms and developers can not control them, however developers can create Local Scope and every children is now part of new Local Scope and is isolated from other Scope.
By giving Name to UI Control, control and its properties become accessible through the scope.
Scope also lets you put functions in it, and different scopes never interfere with same named items. By convention, Scope initialization is written differently than conventional JavaScript.

<script type="text/javascript">
    ({
        view: 'red',
        list: [
            { label: 'Oranges', value: 'orange' },
            { label: 'Apples', value: 'red' },
            { label: 'Grapes', value: 'green' }
        ],
        display: function (item) {
            if (!item)
                return '';
            return item.label + ' are ' + item.value;
        }
    })
</script>

The above script is actually an harmless code, which does nothing when it is parsed and executed by browser. However, the library removes this script and stores it for execution on later stage. And when the controls are initialized, Web Atoms will setup scope corresponding to its position in UI Hierarchy. After setup, these values are available as $scope.view, $scope.list and $scope.display respectively. By accessing through scope property, it provides isolation needed for multi component hosting on one page.

 

Following sample illustrates use of local scope.

    <div
        atom-type="AtomControl"
        atom-local-scope="true"
        atom-abs-pos="100,100,500,200"
        >

        <script type="text/javascript">
            ({
                name: "Scope 1",
                run: function (scope, sender) {
                    alert("Called in Control with " + scope.name);
                }
            })
        </script>

        <button
            atom-event-click="{$localScope.run}"
            >Execute <span atom-text="{$localScope.name}"></span></button>

    </div>

    <div
        atom-type="AtomControl"
        atom-local-scope="true"
        atom-abs-pos="600,100,500,200"
        >

        <script type="text/javascript">
            ({
                name: "Scope 2",
                run: function (scope, sender) {
                    alert("Called in Control with " + scope.name);
                }
            })
        </script>

        <button
            atom-event-click="{$localScope.run}"
            >Execute <span atom-text="{$localScope.name}"></span></button>

    </div>

Simple AJAX (AtomPromise)

In order to provide simple interface to JavaScript promises to implement AJAX and similar asynchronous functionality, Web Atoms has incorporated AtomPromise in the property system, which lets us assign promise in simple expression, but it will do the complex event wiring automatically. In following example, you can see that we are assigning a JSON promise, and it looks like data from url is fetched and assigned to Combo Box. But in reality, we are only assigning a promise, and only if the result of promise will be successful, than actual items from the promise will be assigned in future.

The following example is pretty self explanatory that we are loading list of countries from the given url ‘country-list.json’

<select
    atom-name="countryCombo"
    atom-type="AtomComboBox"
    atom-items="{ AtomPromise.json('country-list.json')}"
    atom-value="$[scope.view]"
    >
</select>

<span
    atom-text="['Selected Country Code is ' + $scope.countryCombo.value]" >
</span>

Templates

In order to achieve true separation of Data and UI, Web Atoms comes with simple DOM Node Templates, which uses UI Data Binding to display contents. And various controls define various templates that can be easily customized by changing Style and other properties of HTML Element. By simply applying an element with atom-template attribute, element is removed from UI Hierarchy and used as template to display the data.

<div
    atom-type="AtomListBox"
    atom-items="{ AtomPromise.json('movie-list.json') }"
    atom-name="movieList"
    atom-auto-select-on-click="{ false }"
    >
    <div
        atom-template="itemTemplate">
        <button atom-type="AtomItemSelector">Select</button>
        <span atom-text="{ ($scope.item_index + 1) + ') ' }"></span>
        <span atom-text="{ $data.MovieName }"></span>
    </div>
</div>

Style Binding

Web Atoms provides extended mechanism of defining and binding individual style properties, which increases granularity of markup.

<script type="text/javascript">
    ({
        list: [
            { label: 'Orange', itemColor: 'orange', itemWidth: 100 },
            { label: 'Apple', itemColor: 'red', itemWidth: 200 }
        ]
    })
</script>

<div
    atom-type="AtomItemsControl"
    atom-items="{ $scope.list }"
    >
    <div
        atom-template="itemTemplate"
        atom-text="{$data.label}"
        style-color="#000000"
        style-background-color="{$data.itemColor}"
        style-width="{ $data.itemWidth + 'px' }"
        >
    </div>
</div>

Style binding is useful when your style is available in the form of Data. Assuming in above example, list is populated from Data.

Licensing

Web Atoms JS is licensed in the following types, please note, license is applicable to the page of the site which uses Web Atoms JS Library.

  1. Free – Attributed License – Commercial or Non Commercial – Requires a back link in bottom right corner of every page to http://webatomsjs.neurospeech.com and Requires Registration with Our Site Directory.
  2. Non Commercial – Open Source Projects – Any open source free apps built and distributed under GPL, BSD, Apache or MIT license can use Web Atoms – Requires Registration with Our Site Directory.
  3. Yearly Subscription – Site License – Single Domain that can be hosted on any number of servers with yearly subscription of $99/year.
  4. Yearly Subscription – Server License – Single Server that can hosted any number of Sites with yearly subscription of $299/year.
  5. Site Perpetual License
    • $999 per Site for hosting on One Server
    • $1999 per Site for hosting on 10 Load Balancer Server
    • $4999 per Site to host on unlimited number of servers or CDN
  6. Server Perpetual License
    • $1999 per Server to host 10 Sites
    • $4999 per Server to host unlimited sites
    • $9999 Data Center License to host unlimited sites on unlimited servers

Documentation

To learn and explore Web Atoms in detail, please visit http://neurospeech.com/webatoms/docs

Share
Tagged with:  

Windows 8 Developer Preview (First Look)

On September 18, 2011, in Programming, Technology, by Akash Kava

I installed Windows Developer Preview of upcoming operating system Windows 8, and it has few good and bad things. Just like a new product, it has new dashboard and cool way to navigate between apps using touch gesture, these things sure excites me up but also looking at the internals, there are more challenges for everyone to catch up with Window 8.

New Task Manager

Nice of all, I like the new improved Task Manager, which lets me look into complete Process Tree as well as I can see user wise Process Tree.

WindowsTaskManager

It also displays Process Tree grouped by Users.

UserProcesses

And best of all, it lets me control my startup items from here, I can disable items I don’t want to auto start.

StartupItems

New File Copy Dialog

Another improved user interface is, File Copy dialog, instead of old style animation, it now displays a graph of progress with real cool line graph that’s very live.

FileCopyDialog

New Search

Search is redesigned completely and you can search for settings by pressing Window + W key. Let’s say I want to change my desktop background, so I pressed Window + W and I typed “wallpaper”, it did give me these options.

Well I just tried all combinations of Window keys and only found following five useful combinations.

  1. Window + W lets you search the settings (usually control panel)
  2. Window + P lets you switch between dual desktop and connect to projector settings
  3. Window + D brings back the desktop
  4. Window + F lets you search the files
  5. Window + Q lets you search Metro App’s Items

To a big disappointment, I did not find anything to search apps, so I have to click on Windows + W and then click on App to actually search applications installed on my machine.

Wallpaper

No Old Apps on Metro Desktop

Metro UI Apps are redesigned using HTML5+JS and Appx with Windows Runtime (XAML + Windows Runtime). So none of your old Win32, .NET apps will execute on Metro UI. They can only execute inside the desktop (old fashion windows). So we have to redesign and rewrite the applications for Metro Desktop completely from scratch.

Metro Desktop Apps are not Silverlight

Although they quite look like silverlight, but looking at the documentation, Microsoft has introduced complete new set of library with “Windows.UI” namespace, which represents complete copy of Silverlight controls (and more) but they are not silverlight. So if you wrote your apps in Silverlight, they wont directly run on Metro UI, but you might be able to port them to Metro UI with some code changes as namespace changes System.Windows.Controls to Windows.UI.Controls. However, it may not be so easy but you will get very unexpected behavior if you try to port it directly.

Three Different UI Technologies to Deal With

Well the only sad part is, now we have total 3 different UI technologies to deal with.

  1. WPF 3.0, 3.5, 4.0 (Original WPF based on XAML). Apps written on WPF are old fashioned, and they will not execute on Metro UI, they will only run in Desktop version.
  2. Silverlight (Web and Phone), Once again, two different forms of same Silverlight for web and phone. However all web that runs Silverlight (and even flash) wont run on Metro UI.
  3. Windows Runtime (XAML,HTML5+JS), this is complete new set of library including various controls from Silverlight and WPF, however it is still not complete with both of them and it also includes more controls of its own. This is purely for Metro UI. HTML5 and JS are once again little different as Microsoft has its own API embedded to make developers feel easy to write code. But this does not mean that your HTML5 code will work absolutely correctly without any changes on Metro UI. In IE 10, it may run, but to make it an appx, you might need to change few things.

As new UI stack is introduced by Microsoft, we will soon release a new version of “UI Atoms” that will allow users to write Windows Runtime Metro UI apps with UI Atoms Controls.

Share
Tagged with:  

UI Atoms 1.7.5 Released

On April 3, 2011, in C#, Programming, RIA, Technology, by Akash Kava

We are happy to announce new release of UI Atoms 1.7.5 with following new features.

  1. New AtomDataForm Control
  2. Tabs in AtomForm and AtomDataForm
  3. Lambda Binding Extensions

Introducing new Control AtomDataForm

AtomForm did support UI Validations, however Microsoft RIA Services Client has some inbuilt validation and support for IEditableObject. So we created a new AtomDataForm that supports RIA Services validation and IEditableObject support.

  1. AtomDataForm supports object with IEditableObject interface and fires event for BeginEdit, CancelEdit and EndEdit
  2. AtomDataForm displays items in read only mode unless Edit button is clicked
  3. After edit button is clicked, Save and Cancel button appear for you to persist changes or cancel changes
  4. AtomDataForm contains UI Element (TextBox, ComboBox etc) as children, so you can easily define child ui element in your xaml as shown in sample below
  5. AtomDataForm supports Tabbed layout, for that you can insert your items within AtomDataFormTab as shown in example below
  6. Following sample illustrates Tabs, but you can also create simple user interface without tab as well
  7. You can also use AtomDataFormGroup to group items in to a headered group
  8. Every child element of AtomDataForm can be accessed in code behind file easily because they appear as a variables when you define x:Name property
  9. AtomDataForm supports CanChangeDataContext property, which is false when the form is in edit mode
  10. You can easily reuse any third party control within AtomDataForm, AtomDataFormGroup and AtomDataFormTab
AtomDataForm Sample
  1. <ns:AtomDataForm
  2.     Grid.Column="1"
  3.     DataContext="{Binding SelectedItem,ElementName=dataGrid}" >
  4.             
  5.     <!– 1st Tab–>
  6.     <ns:AtomDataFormTab Header="Default">
  7.                 
  8.         <TextBox
  9.             ns:AtomDataForm.Label="Name:"
  10.             Text="{Binding ProductName, Mode=TwoWay}"/>
  11.                 
  12.         <ns:AtomToggleButtonBar
  13.             ns:AtomDataForm.Label="Type:"
  14.             SelectedItem="{Binding ProductType,Mode=TwoWay}">
  15.             <sys:String>Product</sys:String>
  16.             <sys:String>Service</sys:String>
  17.         </ns:AtomToggleButtonBar>
  18.                 
  19.         <TextBox
  20.             ns:AtomDataForm.Label="Folder:">
  21.             <ns:AtomDataForm.CommandBox>
  22.                 <Button Content="…"/>
  23.             </ns:AtomDataForm.CommandBox>
  24.         </TextBox>
  25.                 
  26.     </ns:AtomDataFormTab>
  27.             
  28.     <!– 2nd Tab–>
  29.     <ns:AtomDataFormTab Header="General">
  30.                 
  31.         <TextBox
  32.             ns:AtomDataForm.Label="Email:"  
  33.             Text="{Binding Email, Mode=TwoWay}"/>
  34.                 
  35.     </ns:AtomDataFormTab>
  36.             
  37.     <!– 3rd Conditional Tab–>
  38.     <!– This tab will be visible only if Product's
  39.     IsTypeService is true–>
  40.     <ns:AtomDataFormTab
  41.         Header="Service"
  42.         IsEnabled="{Binding IsTypeService}">
  43.                 
  44.         <TextBox
  45.             ns:AtomDataForm.Label="Service Details:"/>
  46.                 
  47.     </ns:AtomDataFormTab>
  48.  
  49.     <!– 4th Conditional Tab–>
  50.     <!– This tab will be visible only if Product's
  51.     IsTypeProduct is true–>
  52.     <ns:AtomDataFormTab
  53.         Header="Product"
  54.         IsEnabled="{Binding IsTypeProduct}">
  55.                 
  56.         <TextBox ns:AtomDataForm.Label="Product Details:" >
  57.             <ns:AtomDataForm.CommandBox>
  58.                 <Button Content="Search"/>
  59.             </ns:AtomDataForm.CommandBox>
  60.         </TextBox>
  61.                 
  62.     </ns:AtomDataFormTab>
  63.             
  64. </ns:AtomDataForm>

In above sample you can notice following things,

  1. Header property of AtomDataFormTab is displayed in the title section on the top
  2. AtomDataFormTab contains children and each child can have properties as below
    1. ns:AtomDataForm.Label displays label on left side
    2. ns:AtomDataForm.Description displays description on bottom
    3. ns:AtomDataForm.Title displays title on the top of control
    4. ns:AtomDataForm.CommandBox displays a UI Element on the right corner, usually a search button or expand button
  3. AtomDataFormTab supports IsEnabled binding, you can bind this property to show/hide the tab as shown in the example above
  4. Every child elemen of either AtomDataForm , AtomDataFormTab or AtomDataFormGroup supports Visibility and IsEnabled binding
    1. If Visibility is bound and it results in Collapsed then entire form item is not displayed
    2. IsEnabled binding can enable/disable the editable control

Following is screenshot of Tabbed AtomDataForm in edit mode

AtomDataForm

Introducing Lambda Binder Extensions

Writing binding expressions with conditions and converters can be very complex especially rewriting many and same logic at different classes. Now UI Atoms support, Lambda Binding Extensions which lets you do binding within the code without creating any complex IValueConverter implementation.

Bind Method Extension

Element Property Binding
  1. theForm.Bind(AtomDataForm.HeaderProperty,
  2.     () => string.Format("{0} ({1})",
  3.             productName.Text,
  4.             typeToggleButtonBar.SelectedItem
  5.         ));

This will bind theForm’s Header property to an expression that will combine properties of two different elements. And this will also automatically update when any of bound source or its property will change.

DataContext Property Binding
  1. theForm.Bind(AtomDataForm.HeaderProperty,
  2.     () => string.Format("{0} ({1})",
  3.             theForm.DataContext.Property("ProductName"),
  4.             theForm.DataContext.Property("ProductType")
  5.         ));

Assuming, we may not have property information at design time, but we know that DataContext will be set to an object containing properties, then we can write Property extension method as shown above.

BindVisibility Method Extension

Visibility converters are very frequent so we created a BindVisibility extension method that will let you specify a boolean expression that will be converted to Visibility on the fly.

BindVisibility Extension
  1. productTab.BindVisibility(
  2.     () =>
  3.         typeToggleButtonBar.SelectedIndex == 0);

These extensions can be used anywhere in any third party controls as well.

Download Now

Click here to download your free demo copy of NeuroSpeech UI Atoms 1.7.5

Share
Tagged with:  

Lambda Binder for WPF and Silverlight

On March 20, 2011, in C#, Technology, by Akash Kava

LambdaBinder class helps in creating complex binding expressions without having to create IValueConverter and IMultiValueConverter, it lets you write inline expresions with advanced binding scenarios.

Lets say, you have two TextBox for first and last name and you want a Title to be displayed as addition of both.

So lets say, you can write it as follow,

Adding Two Properties
title.Bind(TextBlock.TextProperty,
    () => firstName.Text + " " + lastName.Text);

Formatting Properties
title.Bind(TextBlock.TextProperty,
    () => string.Format("{0} {1}",
        firstName.Text, lastName.Text));

You can pass on the Linq expression to Bind extension method of LamdaBinder and that will convert and set binding so that anytime if firstName or lastName is modified, the title will be updated automatically.

Assuming I want some hypothetical visibility logic, for example, only if the firstName is entered, lastName should be visible.

Conditional Visibility Binding
lastName.Bind(TextBox.VisibilityProperty,
    () => firstName.Text.Length > 0 ? Visibility.Visible :
        Visibility.Collapsed);

You can also use this to avoid writing IValueConverters and do inline binding in code very easily.

Lambda Binder
public static class LambdaBinder
{

    public static void Bind(
        this DependencyObject dest,
        DependencyProperty destProperty,
        Expression<Func<object>> func)
    {
        MultiBinding b = new MultiBinding();
        b.Converter = new MultiDelegateConverter(func.Compile());
        LambdaBindingBuilder bb = new LambdaBindingBuilder(b);
        bb.Visit(func.Body);
        BindingOperations.SetBinding(dest, destProperty, b);
    }

}

public class LambdaBindingBuilder : ExpressionVisitor
{
    private MultiBinding multiBinding;

    private string lastPath = null;

    public LambdaBindingBuilder(MultiBinding mb)
    {
        this.multiBinding = mb;
    }

    protected override System.Linq.Expressions.Expression VisitMember(MemberExpression node)
    {
        PropertyInfo p = node.Member as PropertyInfo;
        if (p != null) {
            if (string.IsNullOrWhiteSpace(lastPath))
            {
                lastPath = p.Name;
            }
            else {
                lastPath = p.Name + "." + lastPath;
            }
        }
        FieldInfo f = node.Member as FieldInfo;
        if (f != null) {
            Binding b = new Binding(lastPath);
            b.Source = System.Linq.Expressions.Expression.Lambda<Func<object>>(node).Compile()();
            multiBinding.Bindings.Add(b);
            lastPath = null;
        }
        return base.VisitMember(node);
    }

    protected override System.Linq.Expressions.Expression VisitConstant(ConstantExpression node)
    {
        if (!string.IsNullOrWhiteSpace(lastPath)) {
            Binding b = new Binding(lastPath);
            b.Source = node.Value;
            multiBinding.Bindings.Add(b);
            lastPath = null;
        }
        return base.VisitConstant(node);
    }
}

public class MultiDelegateConverter : IMultiValueConverter
{
    private Func<object> func;

    public MultiDelegateConverter(Func<object> func)
    {
        this.func = func;
    }

    public object Convert(object[] values,
        Type targetType,
        object parameter,
        System.Globalization.CultureInfo culture)
    {
        return func();
    }

    public object[] ConvertBack(object value,
        Type[] targetTypes,
        object parameter,
        System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

 

LambdaBinder is part of UI Atoms suite. At NeuroSpeech, we do research on UI and we are coming up with more interesting featues in UI Atoms.

Please Click Here to download latest update of UI Atoms with AtomForm including Tabs in the form.

Share
Tagged with:  

UI Atoms 1.5.8 Released

On January 11, 2011, in Programming, by Akash Kava

We are happy to announce new release of UI Atoms 1.5.8 with following new features.

UI Atoms for WPF 4.0

In this release of UI Atoms, we have a new library of dlls specially designed for WPF 4.0, which now includes support for Visual State Managers and renders everything in WPF 4.0 presentation. You can find Bin.Net4 folder inside WPF, that contains libraries only for WPF 4.0 version.

AtomForm Label Alignment for Silverlight and WPF

Silverlight-Form-Label-Alignment

AtomForm now provides following two properties,

  • LabelHorizontalAlignment property that can align the label horizontally in the form item.
  • LabelVerticalAlignment property that can align the label vertically in the form item.

Label Can now contain string or UI Element object

Rich Label Format
  1. <ns:AtomTextBox HorizontalAlignment="Stretch"
  2.                 Text="{Binding Path=ProjectName, Mode=TwoWay}" Width="Auto" >
  3.     <ns:AtomForm.Label>
  4.         <StackPanel Orientation="Horizontal">
  5.             <TextBlock>Name:</TextBlock>
  6.             <Image Source="/PrismTest;component/Images/Logo.png" Width="16" Height="16" />
  7.         </StackPanel>
  8.     </ns:AtomForm.Label>
  9. </ns:AtomTextBox>

Rich-Label-Silverlight-WPF-Form

 

Advanced Quick Form Designer

Typing Tags with all Bindings could be quite time consuming, where it involves moving items up and down, deleting and adding new Form Items. Advanced Quick Form Designer resolves all this problems by giving you state of art designer, which provides one quick grid to enter all necessary information. However the form designer works well even for existing forms, and you can generate entire new form by selecting some Type as well.

Advanced-Silverlight-WPF-Form-Designer

As you see, type of control can be changed that will represent the form item and corresponding binding property can be changed as well. Just with simple one click, you can move items up and down or delete them. You can add a new control that is defaulted to AtomTextBox at the top, you can change default control to add multiple one after another very easily. Also you can click “Generate From Type” to select any Business Object Type and generate a brand new form.

Generate-Form-From-Type-Silverlight-WPF

Selecting type will automatically generate form with its bindings.

Share
Tagged with:  

This tutorial outlines how to customize UI Atoms’ AtomForm appearance and layout simply by customizing its ItemContainerStyle.

AtomForm is derived from ItemsControl, and ItemsControl declares ItemContainerStyle which can customize the template of individual items that are being displayed. UI Atoms give you complete freedom of how to change your look and feel very easily by just adding a simple template in your resource dictionary.

 

Create New Item Container Style

To do this, open your xaml page in the Expression Blend and right click on the AtomForm. And choose Edit Additional Templates, and Select Edit Generated Item Container (ItemContainerStyle) and then click on “Edit a copy…”

SelectItemContainerStyle

Then choose a location to keep your style in,

ChooseStyle

Once the style editor is open, right click on “Style” and click on “Edit Template” and then click on “Edit Current”

ChooseCurrent

Now you will see the Item Container Style’s current Form Item template. Where you can change the colors and layout, for example, we have modified the Vertical Layout of “PART_Label” field as Top in this figure below.

ChangeLayout

Share
Tagged with:  

Enabling Tracing in Silverlight with UI Atoms

On June 19, 2010, in C#, by Akash Kava

UI Atoms 2010 v1.9 update now includes Trace API for developers to log information on screen just like normal .NET application.

Diagnostics Trace API

Microsoft .NET provided Trace API to help in troubleshoot problems which is of great help at time of development. But Silverlight developers are disappointed for not being able to trace in Silverlight apps. However running apps on multiple platform isn’t quite easy, and different user experiences on different platforms raise unexpected issues. Such issues are difficult to resolve as deployed client computer may not have development tools available to troubleshoot and see application logs.

Trace.WriteLine(“ Hello World “);

We sure miss Trace in Silverlight, so we decided to add similar diagnostics API in Silverlight.

Trace Viewer

In Silverlight, as it runs inside a browser, there is no way to see any trace information not only this, on different platforms like Mac, it may be too difficult for no technical user to install and enable remote debugging.

So we decided to include a visual component that can be put anywhere on screen, just like “Output” pane in visual studio. Its developer’s choice to fit the Trace Viewer. Its pretty simple Text View control, where in you can see lines of log automatically scrolling down as log grows.

AtomTraceView

UI Atoms’s AtomTraceView control works well with Silverlight as well as WPF, in WPF it uses inbuilt Trace functionality and displays trace information to user, and in Silverlight we have added custom API, that is used to display Trace information. Syntax is pretty simple.

<Grid>
   <Grid.RowDefintions>
       <RowDefinition/>
       <RowDefinition Height="200"/>
   <Grid.RowDefintions>

   <MyUserControl/>

   <AtomTraceView Grid.Row="1"/>

<Grid>

This way you can include AtomTraceView at the bottom of your page and it will display all traces programmed by the developer.

Limited API

However, .NET Trace API is very huge, and it is extensible, but Trace API offered by UI Atoms as of now is very limited, not by the design but by implications, Silverlight itself is very limited platform, this is just an Add-on for users to troubleshoot their apps.

Trace Statements in Silverlight

In order to write Trace statements, you have to import following namespace,

using NeuroSpeech.UIAtoms.Core;

Then you can write following statements and they will appear in AtomTraceView Control.

AtomTrace.WriteLine(" Hello World ");

AtomTrace.WriteLine( exception.ToString() );

AtomTrace.WriteLine( string.Format("{0},{1} Coordinates", x, y) );

 

The AtomTrace class exists for both Silverlight and WPF, so it becomes easier to write your logs with AtomTrace instead of Trace, so your code can be shared on both Silverlight as well as WPF.

Trace and Multithreading

Trace statements can be accessed by thread in Silverlight app, however the sequence in which it will appear can not be guaranteed because it depends upon the processor and scheduling algorithm used in thread pool of Silverlight application.

Custom Trace Listener

Just similar to .NET, we have included  AtomTraceListener class, which you can derive and customize trace information according to your need as well as it has Traced event, which you can implement and get trace notifications anywhere..

 

Future of Trace API in Silverlight

When Trace API will be included by Microsoft in future edition of Silverlight, we may plan to remove Trace API, to be consistent with the Silverlight development workflow, this API has been enabled only to write shared code between WPF and Silverlight environment. However otherwise, we plan to make tracing more rich with UI Atoms. But for now, it is very helpful for everyone.

Live Demo

Click Here to see live demo of Tracing in Silverlight.

Click Here to download demo version of UI Atoms 2010.

Share
Tagged with:  

Scientific calculations often require measurement unit conversion and demand high accuracy. Although it may be very easy to google around the web and get some formula, however when we looked into SI units and its Unit Guide, then we realized that even units with same name have little different value in different countries and continents.

So we decided to bring them all into User Interface control for WPF and Silverlight.

  1. Which allows Developer to adhere to one standard unit.
  2. Which allows users to choose unit of their own choice.
  3. See the conversion while editing the value.

MeasurementControlPart1

 

The following sample code displays how to use these unit converters in Silverlight and WPF.

Properties

Each of the measurement unit converter controls has four properties as mentioned below.

DisplayValue Property:

This is the editable value displayed in the text box, and user can directly modify this value by either using up/down arrow buttons or by typing in the value. The display value works in conjunction with the type of unit that is selected in Display Unit ID property.

DisplayUnitID Property:

Every measurement unit has different ID assigned by our developers to uniquely identify alpha numeric ID within the set of units. For example, meter and centimeter are IDs of Length. However you do not have to remember these IDs, when you edit your UI in Visual Studio, you can configure these IDs in the property editor. End user can visually modify Display Unit in order to retrieve and enter value in the desired unit.

ValueUnitID Property:

The DisplayUnitID is attached to DisplayValue, similarly the underlying actual value is attached with ValueUnitID property. This Unit ID is usually set to a constant throughout the lifetime of the application and is already defaulted to SI unit. e.g. for Length, it is set to meter. We recommend you to change this only if your base unit requirement is something different then SI unit. This unit can not be changed by end user it can only be programmed in the code at design time.

Value Property:

The value property is something which you are interested saving in the database and use it as base value. This is the converted value of unit ValueUnitID specified from display value of display unit.

Example:

In the first control in the above picture, Display Value is 100, Display Unit is Fathom, Value Unit is meter, so converted value in meter is 182.8804.

Live Sample:

Click here to view live sample in Silverlight.

Download Demo:

Click here to download the demo version of UI Atoms.

Share
Tagged with:  

UI Atoms 2010 v1.1 Released

On May 5, 2010, in C#, Programming, by Akash Kava

New update of UI Atoms 2010 v1.1 is now available, it includes fixes for Silverlight 4 and new controls as per following list.

Update 1.1

  1. UI Atoms is now upgraded to Silverlight 4, all binding workarounds have been removed.
  2. Six New Measurement Unit Controls have been added.

Measurement Unit Controls

Scientific measurements are complex and wide range of units are used everywhere, though conversions are not difficult but it is not possible to carry and remember all conversions and correct formulae.

UI Atoms 2010 v1.1 brings power of SI units conversion in set of following Measurement Unit Controls.

  • AtomLengthEditor – helps in conversion of “Length” units.
  • AtomTemperatureEditor – helps in conversion of “Temperature” units.
  • AtomTimeEditor – helps in conversion of “Time” units.
  • AtomVelocityEditor – helps in conversion of “Velocity” units.
  • AtomVolumeEditor – helps in conversion of “Volume” units.
  • AtomWeightEditor – helps in conversion of “Weight” units.

MeasurementControls Currently, these controls offers very simple GUI as first draft, however you can see the number of units that are available that can help users view/edit the value in any desired unit.

Share
Tagged with:  

This is Preliminary documentation about UI Delegation Pattern to create Clean and Reusable Data Components and UI Markups in a Business Application.

UI Delegation Pattern

I would call it simply divide and rule, UI Delegation Pattern is narrowing the focus towards piece of UI Element on the screen and have a UI component to fulfill every specific business needs.

User Interface is the direct connection between User and your business application, thought MVC, MVVM models exist, but they are found to be very useful in CRUD business applications, but when your application is more then CRUD and it involves complex UI and media / hardware interfaces for scientific and entertainment related applications, MVC/MVVM are little difficult to maintain over huge applications. This pattern is already in existence at many places.

Initial Rough Draft

This is initial rough draft, I intend to collect problems and solutions and then I want to give a good name to this pattern, for now I am calling this as “UI Delegation Pattern” however I don’t know whether it suits the name correctly or not. But your opinions are most welcome, if such pattern is already named and exists then I am sorry if I am unaware of it, but please suggest if you know so.

UI Markup vs. Editor Files

Earlier Visual Basic or Visual Studio would create .frm and resource files that would contain the contents of UI design created in “Designer/Editor” inside an IDE. These Editors would create code that is required to execute at runtime to create desired user interface. However since Editors would create code with specific style and pattern, these editor files are more or less very structured and they are less buggy. Of course too much of code will certainly make Editor very slow but at the same time, the consistency of UI code is preserved. But you are too much dependent on the Editor and complex UI could be very difficult to work in Editors.

Where else UI Markup based on xml, gives full freedom to user to create highly complex UI, but at the same time there is no consistency left as everyone writes code very differently. Markups gets piled into one file and it becomes way to difficult to maintain and understand how it works.

Identify Markup Noise

My first approach is to identify problems with Markup Noise, so lets identify what is markup noise. When I see any html, aspx, php or such web scripts, the most annoying things I discover that in spite  great CSS and Modular programming support, the scripts becomes a big junk to maintain. Sure WPF / Silverlight are also text markups, hand coded markups becomes way to big junk to manage.

Bigger problem is to visualize markups as they become more complex. As more and more lines of code gets piled into markup, more time is spent understanding and troubleshooting the UI.

How to Reduce Markup Noise?

CSS brought a very useful way to reduce markup noise. Still lot of developers write inline styles and I hate to see that. Ideally nicely written code should have inline styles as small as possible.

Appearance Delegation

CSS comes under category of Appearance Delegation where your delegate the look and feel of your component to CSS file. In WPF and Silverlight the themes are styles are introduced and you must have all your styles and look and feel related code into resources only.

The markup containers (Connection Containers) such as Window / Page / User Control should not have any inbuilt styles at all.

Business Logic Delegation

This was not possible in plain html, but aspx, php etc did brought concept of server side controls where in you could inject business logic specific to components and reuse them. But these components (user controls / custom controls ) are only designed when they need to be reused, but even if it will be used only once, I would still suggest its better to have components as small as possible.

Example, Country Combo drop down , Gender Combo drop down, these boxes are nothing but set of options provided to user to select one of them. Now nobody makes specific custom controls for such items, but lets see a practical example.

Bad Markup Example

    <Window.Resources>
        <XmlDataProvider x:Key="CountryData" XPath="/Countries">
            <Countries xmlns="">
                <Country
                    CountryName="United States"
                    CountryCode="US"/>
                <Country
                    CountryName="United States"
                    CountryCode="US"/>
            </Countries>
        </XmlDataProvider>
    </Window.Resources>
    <StackPanel>

        <ComboBox
            ItemsSource="{Binding Source={StaticResource CountryData},
                XPath=Country}"
            DisplayMemberPath="@CountryName"
            SelectedValuePath="@CountryCode"
            />

        <ComboBox>
            <sys:String>Male</sys:String>
            <sys:String>Female</sys:String>
        </ComboBox>

    </StackPanel>

Now this file defines a resource xml for Country List, and it is bounded by ComboBox to list countries and another ComboBox defines inline items to be displayed.

Let us identify “Controls and Connection Containers”.

The window, that hosts Country List and Gender Combo Boxes is “Connection Container” in which we should only host controls and connect inter dependent properties of every controls.

The Connection Container should not have any code that is not related to either any other items or business logic of the container at all.

List of Countries and Gender items are not at all related to anyone else except for the drop downs. This is pure markup junk where we have so many unnecessary information.

Solution

Define custom controls as shown below and see how small our markup becomes. And move Country List xml to some resource file.

    public class CountryComboBox : ComboBox
    {

        public CountryComboBox()
        {
            this.DisplayMemberPath = "@CountryName";
            this.SelectedValuePath = "@CountryCode";

            Binding b = new Binding();
            b.XPath = "Country";
            b.Source = FindResource("CountryData");
            this.SetBinding(ItemsSourceProperty, b);
        }

    }

    public class GenderComboBox : ComboBox
    {
        public GenderComboBox()
        {
            this.ItemsSource =
                new string[] {
                    "Male",
                    "Female"
                };
        }
    }

 

The final Markup.

    <StackPanel>

        <local:CountryComboBox
            />

        <local:GenderComboBox
            />

    </StackPanel>

 

Wow, the markup is very clean now. Also the code is easy to understand.

Conclusion

The connection container (Window / Page / User Control) should only have interdependent declarations and should not have any items that are only specific to one control. It should be as clean as possible and it should execute all necessary business logic for the component.

Configuration items, even resource bindings should be avoided in Connection Containers. They should be narrowed down to custom controls as much as possible.

This increases readability, reusability and helps in troubleshooting while focusing by narrowing the target.

Share
Tagged with: