DCSIMG
October 2011 - Posts - Life Michael

October 2011 - Posts

Dependency Property in .NET

The dependency property is a property that can be set directly by various different property providers while having them prioritized. The dependency property depends on multiple property providers. Each one of them has its own level of precedence. We use dependency properties just as any other property. There is no need knowing in advance that a property we work with is a dependency property. Some of the available silverlight features (e.g. binding) are limited to dependency properties. The attached properties are sort of dependency properties. Any property that we bind, style, template, transform or animate must be a dependency property. Dependency properties are not always needed. When customizing our application most likely we will eventually end up with the need for having dependency properties. The dependency properties acts as kind of wrappers around a field. The dependency properties are kind of a replacement for a field a standard property wraps.

In order to define a dependency property we should first instantiate the System.Windows.DependencyProperty class. This new object will represent the dependency property. The dependency property needs to be always available and for that reason we define it as a static field in the associated class. The field that defines a dependency property has the name of the ordinary property plus the word Property at its end. This way the dependency property definition is separated from the actual property. The field should be defined redonly. This way its value can be set within the static constructor only.

The next step should be registering the dependency property with the Silverlight platform. We should complete this registration before we start using the property. Therefore, we will usually perform this required registration within the scope of the static constructor we define in the associated class. We create a DependencyProperty instance by calling the static DependencyProperty.Register() method.

The actual storage of the dependency property value is automatically taken care of, deep inside the WPF property system. The class that contains a dependency properties must derive from DependencyObject. Defining a class that extends UIElement we fulfill this requirement.

The following is a simple code sample for defining a dependency property. You can follow this sample as a template for your own usage.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace ConsoleApplication14
{
    public class Program
    {
        static void Main(string[] args)
        {
            Book book = new Book();
            book.Title = "Core Python";
            Console.WriteLine("### "+book.Title+" ###");
            book.Title = "abc";
            Console.WriteLine("### " + book.Title + " ###");
            book.Title = "Core PHP";
            Console.WriteLine("### " + book.Title + " ###");
            book.Title = "a";
            Console.WriteLine("### " + book.Title + " ###");
        }
    }
    public class Book : DependencyObject
    {
        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register(
                "Title",
                typeof(string),
                typeof(Book),
                new PropertyMetadata(
                    "No Name", TitleChangedCallback, TitleCoerceCallback),
                TitleValidateCallback);

        private static void TitleChangedCallback(
            DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            Console.WriteLine("Log Message: within TitleChangedCallback");
            Console.WriteLine(e.OldValue + " " + e.NewValue);
        }

        private static object TitleCoerceCallback(DependencyObject obj, object o)
        {
            Console.WriteLine("Log Message: within TitleCoerceCallback");
            string str = o as string;
            //here we can validate the title and change it if needed
            if(str.Length>0)
            {
                Console.WriteLine("new title is OK");
            }
            else
            {
                Console.WriteLine("new title is not OK");
                Console.WriteLine("will set 'no name' instead");
                str = "no name";
            }
            return str;
        }

        private static bool TitleValidateCallback(object value)
        {
            Console.WriteLine("Log Message: within TitleValidateCallback");
            //return true if there is a place to call the validation method
            return value != null && ((string) value).Length > 2;
        }

        public string Title
        {
            get
            {
                return (string)GetValue(TitleProperty);
            }
            set
            {
                SetValue(TitleProperty, value);
            }
        }
    }

}
The following video clip explains the above code sample.

Silverlight Initialization Parameters

