Search This Blog

Wednesday, July 27, 2011

Subtitles out of sync Samsung PS51D6900; Subtitles out of sync in Samsung’s plasma TV 50’’

Subtitles in Samsung plasma does not always work as we would like them to. I had several movies which had problems with subtitles. It turned out that it was a problem with frame rate (of 25 frames/s in my case) which Samsung’s plasmas interpret in a wrong way. The symptoms were as follows: subtitles worked correctly in Media Player Classic Home Cinema (link) but failed to work on the TV.

The problem was that these subtitles were FRAME-based. It means that the format was like this:

{3955}{4015}Do roboty!
{4021}{4112}Potrafisz byµ dupkiem, jeśli chcesz.
{4165}{4230}Głupia dziwka.
{4300}{4354}Zamknijcie lokal, gdy skończycie.

That is: {Beginning_frame}{Ending_frame}

If you want the subtitles to work in both: MPC-HC & Samsung plasma you need to convert them to srt format which looks like this:

11
00:00:53,520 --> 00:00:55,760
Czyli dobrze usłyszałem.
Powtarzasz to co roku.

12
00:00:55,920 --> 00:00:57,720
Tak, ale tym razem mówię poważnie.

13
00:00:57,880 --> 00:00:59,320
W końcu żyje się tylko raz.

14
00:00:59,480 --> 00:01:00,440
Pewnie.

 

Generally ANY format which is TIME-based should work. A nice program for converting subtitles to time-based formats is here. You can download a version here as well.

Tuesday, July 26, 2011

Visual Studio 2010 reference other project from the same Solution

- Add a reference to that Project int the Project you're trying to access foreign classes from
  (Add reference-Projects-Foreign_Project)
- Make sure when compiling (debug), your solution platform is set to "Any CPU"
- Make sure they both are referencing the same .Net 4 Profile, one may be using the client profile

Monday, July 25, 2011

Joomla - Re: JAuthentication::__construct: Could not load authentication libraries

I disabled the plugin - Authentication – Joomla as I thought it was for user logging in the page, not the admin login. It was a big mistake though. To turn this feature on you need to log to Joomla’s database and change published to 1 in the jos_plugins table  in row.Name = Authentication – Joomla (it was row.id = 1 in my case).

UPDATE `your_database_name`.`jos_plugins` SET `published` = '1' WHERE `jos_plugins`.`id` =1;

Friday, July 22, 2011

Autofac - reading other container's Metadata

