# Friday, June 25, 2010

Silverlight 4 supports the resolution of relative service addresses. Provided the Silverlight XAP package is hosted at http://somesite.com/application/ClientBin/Application.xap, the following address resolve as indicated:

"../Service1/Service.asmx" resolves to “http://somesite.com/application/Service1/Service.asmx”

For you, CSWorks users out there, it means one good thing: no more ServiceReferences.ClientConfig hassle, see Running CSWorks demo applications from remote clients post for details. Now you can simply specify relative service addres as follows:

<endpoint address="../LiveDataWebService/Service.asmx" ...>

and your CSWorks application will work from any website you deploy it to. Switching to Silverlight 4 pays off!

demo | wcf
Sergey Sorokin   Friday, June 25, 2010 9:59:41 AM (Pacific Daylight Time, UTC-07:00)  #     |  Comments [0]  | 
# Monday, April 19, 2010

Resizable controls - what's the problem?

To save HMI screen space, application developers may want to make some controls resizable. Applying ScaleTransform is not a problem and is a good solution in many cases. See Pipes and Tanks Demo for example - it uses ScaleTransform and redraws screen content when a user changes browser window size.

Unfortunately, ScaleTransform is not an optimal solution when dealing with complex UI elements, especially those containing some amount of text - some pieces may look ugly, some may become too small to be useful. The only solution is to make complex controls able to react to the 'SizeChanged' event and recalculate internal layout at runtime. Latest version of Alarm Summary and Trend Control can do that, and this post shows how application developers can use this functionality.

We will need a container control that lets user change its size, and a piece of code that passes the changes to CSWorks controls. You can develop your own container control (there are a lot of examples available in the web) or use an existing third-party container control for that. I will use RadWindow from Telerik in this example - it serves the purpose quite well.

Resizable Alarm Demo

1. Download Rad Controls for Silverlight trial package from www.telerik.com (DLLs only).
2. Unzip downloaded archive to "C:\Program Files\CSWorks\Demo\Src\tps\Telerik". Telerik DLLs will be unpacked to "C:\Program Files\CSWorks\Demo\Src\tps\Telerik\Binaries\Silverlight\".
3. Open Alarm Demo project ("C:\Program Files\CSWorks\Demo\Src\AlarmDemo\") in Visual Studio.
4. We will use RadWindow control implemented in Telerik.Windows.Controls.Navigation.dll. Add Telerik.Windows.Controls.Navigation.dll and Telerik.Windows.Controls.dll to the reference list for Alarm Demo project.
5. Open Page.xaml file. Add 'telerik' namespace to the UserControl element:

<UserControl ...
  xmlns:telerik="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Navigation"
... >


6. Replace control content with a grid that contains RawWindow that contains CSWorks Alarm Summary, and add SizeChanged event handler for RadWindow:

<Grid>
  <telerik:RadWindow x:Name="radWindow" SizeChanged="OnSizeChanged">
    <telerik:RadWindow.Header>
      <TextBlock Text="Alarm Demo"/>
    </telerik:RadWindow.Header>
    <alarm:AlarmSummary ... />
  </telerik:RadWindow>
</Grid>


7. Open Page.xaml.cs file, implement SizeChanged event handler that adjusts AlarmSummary height and width when RadWindow size is changed: 

private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
  GeneralTransform gtGlobal = alarmSummary.TransformToVisual(radWindow);
  Point leftTopGlobal = gtGlobal.Transform(new Point(0, 0));

  alarmSummary.Height = radWindow.Height - radWindow.BorderThickness.Bottom - leftTopGlobal.Y - 4.0;
  alarmSummary.Width = radWindow.Width - leftTopGlobal.X * 2;
}


8. Update Loaded event handler so RadWindow shows itself after page is loaded:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
  ...
  radWindow.Show();
}


9. Rebuild the project and run Alarm Demo from Start Menu. Resize RadWindow and watch Alarm Summary changing its layout:

Resizable Trend

You can do the same to CSWorks Trend control.