We can easily pass initialization parameters from the HTML code that invokes the Silverlight application to the Silverlight application itself. The parameters should be placed as key value pairs, while the keys are their names and the values are the values of each one of them, as a string which is the value of a parameter placed as a child element of the Silverlight application object element. The name of that parameter should be initParams.
<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>SilverlightApplication19</title>
    <style type="text/css">
    html, body {
	    height: 100%;
	    overflow: auto;
    }
    body {
	    padding: 0;
	    margin: 0;
    }
    #silverlightControlHost {
	    height: 100%;
	    text-align:center;
    }
    </style>
    <script type="text/javascript" src="Silverlight.js"></script>
    <script type="text/javascript">
        function onSilverlightError(sender, args) {
            var appSource = "";
            if (sender != null && sender != 0) {
              appSource = sender.getHost().Source;
            }

            var errorType = args.ErrorType;
            var iErrorCode = args.ErrorCode;

            if (errorType == "ImageError" || errorType == "MediaError") {
              return;
            }

            var errMsg = "Unhandled Error in Silverlight Application " +  appSource + "\n" ;

            errMsg += "Code: "+ iErrorCode + "    \n";
            errMsg += "Category: " + errorType + "       \n";
            errMsg += "Message: " + args.ErrorMessage + "     \n";

            if (errorType == "ParserError") {
                errMsg += "File: " + args.xamlFile + "     \n";
                errMsg += "Line: " + args.lineNumber + "     \n";
                errMsg += "Position: " + args.charPosition + "     \n";
            }
            else if (errorType == "RuntimeError") {
                if (args.lineNumber != 0) {
                    errMsg += "Line: " + args.lineNumber + "     \n";
                    errMsg += "Position: " +  args.charPosition + "     \n";
                }
                errMsg += "MethodName: " + args.methodName + "     \n";
            }

            throw new Error(errMsg);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server" style="height:100%">
    <div id="silverlightControlHost">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
		  <param name="source" value="ClientBin/SilverlightApplication19.xap"/>
		  <param name="onError" value="onSilverlightError" />
		  <param name="background" value="white" />
		  <param name="minRuntimeVersion" value="4.0.50826.0" />
		  <param name="autoUpgrade" value="true" />
          <param name="initParams" value="lang=hebrew,country=israel" />
		  <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0"
                style="text-decoration:none">
 			    <img src="http://go.microsoft.com/fwlink/?LinkId=161376"
                alt="Get Microsoft Silverlight" style="border-style:none"/>
		  </a>
	    </object>
        <iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px">
        </iframe>
    </div>
    </form>
</body>
</html>
In our Silverlight application we can access the value of the initParams parameter from within the scope of the App class definition.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication19
{
    public partial class App : Application
    {
        public string Language { get; set; }
        public string Country { get; set; }
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;
            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new MainPage();
            if (e.InitParams.ContainsKey("country"))
            {
                this.Country = e.InitParams["country"];
            }
            else
            {
                this.Country = "Unknown Country";
            }
            if (e.InitParams.ContainsKey("lang"))
            {
                this.Language = e.InitParams["lang"];
            }
            else
            {
                this.Language = "Unknown Language";
            }
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled.
                // For production applications this error handling should be replaced with something that will
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(
                    delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");
                System.Windows.Browser.HtmlPage.Window.Eval(
                    "throw new Error(\"Unhandled Error in Silverlight Application " +
                    errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}
Once we took care of placing the values of the initialization parameters within properties accessible from within our code we can now access from every page in our Silverlight application. Referring Application.Current returns the reference for the App object currently running.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication19
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Button1Click(object sender, RoutedEventArgs e)
        {
            CountryTextBox.Text = ((App)Application.Current).Country;
            LangTextBox.Text = ((App)Application.Current).Language;
        }
    }
}
The following video clip shows how does it work.

Posted by life | with no comments

The Image Stretch Property in Silverlight

The Stretch possible values include Fill, None, Uniform which is the default value and UniformToFill. Fill will stretch the image in width and height to fit the Image element. None will keep the image native size. Uniform will set the largest possible size while keeping the aspect ratio unchanged. UniformToFill will size the width and the height proportionately until the image fills the available height and width.
<UserControl x:Class="SilverlightApplication15.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <Button>
            <Image Source="mypix.png" />
        </Button>
    </Grid>
</UserControl>
The following video clip shows the execution of this code sample and provides more information.

Posted by life | with no comments

Using new Font Families in Silverlight

Using a new font family in a Silverlight application is fairly simple. There are several ways for doing it. The simplest of them is adding the TTF file to our application (simple drag & drop when using the Visual Studio IDE) and referring it from within the XAML file.
<UserControl x:Class="SilverlightApplication15.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock FontSize="24" FontFamily="Foo.ttf#Foo">We Love Silverlight!</TextBlock>
    </Grid>
</UserControl>
The following video clip shows how does it work.

Posted by life | with no comments

Creating Tooltips in Silverlight

The tooltips are represented by the ToolTip content control. We don't need to add a ToolTip element. We can set an attached property and the Silverlight platform will create the tool tip automatically.
<UserControl x:Class="SilverlightApplication15.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <Canvas>
        <Button FontSize="22" 
                ToolTipService.ToolTip="This is a Simple Tooltip" 
                Content="OK"></Button>
    </Canvas>
</UserControl>
The following video clip explains this code sample.

We can easily create a customized tool tip by using the ToolTipService.ToolTip associated property.

<UserControl x:Class="SilverlightApplication15.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Canvas>
        <Button FontSize="22" Content="OK">
            <ToolTipService.ToolTip>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="This is The First Text" />
                    <TextBlock Text="This is The Second Text" />
                    <TextBlock Text="This is The Third Text" />
                    <Image Source="mypix.png" />
                </StackPanel>
            </ToolTipService.ToolTip>
        </Button>
    </Canvas>
</UserControl>
The following video clip explains this code sample.

Posted by life | with no comments

Simple Style Definition in Silverlight

Instead of specifying separately for each and every element how exactly it should look we can define a style and then apply it on various elements. Using styles promotes code reuse, makes our code shorter and assists with the code maintenance in the long run. Defining a style is about defining a collection of property values we can then apply to any element we select. Using styles is very similar to using CSS. In both cases we reuse a style definition.

The style is a resource. We define it as any other resource. Each style includes a collection of Setter elements .Each Setter element sets a specific property. The property must be a dependency one.

Unlike WPF we cannot apply the same style on different types of elements and we cannot use triggers in order to change the style of a given control when a specific property changes its value.

The following code sample includes the definition of a simple style that targets buttons.

<UserControl x:Class="SilverlightApplication30.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <Style x:Key="CuteButton" TargetType="Button">
            <Setter Property="FontFamily" Value="Arial" />
            <Setter Property="FontSize" Value="18" />
            <Setter Property="Foreground" Value="Blue" />
            <Setter Property="Padding" Value="10" />
        </Style>
    </UserControl.Resources>
    <Canvas x:Name="LayoutRoot" Background="White">
        <Button Name="MyBt" Content="Click Here" Style="{StaticResource CuteButton}" />        
    </Canvas>
</UserControl>
The following video clip overviews this code sample and explains it.

Posted by life | with no comments
תגים:,

The Component Art Dashboard Server

The Component Art dashboard server allows you to develop in Silverlight, place the XAML file on server and allows it to automatically convert it to HTML5 delivered directly to any mobile platform. The rich UI components developed by Component Art allow you to extend your hybrid application into the next level.

Whether you develop for iPhone, WP7 or Android you might want to take advantage of this new capability and extend your hybrid application with attractive rich user interface.

Simple Template Definition in Silverlight

Templates allow us to apply a set of design rules on the controls we have on our page. They change the visual face of every common control. Unlike styles, when using a template we are not limited for those properties that were defined in the Element class. Templates are limited for those elements that extend the Control class. We cannot use them on others. Every control has a built-in recipe that determines how it should be rendered. This recipe is known as the control template. The template is defined using XAML and is applied using the Template property.

<UserControl x:Class="SilverlightApplication28.MainPage"
    xmlns="http://schemas.microsoft.com/client/2007" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <UserControl.Resources>
        <Color x:Key="MyBackgroundColor">#CCCCCCCC</Color>
        <ControlTemplate x:Key="MyButtonTemplate" TargetType="Button">
            <Border BorderBrush="Red" BorderThickness="4" 
                    CornerRadius="12" Background="{TemplateBinding Background}">
                <ContentPresenter>
                </ContentPresenter>
            </Border>
        </ControlTemplate>
        <Style x:Key="MyButtonStyle" TargetType="Button">
            <Setter Property="Foreground" 
                    Value="Blue"></Setter>
            <Setter Property="Background" 
                    Value="{StaticResource MyBackgroundColor}"></Setter>
            <Setter Property="Template" 
                    Value="{StaticResource MyButtonTemplate}"></Setter>
        </Style>
    </UserControl.Resources>
    <StackPanel x:Name="ApplicationLayout" Background="LightYellow" >
        <Button Style="{StaticResource MyButtonStyle}" 
                Content="Simple Templated Button" 
                Margin="10" Padding="20" FontSize="22">            
        </Button>
    </StackPanel>
</UserControl>
The following video clip goes over this code sample, explains it and shows its output.

Posted by life | with no comments

Silverlight Pages Navigation Security Issue

When the Silverlight application uses pages the URL address is appended with the name of the page resource the user see. This has a security implication as it might allow a malicious user to access pages he is not allows to. The following video clip shows that.

Posted by life | with no comments

Frames & Pages in Silverlight

The Frame is a content control. It contains a single child element and it inherits from ContentControl. The single child it displays can be of the type Page. We can easily use this capability for developing an application that includes pages displayed one at a time within a frame. The following code sample shows how simple it is to do it. This is the MainPage.xaml file. It displays a Frame element together with few buttons the user can use in order to navigate to another page.
<UserControl x:Class="SilverlightApplication23.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="500"
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="MainContainer" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition MaxHeight="100"></RowDefinition>
        </Grid.RowDefinitions>
        <sdk:Frame Height="179" Grid.Row="0" HorizontalAlignment="Left"
                   Margin="43,30,0,0" Name="MainFrame" VerticalAlignment="Top" Width="315" />
        <Grid Grid.Row="1" x:Name="LayoutButtons" Background="Yellow">
            <Grid.ColumnDefinitions>
                <ColumnDefinition ></ColumnDefinition>
                <ColumnDefinition ></ColumnDefinition>
                <ColumnDefinition ></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Button FontSize="22" Grid.Column="0" Content="First"
                    MaxWidth="100" MaxHeight="50" Click="ButtonClick"></Button>
            <Button FontSize="22" Grid.Column="1" Content="Second"
                    MaxWidth="100" MaxHeight="50" Click="ButtonClick1"></Button>
            <Button FontSize="22" Grid.Column="3" Content="Third"
                    MaxWidth="100" MaxHeight="50" Click="ButtonClick2"></Button>
        </Grid>
    </Grid>
</UserControl>
This is the MainPage.xaml.cs file. It includes the code behind of the main page. This is the code responsible for switching between the pages.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication23
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            MainFrame.Navigate(new Uri("/First.xaml", UriKind.Relative));
        }

        private void ButtonClick1(object sender, RoutedEventArgs e)
        {
            MainFrame.Navigate(new Uri("/Second.xaml", UriKind.Relative));
        }

        private void ButtonClick2(object sender, RoutedEventArgs e)
        {
            MainFrame.Navigate(new Uri("/Third.xaml", UriKind.Relative));
        }
    }
}
This is the First.xaml file. It includes the definition for the user interface the first page displays.
<navigation:Page x:Class="SilverlightApplication23.Page1"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           mc:Ignorable="d"
           xmlns:navigation=
           "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           d:DesignWidth="640" d:DesignHeight="480"
           Title="Page1 Page"
           xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
    <Grid x:Name="LayoutRoot">
        <sdk:Label Height="41" HorizontalAlignment="Left" Margin="31,43,0,0" Name="label1"
        VerticalAlignment="Top" Width="225" Content="This is First Page!" FontSize="24" />
    </Grid>