public class Person
    {
        public string name;
        public int age;

        public Person(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        public Person() { }
    }

    public class Other
    {
        readonly IEnumerable<Meta<Person>> _personsMeta;

        public Other(IEnumerable<Meta<Person>> personsMeta)
        {
            _personsMeta = personsMeta;
        }

        public void Write()
        {
            IEnumerable appender = _personsMeta;
            IEnumerator enumer = appender.GetEnumerator();
           
            enumer.MoveNext();
            Meta<Person> person = (Meta<Person>)enumer.Current;
            Dictionary<string,object> metaDict = (Dictionary<string,object>)person.Metadata;

            var info = metaDict.First(a => a.Key.Equals("descr")).Value;
            var info2 = metaDict.Where(a => a.Key.Equals("descr")).Select(a => a.Value).First();
            var info3 = (from entry in metaDict where entry.Key == "descr" select entry.Value).First();

            Console.WriteLine("Person container metadata: \n\"" + info3 + "\"");
        }
    }

    //Autofac - reading other container's Metadata
    class Program
    {
        static void Main()
        {  
            var builder = new ContainerBuilder();
            builder.RegisterType<Person>().WithMetadata("descr", "Describes basic properties of the client, like name or age");
            builder.Register<Other>(c => new Other(c.Resolve<IEnumerable<Meta<Person>>>() ));

            var container = builder.Build();
            using (var lifetime = container.BeginLifetimeScope())
            {
                var otherObj = container.Resolve<Other>();
                otherObj.Write();
            }

            Console.WriteLine("Done! Press any key.");
            Console.ReadKey();
        }
    }

Autofac - passing parameters to Resolve() without and with singletons

public class Person
    {
        public string name;
        public int age;

        public Person(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        public Person() { }
    }

    //Autofac - passing parameters to Resolve() without and with singletons
    class Program
    {
        static void Main()
        {  
            var builder = new ContainerBuilder();
            builder.RegisterType<Person>();
            var container = builder.Build();
            using (var lifetime = container.BeginLifetimeScope())
            {
                var jane = container.Resolve<Person>(new NamedParameter("name", "Jane"), new NamedParameter("age", 15));
                var kate = container.Resolve<Person>(new NamedParameter("name", "Kathie"), new NamedParameter("age", 15));
                var xxx = container.Resolve<Person>();
                if (jane.Equals(kate))
                {
                    Console.WriteLine("The same");
                }
                else
                {
                    Console.WriteLine("Different");
                }
            }

            builder = new ContainerBuilder();
            builder.RegisterType<Person>().SingleInstance();
            container = builder.Build();
            using (var lifetime = container.BeginLifetimeScope())
            {
                var jane = container.Resolve<Person>(new NamedParameter("name", "Jane"), new NamedParameter("age", 15));
                var kate = container.Resolve<Person>(new NamedParameter("name", "Kathie"), new NamedParameter("age", 15));
                var xxx = container.Resolve<Person>();
                if (jane.Equals(kate))
                {
                    Console.WriteLine("The same");
                }
                else
                {
                    Console.WriteLine("Different");
                }
            }

            Console.WriteLine("Done! Press any key.");
            Console.ReadKey();
        }

Autofac create different classes (components) based on a parameter value

public interface A
   {
       void p();
   }

   public class B : A
   {
       public void p()
       { }
   }

   public class C : A
   {
       public void p()
       { }
   }

   //create different classes (components) based on a parameter value
   class Program
   {
       //Selection of an Implementer based on a Parameter Value
       static void Main()
       {  
           var builder = new ContainerBuilder();
           //c - container, p - parameters
           builder.Register<A>((c, p) =>
           {
               //we cannot cast directly to int as parameter string has to be parsed in order to get int
               string accountIdStr = p.Named<string>("id");
               int accountId = int.Parse(accountIdStr);
               if (accountId > 900 )
                   return new C();
               else
                   return new B();
           });

           var container = builder.Build();
           var obj = container.Resolve<A>(new NamedParameter("id", "12345"));

           Console.WriteLine("Obj resolved: " + obj.GetType().ToString());
           Console.WriteLine("Done! Press any key.");
           Console.ReadKey();
       }
   }

Thursday, July 21, 2011

Autofac listing components from a container taken from an assembly (Dll)

public interface A
{
    void p();
}

public class B : A
{
    public void p()
    { }
}

public class C : A
{
    public void p()
    { }
}

class Program
{
    static void Main()
    {
        var builder = new ContainerBuilder();
        var executingAssembly = Assembly.GetExecutingAssembly();
        var registrationBuilder = builder.RegisterAssemblyTypes(executingAssembly)
                            .Where(t => t.Name.Equals("C") || t.Name.Equals("B"))
                            .AsImplementedInterfaces().AsSelf();
        var container = builder.Build();
        var contList = container.Resolve<IEnumerable<A>>();

        Console.WriteLine("Done! Press any key.");
        Console.ReadKey();
    }
}

Autofac register class with different constructors; Autofac registering and constructor priority

This examples exaplains the basic operation of constructor priority in Autofac which is a dependency injection framework simmilar to spring.

 

class MemoChecker{
    public MemoChecker(IList<Memo> memos, IMemoDueNotifier notifier){}

    public MemoChecker(IList<Memo> memos, IMemoDueNotifier notifier, string unnecessaryParam){}
}


var builder = new ContainerBuilder();
builder.Register(c => new MemoChecker(c.Resolve<IList<Memo>>(), c.Resolve<IMemoDueNotifier>(), "aa")).InstancePerLifetimeScope();
builder.Register(c => new MemoChecker(c.Resolve<IList<Memo>>(), c.Resolve<IMemoDueNotifier>())).InstancePerLifetimeScope();
using (var cd = _container.BeginLifetimeScope())
{
    cd.Resolve<MemoChecker>().identifyItslef();
}

Now:
this - MemoChecker(IList<Memo> memos, IMemoDueNotifier notifier) constructor will be called


builder.Register(c => new MemoChecker(c.Resolve<IList<Memo>>(), c.Resolve<IMemoDueNotifier>(), "aa")).InstancePerLifetimeScope();
builder.Register(c => new MemoChecker(c.Resolve<IList<Memo>>(), c.Resolve<IMemoDueNotifier>())).InstancePerLifetimeScope();
builder.Register(c => new MemoChecker(c.Resolve<IList<Memo>>(), c.Resolve<IMemoDueNotifier>(), "aa")).InstancePerLifetimeScope();

Now:
this - MemoChecker(IList<Memo> memos, IMemoDueNotifier notifier, string unnecessaryParam) constructor will be called


===================================================

New constructors:
public MemoChecker(IList<Memo> memos, IMemoDueNotifier notifier){}
public MemoChecker(IList<Memo> memos, IMemoDueNotifier notifier, string unnecessaryParam){}


var builder = new ContainerBuilder();
builder.RegisterType<MemoChecker>().InstancePerLifetimeScope();
builder.RegisterType<PrintingNotifier>().As<IMemoDueNotifier>();
builder.RegisterInstance(memos).As<IList<Memo>>();
builder.RegisterInstance(Console.Out).As<TextWriter>().ExternallyOwned();
using (var cd = _container.BeginLifetimeScope())
{
    cd.Resolve<MemoChecker>().identifyItslef();
}

Now:
this - MemoChecker(IList<Memo> memos, IMemoDueNotifier notifier) constructor will be called

===================================================

New constructors:
public MemoChecker(IList<Memo> memos, IMemoDueNotifier notifier){}
public MemoChecker(IList<Memo> memos, IMemoDueNotifier notifier, TextWriter unnecessaryParam){}


var builder = new ContainerBuilder();
builder.RegisterType<MemoChecker>().InstancePerLifetimeScope();
builder.RegisterType<PrintingNotifier>().As<IMemoDueNotifier>();
builder.RegisterInstance(memos).As<IList<Memo>>();
builder.RegisterInstance(Console.Out).As<TextWriter>().ExternallyOwned();
using (var cd = _container.BeginLifetimeScope())
{
    cd.Resolve<MemoChecker>().identifyItslef();
}

Now:
this - MemoChecker(IList<Memo> memos, IMemoDueNotifier notifier, TextWriter unnecessaryParam) constructor will be called

Wednesday, July 20, 2011

archlinux installing openvpn-als

pacman –S extra/openjdk6 extra/apache-ant extra/junit

download openvpn-als from:
http://sourceforge.net/projects/openvpn-als/

extract it to: /opt/openvpn-als
copy tools.jar to /opt/openvpn-als/adito/lib/tools.jar and to /opt/openvpn-als/lib/tools.jar


cd /opt/openvpn-als && ant install

[installing....]
wait for web browser address:
127.0.0.1:28080

good guide on installing adito is here:
http://jaredheinrichs.com/how-to-install-openvpn-als-on-ubuntu-linux-ssl-vpn.html

pacman for dummies Archlinux

pacman –Q      > searches your pc
pacman –Ss     > searches the repos
pacman –S pac_name pac_name2      > installs package
pacman –R pac_name   >remove package
pacman –S pac_name    >upgrade single package
pacman –Syu    >upgrade all packages
pacman –Sy      >refresh package list

Simple LINQ usage in C#

class Program
    {
        //define a list of strings
        private static List<string> people = new List<string>()
            {
              "Granville", "John", "Rachel", "Betty",
              "Chandler", "Ross", "Monica"
            };

        class Person
        {
            public string Name;
            public int height;
        }

        //define a list of Person objects
        private static List<Person> people2 = new List<Person>()
        {
            new Person{Name = "Granville", height = 165},
            new Person{Name = "John", height = 185},
                new Person{Name = "Rachel", height = 179},
                    new Person{Name = "Betty", height = 125},
            new Person{Name = "Chandler", height = 132},
            new Person{Name = "Ross", height = 153},
            new Person{Name = "Monica" , height = 198}
        };


        //list items in people = List<Person> which height's is greater than 100
        public static void Example4()
        {
            IEnumerable<Person> query = from p in people2 where p.height > 180 select p;

            foreach (Person person in query)
            {
                Console.WriteLine(person.Name + " " + person.height);
            }
        }

        //list items in people = List<Person> which height's is greater than 100 and order by this Name ascending
        //using lambda expression
        public static void Example5()
        {
            IEnumerable<Person> query = people2.Where(x => x.height > 180).OrderBy(x => x.Name);

            foreach (Person person in query)
            {
                Console.WriteLine(person.Name + " " + person.height);
            }
        }

        //count items in people = List<string>
        public static void Example1()
        {
            int queryCount = (from p in people select p).Count();
            Console.WriteLine(queryCount);
        }

        //list items in people = List<string> which string's length is greater than 5
        public static void Example2()
        {
            IEnumerable<string> query = from p in people
                                        where p.Length > 5
                                        orderby p
                                        select p;

            foreach (string person in query)
            {
                Console.WriteLine(person);
            }
        }

        //list items in people = List<string> which string's length is greater than 5 and order by this string ascending
        //using lambda expressions
        public static void Example3()
        {
            IEnumerable<string> query =  people.Where(x => x.Length > 5).OrderBy(x => x);

            foreach (string person in query)
            {
                Console.WriteLine(person);
            }
        }

       

        static void Main(string[] args)
        {
            //Example1();
            //Example2();
            //Example3();
            //Example4();
            Example5();

            Console.ReadLine();
        }
    }

Simple command in MVVM model, Silverlight, C#

MVVM model:

  • Model - behaviour and data management
  • View - renders model into UI
  • ViewModel - "model of the view"; data binding between view and model;

This example shows how to create a button with an event "Save" bound to it in MVVM model.

In application's shell (MainPage.xaml) we define UpperPanelView resource and insert the body of UpperPanelView.

MainPage.xaml:

<UserControl x:Class="SilverlightMVVM.MainPage"
    ....
    xmlns:basicviews="clr-namespace:SilverlightMVVM.Views">
    <UserControl.Resources>
        <basicviews:UpperPanelView x:Key="UpperPanelView"/>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <basicviews:UpperPanelView Grid.Row="1" DataContext="{Binding Source={StaticResource UpperPanelView}}"/>
    </Grid>
</UserControl>

UpperPanelView has a button with a command Save bound to UpperPanelView.Save property.

UpperPanelView.xaml:

<UserControl x:Class="SilverlightMVVM.Views.UpperPanelView"
    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="150" d:DesignWidth="402" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="LayoutRoot" Background="White">
        <sdk:Label Height="28" HorizontalAlignment="Center" Margin="42,12,54,0" Name="label1" VerticalAlignment="Top" Width="306" Content="Upper panel" FontSize="20" FontWeight="Bold" />
        <Button Content="Save" Height="23" HorizontalAlignment="Center" Margin="159,59,169,0" Name="saveButton" VerticalAlignment="Top" Width="75"
                Command="{Binding Save}" CommandParameter="{Binding ElementName=listImages, Path=SelectedItem}"/>
    </Grid>
</UserControl>

UpperPanelView.xaml.cs hold the Save property of type SaveCommand. We have bound button click property to this event earlier.

UpperPanelView.xaml.cs:

public partial class UpperPanelView : UserControl
{
    public UpperPanelView()
    {
        InitializeComponent();
    }


    //Commands
    private SaveCommand _saveCommand;
    public SaveCommand Save
    {
        get
        {
            if (_saveCommand == null)
                _saveCommand = new SaveCommand(this);
            return _saveCommand;
        }
    }
}


SaveCommand implements ICommand interface and so has the implementation of the Save command.


SaveCommand.cs:

public class SaveCommand : ICommand
    {
        private UpperPanelView _viewModel;

        public SaveCommand(UpperPanelView viewModel)
        {
            _viewModel = viewModel;
        }


        public bool CanExecute(object parameter)
        {
            //return (_viewModel.SelectedCapture != null) ? true : false;
            return true;
        }

        public void Execute(object parameter)
        {
            MessageBox.Show("Ala ma kota");
        }

        public event EventHandler CanExecuteChanged;

        protected virtual void OnCanExecuteChanged(EventArgs e)
        {
            var canExecuteChanged = CanExecuteChanged;

            if (canExecuteChanged != null)
                canExecuteChanged(this, e);
        }
    }

============================================

Another example:

MessageBrowserView.xaml
------------------------
<Button Content="A" Command="{Binding MenuItemClickCommand}"></Button>

MessageBrowserView.xaml.cs
----------------------------
public MessageBrowserView(MessageBrowserViewModel viewModel)
{
  DataContext = viewModel;
  InitializeComponent();
}

MessageBrowserViewModel.cs
---------------------------

public MessageBrowserViewModel()
{
MenuItemClickCommand = new ActionCommand(MenuItemClick);
}

/// <summary>
/// Komenda odpowiadająca na kliknięcie w Menu
/// </summary>
public ICommand MenuItemClickCommand { get; private set; }

private void MenuItemClick()
{
     MessageBox.Show("AAAA");
}

Monday, July 18, 2011

PRISM 'VS100COMNTOOLS' not set Cannot set the build environment; Visual Studio Web Developer 2010 Express

This means that PRISM cannot find your Visual Studio installation folder. Add this line in RegisterPrismBinaries.bat:

SET VS100COMNTOOLS=c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\

(or whatever folder you have vsvars32.bat in).

The beginning of the file should look like this:

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

@ECHO OFF

SET ScriptsDir=%~dp0\Scripts
SET BinDir=.\Bin
SET Pause=true
SET Register=true
SET VS100COMNTOOLS=c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\

IF "%1"=="/?" GOTO HELP

IF DEFINED DevEnvDir GOTO OPTIONS

IF NOT DEFINED VS100COMNTOOLS GOTO VSNOTFOUND
---------------------------------------------------------------

After running RegisterPrismBinaries.bat you should see:

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


------------------------------------------
Setting the build environment
------------------------------------------


------------------------------------------
Registration initiated
------------------------------------------

Microsoft (R) Build Engine Version 4.0.30319.1
[Microsoft .NET Framework, Version 4.0.30319.235]
Copyright (C) Microsoft Corporation 2007. All rights reserved.

Build started 2011-07-18 16:34:36.
Project "C:\PRISM4\Scripts\RegisterPrismLibrary.proj" on node 1 (default target
s).
RegisterLibrary:
  regedit.exe /s "C:\Users\kosiara\AppData\Local\Temp\tmp35B9.tmp"
  Deleting file "C:\Users\kosiara\AppData\Local\Temp\tmp35B9.tmp".
Done Building Project "C:\PRISM4\Scripts\RegisterPrismLibrary.proj" (default ta
rgets).


Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:00.31

------------------------------------------
Registration completed
------------------------------------------

NET USE clear connections; Microsoft Windows NET USE delete connections;

Use:

NET USE * /DELETE

WPF toolkit datagrid usage; WPF datagrid column size;

The datagrid for old WPF (from Visual Studio 2008) is available as an addon from WPF toolkit project. WPF toolkit is available here. Source code for this example is available here. In this example one creates a class holding data in the grid (GridRow). Instances of this class are held in an ObservableCollection. It has to be ObservableCollection because only then changes in the collection will be reflected in the grid. You could use a simple List but the Grid will not update new information then.

Later on you set the grid’s ItemsSource as the ObservableCollection created earlier on.

 

        In XAML file:
       
    <dg:DataGrid AutoGenerateColumns="True"  Height="433" Name="dataGrid1" Width="809" Canvas.Left="4.999" Canvas.Top="55"  Margin="5" SelectionChanged="dataGrid1_SelectionChanged" AutoGeneratedColumns="dataGrid1_AutoGeneratedColumns">
        </dg:DataGrid>
       
       
        In cs file:
       
        public class GridRow
        {
            public string Nr { get; set; }

            public string Lp { get; set; }

            public string Name { get; set; }

        }
       
        public static ObservableCollection<GridRow> GetSampleCustomerList()
        {
            ObservableCollection<GridRow> aaaa = new ObservableCollection<GridRow>();
            GridRow gr = new GridRow();
            gr.Nr = "10345";
            gr.Lp = "1";
            gr.Name = "Janina";
            aaaa.Add(gr);
        }
       
        private void constructDataGrid()
        {
            dataGrid1.ItemsSource = GetSampleCustomerList();
        }
       
        private void dataGrid1_AutoGeneratedColumns(object sender, EventArgs e)
        {
            dataGrid1.Columns[0].Width = 55; //Nr
            dataGrid1.Columns[1].Width = 46; //Lp
            dataGrid1.Columns[2].Width = 140; //Name
        }
       

Flex Pie chart; Flex how to use Pie charts; Flex sample testcase counting pie chart;

This example shows how to create a Pie chart that counts test cases (it can be anything else, of course). Source code is available here.

Pie chart is bound to an ArrayCollection (don’t forget to insert [Bindable] property – without it the Pie chart won’t work of course). The showDataTips="true" property displays nice percentage information in Flash when you hover your mouse over it. resultHandlerStatCorrectTCs and resultHandlerStatFailedTCs are async functions that gather data for the Pie chart.

 


<mx:PieChart x="50" y="90" id="piechart1" dataProvider="{tcPercResults}" showDataTips="true" width="300" height="300">
    <mx:series>
        <mx:PieSeries displayName="TestCases" field="Amount" nameField="Expense" explodeRadius=".12"/>
    </mx:series>
</mx:PieChart>
<mx:Legend dataProvider="{piechart1}" x="0" y="90"/>

 

//Statistics
[Bindable]
public var tcPercResults:ArrayCollection = new ArrayCollection([
    {Expense:"Failed", Amount:2000},
    {Expense:"Success", Amount:1000},
]);
   
   
   
protected function statCanvas_creationCompleteHandler(event:FlexEvent):void
{
    //get correct TCs
    var resultObjCorrectTCs:AsyncToken;
    var responderCorrectTCs:AsyncResponder = new AsyncResponder( resultHandlerStatCorrectTCs, faultHandlerForAsyncCall );
    resultObjCorrectTCs = testService.getCorrectTCCount();
    resultObjCorrectTCs.addResponder( responderCorrectTCs );
   
   
    //get failed TCs
    var resultObjFailedTCs:AsyncToken;
    var responderFailedTCs:AsyncResponder = new AsyncResponder( resultHandlerStatFailedTCs, faultHandlerForAsyncCall );
    resultObjFailedTCs = testService.getFailedTCCount();
    resultObjFailedTCs.addResponder( responderFailedTCs );
   
}
   
   
   
    public function resultHandlerStatCorrectTCs( event:ResultEvent, token:Object=null ):void
{
    //Alert.show( "RESULT: "+ event.result as String );
    //var rpcRes:int = event.result as int;
    var rpcRes:int = int(event.result);
    this.statCorrectTCs = rpcRes;
   
    //set Correct TC on a graph
    var resultCorr:Object = tcPercResults.getItemAt(1);
    resultCorr["Amount"] = this.statCorrectTCs;
    tcPercResults.setItemAt(resultCorr,1);
}

public function resultHandlerStatFailedTCs( event:ResultEvent, token:Object=null ):void
{
    //Alert.show( "RESULT: "+ event.result as String );
    //var rpcRes:int = event.result as int;
    var rpcRes:int = int(event.result);
    this.statFailedTCs = rpcRes;
   
    //set Failed TC on a graph
    var result:Object = tcPercResults.getItemAt(0);
    result["Amount"] = this.statFailedTCs;
    tcPercResults.setItemAt(result,0);
}

Wednesday, July 13, 2011

WPF clone tabItem; WPF create TabItems dynamically; WPF cannot edit TabItems controls; WPF cannot access TabItems controls;

It is impossible to clone TabItems from an existing one without using XamlReader and XamlWriter. You can, however, define a template for creating new TabItems. The template has to be created in your xaml file in Window resources.

<Window.Resources>
  <DataTemplate x:Key="tabItemContent">
            <Canvas Margin="0,0,0,0" Name="tabPracownikCanvas" Visibility="Visible">
                <ListBox Canvas.Left="0" Canvas.Top="-0.004" Height="229.977" Name="listBox1" Width="152.207">
                    <ListBoxItem>Dane osobowe</ListBoxItem>
                    </ListBox>
                <RichTextBox  Canvas.Left="0" Canvas.Top="261.085" Height="246.642" Name="richTextBoxBasicInfo" Width="152.207" IsReadOnly="True"/>
                <Label Canvas.Left="0" Canvas.Top="233.31" Height="27.775" Name="label1" Width="152.207" Content="SomeTextHere">
                </Label>
                <Canvas Canvas.Left="155.54" Canvas.Top="-0.018" Height="507.745" Name="canvasWithDetailedInfo" Width="430.731" >
                </Canvas>
            </Canvas>
        </DataTemplate>
</Window.Resources>

To add new tabItem just do the following:

TabItem item = new TabItem();
item.Header = "New item";
item.ContentTemplate = TryFindResource("tabItemContent") as DataTemplate;
tabControl2.Items.Add(item);

YOU CANNOT change the contents which were created dynamically just through children editing. You need to bind some properties.

e.g. we will bind label contents:

create a class:

        class Person
        {
            public string Name { get; set; }

            public string Surname { get; set; }
        }

change the label content to binding:

<Label Canvas.Left="0" Canvas.Top="233.31" Height="27.775" Name="label1" Width="152.207" Content="{Binding Name}">

change the Item’s content:

item.Content = new Person() { Name = "dupa", Surname = "xxxx" }

It will automatically change the label’s content when you change item.Content.Name property.

 

Tuesday, July 5, 2011

Flex ctrl+r key press; Flex ctrl+f key press; Flex ctrl+F key press

 

To intercept the above key presses you need to register an event handler (possibly in an init function or any onCreation event) like this:

stage.addEventListener(KeyboardEvent.KEY_DOWN, mainWindow_keyDownHandler);

The function looks as follows:

protected function mainWindow_keyDownHandler(event:KeyboardEvent):void
        {
            if (event.ctrlKey && event.charCode == 114)
//ctrl+r
            {

                button2_clickHandler(null); //refresh
            }
           
            if (event.ctrlKey && event.charCode == 102) { //ctrl+f
                button3_clickHandler(null); //custom filter
            }
           
            if (event.ctrlKey && event.shiftKey && event.charCode == 70) { //ctrl+F
                button1_clickHandler(null); //full screen
            }
        }