1. Open Trend Demo project ("C:\Program Files\CSWorks\Demo\Src\TrendDemo\TrendDemo.Sample.csproj")
2. Add Telerik.Windows.Controls.Navigation.dll and Telerik.Windows.Controls.dll to the reference list.
3. Open MainPage.xaml file. Add 'telerik' namespace as shown above.
4. Change xaml so RadWindow contains TrendControl:

<Grid>
  <telerik:RadWindow x:Name="radWindow" SizeChanged="OnSizeChanged">
    <telerik:RadWindow.Header>
      <TextBlock Text="Trend Demo"/>
    </telerik:RadWindow.Header>
    <t:Trend ...>
      ...
    </t:Trend>
  </telerik:RadWindow>
</Grid>


5. Open MainPage.xanl.cs. Add OnSizeChanged handler:

private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
  GeneralTransform gtGlobal = _demoTrend.TransformToVisual(radWindow);
  Point leftTopGlobal = gtGlobal.Transform(new Point(0, 0));

  _demoTrend.Height = radWindow.Height - radWindow.BorderThickness.Bottom - leftTopGlobal.Y - 4.0;
  _demoTrend.Width = radWindow.Width - leftTopGlobal.X * 2;
}


6. Show RadWindow on startup:

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
  ...
  radWindow.Show();
}


7. Rebuild the project and run Trend Demo from Start Menu. Resize RadWindow and watch Trend control changing its layout: 


Sergey Sorokin   Monday, April 19, 2010 2:11:23 PM (Pacific Daylight Time, UTC-07:00)  #     |  Comments [0]  | 
# Monday, March 15, 2010

CSWorks client framework is all about third-party UI components. As of this writing, all major Silverlight component providers have come up with their versions of the Gauge control. In this example, I will show how you can integrate Telerik and/or ComponentOne gauge controls into CSWorks Pipes and Tanks Demo application. The result will look like this:



Here are the steps to make it work.

1. Download Telerik Silverlight controls (dlls only) and ComponentOne Studio Trial Package for Silverlight.
2. Create a folder for third-party controls - C:\Program Files\CSWorks\ThirdParty.
3. Unpack downloaded Telerik archive and install ComponentOne package.
4. Copy Telerik assemblies (Telerik.Windows.Controls.Gauge.dll, Telerik.Windows.Controls.dll, Telerik.Windows.Data.dll) and ComponentOne assemblies (C1.Silverlight.dll, C1.Silverlight.Gauge.dll) to ThirdParty folder.
5. Open C:\Program Files\CSWorks\Demo\Src\PipesAndTanksDemo\PipesAndTanksDemo.Sample.csproj in Visual Studio.
6. Add all copied third party assemblies to the project reference list.
7. Open Page.xaml and add third-party namespaces to the namespace list:

<UserControl x:Class="CSWorks.Client.PipesAndTanksDemo.Page"
  ...
  xmlns:tcontrol="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Gauge"
  xmlns:tgauge="clr-namespace:Telerik.Windows.Controls.Gauges;assembly=Telerik.Windows.Controls.Gauge"
  xmlns:c1gauge="clr-namespace:C1.Silverlight.Gauge;assembly=C1.Silverlight.Gauge"

  ...>


8. Add gauge controls to the page and bind them to LeftPumpSpeed and RightPumpSpeed data items:

<controls:TabItem Header="HMI Controls View">
    <Canvas>
        ...
        <Grid ...>
            ...
            <Border ...>
              ...
            </Border>

            <!-- Telerik Gauge for left pump -->
            <Border Grid.Row="1" Grid.Column="5" Grid.RowSpan="1" Grid.ColumnSpan="3" Background="White" BorderBrush="Black" BorderThickness="1" CornerRadius="5" Padding="5,0,5,0" Margin="0,10,0,-10">
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="Telerik Gauge" Foreground="Black" FontSize="8" HorizontalAlignment="Center"/>
                    <tcontrol:RadGauge x:Name="radGauge" VerticalAlignment="Bottom" >
                        <tgauge:RadialGauge  >
                            <tgauge:RadialScale Min="0" Max="200" LabelRotationMode="None" FontSize="7">
                                <tgauge:RadialScale.Label>
                                    <tgauge:LabelProperties FontSize="4.5"/>
                                </tgauge:RadialScale.Label>
                                <tgauge:RangeList>
                                    <tgauge:RadialRange Min="0" Max="100" StartWidth="0.05" EndWidth="0.05" Background="Green"/>
                                    <tgauge:RadialRange Min="100" Max="160" StartWidth="0.05" EndWidth="0.05" Background="Orange"/>
                                    <tgauge:RadialRange Min="160" Max="200" StartWidth="0.05" EndWidth="0.05" Background="Red" />
                                </tgauge:RangeList>
                                <tgauge:IndicatorList>
                                    <tgauge:Needle Value="{Binding Value, Mode=OneWay, Source={StaticResource LeftPumpSpeed}}"/>
                                </tgauge:IndicatorList>
                            </tgauge:RadialScale>
                        </tgauge:RadialGauge>
                    </tcontrol:RadGauge>
                    <TextBlock Text="rpm" Foreground="White" FontSize="7" HorizontalAlignment="Center" VerticalAlignment="Bottom"  Margin="0,-30,0,30"/>
                </StackPanel>
            </Border>

            <!-- ComponentOne Gauge for right pump -->
            <Border Grid.Row="1" Grid.Column="9" Grid.RowSpan="1" Grid.ColumnSpan="3" Background="White" BorderBrush="Black" BorderThickness="1" CornerRadius="5" Padding="5,0,5,0" Margin="0,10,0,-10">
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="C1 Gauge" Foreground="Black" FontSize="8" HorizontalAlignment="Center"/>
                    <c1gauge:C1RadialGauge  Minimum="0" Maximum="200" Value="{Binding Value, Mode=OneWay, Source={StaticResource RightPumpSpeed}}">
                        <c1gauge:C1GaugeLabel Interval="20" Foreground="Black" Format="#" FontSize="6" FontWeight="200" Location="0.85"/>
                        <c1gauge:C1GaugeRange From="0" To="100"  Fill="Green" Location="0.45"/>
                        <c1gauge:C1GaugeRange From="100" To="160"  Fill="Orange" Location="0.45"/>
                        <c1gauge:C1GaugeRange From="160" To="200"  Fill="Red" Location="0.45"/>
                        <c1gauge:C1GaugeMark Interval="20" />
                    </c1gauge:C1RadialGauge>
                    <TextBlock Text="rpm" Foreground="Black" FontSize="7" HorizontalAlignment="Center" VerticalAlignment="Bottom"  Margin="0,-30,0,30"/>
                </StackPanel>
            </Border>


            <TextBlock Text="All UI elements ..." .../>
          </Grid>
          ...
    </Canvas>
</controls:TabItem>


9. Build the project and start Pipes and Tanks Demo from your start menu. Enjoy professional-looking controls in action.

Sergey Sorokin   Monday, March 15, 2010 9:47:19 AM (Pacific Standard Time, UTC-08:00)  #     |  Comments [1]  | 
# Monday, March 08, 2010

After installing CSWorks, many of you are tempted to connect it to your OPC data source. Here is a quick step-by-step guide how you can do that in five minutes.

In this example, I will assume we are dealing with Matrikon OPC Simulation Server - you can download it for free from Matrikon website. After installing Matrikon components, you can start tweaking CSWorks Pipes and Tank Demo so it uses data from Matrikon OPC Server.

Add new data source to LiveData Service configuration

Add a few lines to C:\Program Files\CSWorks\Framework\Server\CSWorks.Server.LiveDataService.exe.config:

    <opcLiveDataSources type="CSWorks.Server.DataSource.Opc.OpcLiveDataSource, CSWorks.Server.OpcProvider">
      ...
      <opcLiveDataSource name="OpcMatrikon" sampleBufferLength="16" hostName="localhost" progId="Matrikon.OPC.Simulation.1" subscriptionUpdateRate="250">
        <templates>
          <template name="matrikonBoolTag" type="Boolean" readPath="Random.Boolean" canWrite="true"/>
        </templates>
      </opcLiveDataSource>

    </opcLiveDataSources>


Restart LiveData Service so your changes take effect and the service connects to the data source.

Add new data source to LiveData Server topology configuration