</navigation:Page>
This is the Second.xaml file. It includes the definition for the user interface the second page displays.
<navigation:Page x:Class="SilverlightApplication23.Second"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           mc:Ignorable="d"
           xmlns:navigation=
           "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           d:DesignWidth="640" d:DesignHeight="480" Title="Second Page"
           xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
    <Grid x:Name="LayoutRoot">
        <sdk:Label Height="47" HorizontalAlignment="Left" Margin="101,67,0,0"
           Name="label1" VerticalAlignment="Top" Width="342" FontSize="24"
           Content="This is The Second Page!" Background="#15000000" />
    </Grid>
</navigation:Page>
This is the Third.xaml file. It includes the definition for the user interface the third page displays.
<navigation:Page x:Class="SilverlightApplication23.Third"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           mc:Ignorable="d"
           xmlns:navigation=
           "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           d:DesignWidth="640" d:DesignHeight="480" Title="Third Page"
           xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
    <Grid x:Name="LayoutRoot">
        <sdk:Label Height="64" HorizontalAlignment="Left"
                   Margin="55,49,0,0" Name="label1" VerticalAlignment="Top"
                   Width="454" Content="Third Page!" Background="#4BF2D11F" FontSize="25" />
    </Grid>
</navigation:Page>
The following video clip shows and explains this code sample.