Add one line to C:\Program Files\CSWorks\Demo\Web\LiveDataWebService\web.config:

  <liveDataTopology>
    <liveDataPartitions>
      <liveDataPartition name="partition1" primaryLiveDataServer="liveDataServer_1_primary" secondaryLiveDataServer="">
        <dataSources>
          ...
          <dataSource name="OpcMatrikon"/>
        </dataSources>
      </liveDataPartition>
    </liveDataPartitions>
  </liveDataTopology>


Now LiveData Web Service knows where to get data for OpcMatrikon data source.

Modify demo application

Run Microsoft Visual Studio and open Pipes and Tanks Demo project at C:\Program Files\CSWorks\Demo\Src\PipesAndTanksDemo\PipesAndTanksDemo.Sample.csproj. Let's make several additions to the Page.xaml file.

Add a new data item that gets data from the boolean tag configured for Matrikon OPC Server:

    <UserControl.Resources>
        ...
        <d:BoolDataItem x:Key="TestValve" Id="type in new guid here" DataSource="OpcMatrikon" TemplateName="matrikonBoolTag" Parameters=""/>
    </UserControl.Resources>



Add a few visual elements to the upper left corner of the screen and bind them to the new data item:

        <controls:TabControl...>
            <controls:TabItem Header="HMI Controls View">
                <Canvas>
                    ...
                    <Grid ...>
                          ...
                      </Grid.ColumnDefinitions>

                        <pipes:RightValve Grid.Row="0" Grid.Column="3" IsOpen="{Binding Value, Mode=OneWay, Source={StaticResource TestValve}}" OpenColor="Black" ClosedColor="Black" IsEnabled="False" Margin="-16,0,16,0"/>
                        <PipesAndTanksDemo:Wireframe Grid.Row="0" Grid.Column="3" Status="{Binding Status, Mode=OneWay, Source={StaticResource TestValve}}" Margin="-16,0,16,0"/>
                        <pipes:RightTWay Grid.Row="0" Grid.Column="2" IsFilled="{Binding Value, Mode=OneWay, Source={StaticResource TestValve}}" FillColor="Coral" Margin="-16,0,16,0"/>
                        <PipesAndTanksDemo:Wireframe Grid.Row="0" Grid.Column="2" Status="{Binding Status, Mode=OneWay, Source={StaticResource TestValve}}" Margin="-16,0,16,0"/>

                        ...


Now we have a valve and a t-way joint that supply some coral-colored liquid to Tank 1. Also, we have added a couple of Wireframe elements that will tell us if something is wrong with Matrikon boolean tag.