Posted by life | with no comments

Silverlight Resources & XML

The Silverlight application is actually a package of files archived using ZIP and stored as a single file with the .xap extension. This file can include resources we want to be available for our application. We can alternatively keep these resources on the server or have them as part of the DLL file, which is the default behavior.

The following code sample includes an XML resource file packed as part of the DLL file. This code sample shows how simple it is to access that XML resource and how simple it is to parser its data using Linq to XML.

The following is the XML file (lib.xml). We save it within the root directory of our Silverlight application.

<?xml version="1.0" encoding="utf-8" ?>
<library>
  <book>
    <title>Core Silverlight</title>
    <author>Jonathan Taylor</author>
    <isbn>12312321231</isbn>
  </book>
  <book>
    <title>Core Python</title>
    <author>Greg Johnston</author>
    <isbn>42434234343</isbn>
  </book>
  <book>
    <title>F# Professional</title>
    <author>Nathan Shultz</author>
    <isbn>78723234233</isbn>
  </book>
</library>
The following is the XAML file that defines the user interface (MainPage.xaml).
<UserControl x:Class="SilverlightApplication21.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="800">

    <Grid x:Name="LayoutRoot" Background="White">
        <Button Content="Press Here" Height="23"
                HorizontalAlignment="Left" Margin="53,39,0,0"
                Name="PressHereButton" VerticalAlignment="Top"
                Width="75" Click="PressHereButtonClick" />
        <TextBox Height="36" HorizontalAlignment="Left"
                 Margin="54,86,0,0" Name="DataTextBox"
                 VerticalAlignment="Top" Width="691" />
    </Grid>
</UserControl>
The following is the code behind of the XAML file (MainPage.xaml.cs).
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace SilverlightApplication21
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private void PressHereButtonClick(object sender, RoutedEventArgs e)
        {
            var sri = Application.GetResourceStream(
                new Uri("lib.xml", UriKind.Relative));
            var stream = new StreamReader(sri.Stream);
            var str = stream.ReadToEnd();
            var ob = XDocument.Parse(str);
            var books = from x in ob.Descendants("book")
                        select new
                        {
                            Title = x.Descendants("title").First().Value,
                            Author = x.Descendants("author").First().Value,
                            Isbn = x.Descendants("isbn").First().Value
                        };
            foreach (var book in books)
            {
                DataTextBox.Text += book.Title + "\\" + book.Author + "   ";
            }
        }
    }
}
The following video clip explains this code sample and shows how does it run.

Posted by life | with no comments

C# WebClient Getting Http Headers

This video clip shows how we can get the HTTP headers associated with the HTTP response we get when trying to browse a specific URL address using the WebClient object.

More video clips can be found at www.abelski.com and at www.CSharpBook.co.il.

Posted by life | 1 comment(s)
תגים:, ,

Introduction to Silverlight

I have just completed to develop the first topic of the Silverlight Basics course I am working on these days. You can find its community version available for free personal usage at www.abelski.org. The professional version is available at www.abelski.com. The following video clips were prepared as part of this topic.

Posted by life | with no comments
תגים:

The Log4PHP Logging Framework

Log4PHP is an open source project that provides a versatile logging framework for PHP. Log4PHP is part of the Apache Logging Services project and it works similarly to other Apache Logging Services sub projects, such as Log4J and Log4Net.

I have just completed to develop the first two topics in my Log4PHP course. You can find its community version available for free personal usage at www.abelski.org. The professional version is available at www.abelski.com. The slides of the first two topics the community version includes are available for free personal usage at the following two URL addresses: http://www.abelski.com/courses/log4php/introduction.pdf http://www.abelski.com/courses/log4php/basics.pdf

The following video clip shows how to download the Log4PHP. Once you download you just need to make the files available for your project.

The following video clip explains a simple code sample for using the Log4PHP framework. This code sample include two files.

The PHP source code that uses the Log4PHP open source framework.

<?php
include('log4php/Logger.php');

Logger::configure('loggingconfiguration.xml');

class Something
{
    private $log;

    public function __construct()
    {
        $this->log = Logger::getLogger(__CLASS__);
    }

    public function run()
    {
        $this->log->info("simple informative message");
        $i=1;
        $sum=0;
        while($i<=10)
        {
        	$sum += $i;
        	$this->log->info("i=".$i);
        	$i++;
        }
    }
}

$ob = new Something();
$ob->run();
?>
The XML file that includes the configuration setting for Log4PHP.
<?xml version="1.0" encoding="UTF-8"?>
<log4php:configuration xmlns:log4php="http://logging.apache.org/log4php/">
    <appender name="fileappender" class="LoggerAppenderFile">
        <layout class="LoggerLayoutTTCC" />
        <param name="file" value="project_logs.log" />
    </appender>
    <logger name="Something">
        <appender_ref ref="fileappender" />
    </logger>
</log4php:configuration>

Posted by life | with no comments
תגים:,

Working with Directories in Python

I have just completed to update the directories topic in my Python Fundamentals course. You can find its community version available for free personal usage at www.abelski.org. The slides are available for free download. The professional version is available at www.abelski.com. You can find below the new video clips I have just completed to create in order to assist learning this topic.

Posted by life | with no comments
More Posts Next page »