Time to tell DataManager that we have a new data item. Add a command to the Page_Loaded() handler in Page.xaml.cs:

        void Page_Loaded(object sender, RoutedEventArgs e)
        {
          ...
          dataManager.DataItems.Add(Resources["TestValve"] as DataItem);


Do not forget to update the id of the datamanager in the Page.xaml, otherwise LiveData Service will keep using cached list of required data items and Matrikon tag value will never be returned:

        <d:DataManager x:Key="DataManager" Id="type in new guid here" />

We are done. Build client application and run it at http://localhost/CSWorksDemo/PipesAndTanksDemo.html (or click Start menu and choose All Programs -> CSWorks ->  Client Samples -> Pipes and Tanks Demo). The left upper corner of the screen will have some new visual elements - see screenshot.

Security Issues

In the case of Matrikon Simulation OPC Server, we did not have any issues with COM/DCOM security, because Matrikon installer lets everyone access this OPC Server. You can verify it by running dcomcnfg.exe tool and checking out Matrikon Simulation OPC Server configuration - it explicitly says that "Everyone" has "Launch and Activation" and "Access" permissions for this component, see screenshot.

This cannot be considered safe practice, but makes casual user's life a bit easier. Not all OPC server providers write installers that allow the whole world to access their components. In some cases, you may get notorious "Access Denied" COM/DCOM error 0x80070005 when CSWorks accesses OPC server. Stay tuned - there will be a post dedicated to COM/DCOM security.

demo | opc
Sergey Sorokin   Monday, March 08, 2010 11:48:03 AM (Pacific Standard Time, UTC-08:00)  #     |  Comments [0]  | 
# Friday, March 05, 2010

When someone runs CSWorks Pipes and Tanks Demo application for the first time, the first question is: where all this data for pipes, tanks and valves comes from?

CSWorks installation package includes LiveData Emulator OPC Server component that simulates mixing process and accepts input from the user when he/she opens and closes the valves and changes mixing speed. LiveData Emulator OPC Server is useless for real-world applications but works well as a simple data source for the demo.

In order to make sure that CSWorks displays actual data supplied by this OPC data source, you may want to set up a quick demonstration and see how numbers are changing simultaneously in the demo and in your favourite OPC viewer application.

First off, if you just run OPC viewer on the demo machine and connect it to CSWorks LiveData Emulator OPC Server you will see some tags changing, but those changes won't be in sync with the demo values. This happens because of the way COM/DCOM (and OPC) works.

Unless you configured it otherwise, CSWorks LiveData Service runs under Network Service user account - a special Windows account many system services run under. When CSWorks LiveData Service is being told to access an OPC server (Emulator OPC Server in our case), it instantiates it through COM/DCOM infrastructure. By default, a COM server is started as a separate process on behalf of the launching user - Network Service. If you have a look at the process list while CSWorks demo is running you will see LiveData Emulator process running under Network Service account.

Now you run an OPC viewer application and connect it to CSWorks LiveData Emulator OPC Server. Have a quick look at the process list again - you will see that now you have another instance of LiveData Emulator process running under your personal account. So you have two emulators supplying different data to CSWorks and to the OPC viewer.

Let's make both CSWorks and OPC viewer use the same instance of the emulator. Please use Windows Service Manager to configure CSWorks LiveData Service so it runs under you personal account (say, Administrator). Also use DCOM configuration tool (dcomcnfg.exe) to make sure that LiveData OPC Emulator:

  • can be launched (Properties - Security - Launch and Activation Permissions) and accessed (Properties - Security - Access Permissions) by your personal account;
  • is instantiated runs under interactive user account (Properties - Identity).


This screenshot shows what has to be done.

After doing that, restart CSWorks LiveData Service and your OPC viewer, so they start using properly configured LiveData OPC Emulator server. The screenshot shows three application windows: two Internet Explorer instances with CSWorks demo application, and a third-party OPC viewer that is configured to receive updates for "storage.numeric.reg01" tag. This is the item that CSWorks demo application uses to store Tank 1 fill level.

As CSWorks LiveData Emulator changes Tank 1 fill level, you see it changing in all three windows simultaneously. Perfect, we get the same data in all three windows.

After demonstrating CSWorks live data in action, do not forget to revert all changes made in DCOM configuration and service manager.

demo | opc
Sergey Sorokin   Friday, March 05, 2010 2:07:31 PM (Pacific Standard Time, UTC-08:00)  #     |  Comments [0]  | 
# Wednesday, February 24, 2010

One of the first things I would do after installing CSWorks is to open a browser on another machine in the network and type in "http://MyTestBox/CSWorksDemo/PipesAndTanksDemo.html", where MyTestBox is the name of the machine where I installed CSWorks.

This doesn't work. And it's not supposed to work because of the cross-domain web service call restrictions imposed by your browser. If you have a look at ServiceReferences.ClientConfig file in the Pipes and Tanks Demo xap package (CSWorks.Client.PipesAndTanksDemo.xap in your CSWorksDemo/ClientBin folder; don't worry it's just a ZIP file with XAP extension), you will find endpoint description for LiveData web service calls that looks as follows:



In our case, when Silverlight is trying to make a web service call to http://localhost/CSWorksDemo/LiveDataWebService/Service.asmx, the browser checks the URL of the application which happens to start with "http://MyTestBox". Since it doesn't start with "http://localhost", the browser considers this a potential security threat and blocks the call.

To make things work, just replace "localhost" in the config file with the name (or IP address) of your CSWorks server:



and save updated config to the xap file. Now refresh the page in the browser on the remote machine - Pipes and Tanks Demo should work fine.

Update (June 25, 2010):

with Silverlight 4, you can use relative web service addresses, see this post for details.

Sergey Sorokin   Wednesday, February 24, 2010 4:24:27 PM (Pacific Standard Time, UTC-08:00)  #     |  Comments [0]  |