Search This Blog

Friday, December 23, 2011

Silverlight passing event arguments in InvokeCommandAction; invoke a command when ENTER is pressed in a TextBox; Silverlight MVVM calling method from ViewModel with parameters

We need to trigger a command in ViewModel from View and pass arguments in response to an event. There are a couple of ways to accomplish that.

1. Just call a method from ViewModel:

<TextBox>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="KeyDown">
            <ei:CallMethodAction TargetObject="{Binding}" MethodName="QuickSearchKeyDown"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
<TextBox>


2. Call a Command from ViewModel with parameters:
<TextBox Name="textBox">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="KeyDown">
            <i:InvokeCommandAction  
                    Command="{Binding SomeCommand}"  
                    CommandParameter="{Binding Text, ElementName=textBox}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <i:Interaction.Behaviors>
        <behaviors:UpdateTextBindingOnPropertyChanged />
    </i:Interaction.Behaviors>
</TextBox>

3. Call command in ViewModel and pass arguments in response to an event

<TextBox>
    <i:Interaction.Triggers>
        <Triggers:TextBoxEnterKeyTrigger>
            <Triggers:ExecuteCommandAction Command="SomeCommand" />
        </Triggers:TextBoxEnterKeyTrigger>
    </i:Interaction.Triggers>
</TextBox>

TextBoxEnterKeyTrigger source can be found here.

Wednesday, December 21, 2011

C# how to get underlying types from an anonymous type

If you encounter an anonymous type you can get the underlying types using reflection. In my case the source object was of type ‘EntCls81BD186ACCBAB596592C26438762156AD811E’ i.e. unknown to the compiler = dynamically created.

 

foreach (var possibleRowMatch in sourceDataGrid.ItemsSource)
{
    var rowProperties = possibleRowMatch.GetType().GetProperties();
    for (int i = 0; i < rowProperties.Length; i++)
    {
        string propertyName = rowProperties[i].Name;
        Type columnType = rowProperties[i].PropertyType;
        var columnValue = possibleRowMatch.GetType().GetProperty(propertyName).GetValue(possibleRowMatch, null);

        //cast to a columnType
        if (columnValue.GetType() == columnType)
        {
            //do something
        }
    }
}

Tuesday, December 20, 2011

Silverlight update Text property after each letter; Silverlight TextBox get current text; Silverlight force TextBox to rewrite Text property

Our goal is to force TextBox to refresh its Text property. Unfortunately normally Text property is refreshed ONLY when TextBox loses focus. This in unacceptable in my case.

There are 2 solutions to this problem. Creating a custom TextBox control or using PRISM and UpdateTextBindingOnPropertyChanged  behaviour.

The solution from PRISM is the simplest:

<TextBox>
    <i:Interaction.Behaviors>
        <behaviors:UpdateTextBindingOnPropertyChanged />
    </i:Interaction.Behaviors>
</TextBox>

Custom control can be downloaded here.

Thursday, December 15, 2011

Silverlight two lines in a button; Silverlight two polylines in a button; Silverlight draw shapes inside a button

To draw shapes inside a button use Polyline. You use Fill property to set filled shapes color and Stroke to set line’s color. StrokeThickness sets line’s thickness. Points are just X,Y coordinates.

<Button>
    <Grid>
        <Polyline Stroke="Red" StrokeThickness="2" Points="0,0 8,8" />
        <Polyline Stroke="Red" StrokeThickness="2" Points="0,8 8,0" />
    </Grid>
</Button>

image

Wednesday, December 7, 2011

Notepad++ XML Tools Pretty print Errors detected in content

If you’ve installed XML Tools for Notepad++ and after pressing ctrl+shift+alt+B (pretty format XML with line breaks) you get an error:

“Error in content. […..]”

Look for ANY non-UTF-8 characters in your XML. That could be the case.

Sunday, December 4, 2011

how to install coffee-bytes plugin in eclipse; Eclipse folding plugin; manual folding plugin

I had trouble finding a good folding plugin for eclipse Indigo. The installation details are inserted below. In short: download the archive, extract plugins and features folders to the appropriate plugins and features folders in eclipse.

USAGE:

in User Defined Regions tab use e.g.:

Start identifier: region    End identifier: endregion

In code:

//region SomeName
your code
//endregion SomeName

 

Installation instructions:

  1. Install plugin
    1. Unpack the downloaded file eclipse-folding-plugin.tar.gz
    2. Copy the contents of the:
      1. features folder => eclipse features folder
      2. plugins folder => eclipse plugins folder
  2. Configure plugin in Eclipse:
    1. Select "Windows->Preferences"
    2. Select "Java->Editor->Folding"
    3. Check the "Enable folding" option
    4. Select "Coffee Bytes Java Folding" in the "Select folding to use:" option
    5. Check "User Defined Regions" in the "General Fold Setting:" option

Thursday, December 1, 2011

Silverlight DoubleAnimation rotate 180 degrees; Silverlight animation rotate image from style; Rotate ToggleButton image

This example shows how to make a ToggleButton with an image that rotates according to toggle button’s state.

1. Add a ToggleButton to your view and set its style. (You can download a standard toggle button’s style from microsoft’s sites)

2. Edit the Style:

<vsm:VisualStateManager.VisualStateGroups>
    <vsm:VisualStateGroup x:Name="CheckStates">
        <vsm:VisualState x:Name="Checked">
            <Storyboard>
                <DoubleAnimation Duration="0:0:0.25" Storyboard.TargetName="myToggleButtonRotateTransform" Storyboard.TargetProperty="Angle" To="0"></DoubleAnimation>
            </Storyboard>
        </vsm:VisualState>
    </vsm:VisualStateGroup x:Name="CheckStates">
</vsm:VisualStateManager.VisualStateGroups>

<ContentPresenter RenderTransformOrigin="0.5,0.5"
        x:Name="contentPresenter"
        [.... SOME OTHER STANDARD PROPERTIES ...] >
    <ContentPresenter.RenderTransform>
        <RotateTransform x:Name="myToggleButtonRotateTransform" Angle="0" />
    </ContentPresenter.RenderTransform>
</ContentPresenter>

 

Full style source here.

Silverlight xaml style add image

I will cover adding images with the example of ToggleButton. To add an image to a Silverlight style just do the following:

<ToggleButton>
    <Image Source="/Some.Company.Namespace.ModuleName;component/Styles/Images/image.png" Width="10" Height="10" />
</ToggleButton>

Where Some.Company.Namespace.ModuleName is the assembly name (project properties->Assembly name). This is followed by ‘component’ which denotes project folder. Then we have folder path and image file name.

So the path is:

AssemblyName;component/PathToTheImage

Tuesday, November 29, 2011

Replace/change headlights’ light bulb in Opel Corsa C 2006 1.3 CDTI

Changing the light bulb in Opel Corsa’s C can be a little tricky especially when YOU CAN’T really see what’s inside the headlight as there is so little space inside. I decided to take this picture to make our lives a little easier.
Instructions:
1. Hang the wire on the headlight’s bottom’s hook
2. Line-up the wire with the bulb's cavities
3. Pressing the wire to the bulb’s cavities widen the upper part and THEN push it toward the bulb. After pushing the wire start squeezing it together.


C# DependencyProperty assign List or Array; C# convert List to DependencyObject

Actually if you’re trying to set a List<object> to a dependency property you don’t need to do any of these things. Just make your base class inherit from DependencyObject and use SetValue() method.

public class YourClass : DependencyObject
{
    public static DependencyProperty SCProperty = DependencyProperty.RegisterAttached("SC", typeof(List<SD>), typeof(DataGrid), new PropertyMetadata(SCChanged));
                                                                   
    public static void SetSortedColumns(DependencyObject dp, object value)
    {
        dp.SetValue(SCProperty, value);
    }

    public static object GetSortedColumns(DependencyObject dp)
    {
        return dp.GetValue(SCProperty);
    }

    private static void SCChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { }
   
   
    //REST OF YOUR CODE
    [.....]
    //REST OF YOUR CODE
   
    private void SomeMethod()
    {
        SetValue(SCProperty, newValue_List);
    }
}

Monday, November 28, 2011

Silverlight capturing key clicks; Silverlight capturing special key clicks; Silverlight Keyboard.Modifiers class

To capture special key clicks (like ctrl, alt and shift modifier key clicks) one does not have to use KeyDown & KeyUp method. There is a class Keyboard which is available in Silverlight as well. Use Keyboard.ModifierKeys to accomplish desired effect.

Sample usage:

if (Keyboard.Modifiers.Equals(System.Windows.Input.ModifierKeys.Control))
{
    //do something
}

Keyboard.ModifierKeys  allows a bitwise combination of its members.

To capture other key clicks one needs to write a static class which will be available in the whole application.

The example KeyPressMonitor class is available here.

Wednesday, November 23, 2011

C#–Never place an event inside a struct; C# event is always null inside a struct

When you write something similar to:

namespace XXX
{   
    public struct SomeStruct
    {
        public event SomeDelegate SortDirectionChanged;
    }

    public delegate void SomeDelegate(SomeInfo input);
}
   

then SortDirectionChanged event will always be null.
So when you try to set a delegate to the event like this:

var sth = new SomeStruct();
sth.SortDirectionChanged += SomeMethodServingEventCall;

SortDirectionChanged will be null when you'll try to pass on the struct. (when you check it with a debugger right after the assignment it will appear to be ok – strange). Use class instead.

Monday, November 21, 2011

C# change DataTemplate binding; C# change binding inside DataTemplate from code

 

The main idea is to have a DataTemplate in a separate XAML file but change Binding inside this DataTemplate from source code.
Create a xaml file, insert the DataTemplate and change Build action to: Embedded Resource (Copy to Output Directory: Do no copy - it is not necessary). The Assembly.GetManifestResourceStream() loads our resource as string. We can replace bindings then. XamlReader.Load() will convert string to DataTemplate. The Assembly.GetManifestResourceNames() will give you registered embedded resource name if something does not work.


DataTemplate mycolumnDataTemplate = null;
var dataTemplateStream = new ViewDescription().GetType().Assembly.GetManifestResourceStream("Some.Namespace.SomeReosurceName.xaml");
//Load the DataTemplate.
string dataTemplateString = new System.IO.StreamReader(dataTemplateStream).ReadToEnd();
dataTemplateString = dataTemplateString.Replace("[0]", browserColumn.ColumnName);
mycolumnDataTemplate = XamlReader.Load(dataTemplateString) as DataTemplate;

SomeReosurceName.xaml:

<DataTemplate
    x:Key="CustomDataGridColumnTemplate"
    xmlns="
http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <TextBlock Name="CustomTextBox" Text="{Binding [0]}" Margin="0,4,0,0"/>
</DataTemplate>

Friday, November 11, 2011

Android change dialog width; Android set width of a custom Dialog

When one creates custom dialogs in Android there is a problem with setting the width of the dialog to fill the entire available space. I described custom dialog creation here. This sample shows how to set the width of the custom dialogs in Android:

loginDialog.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;

OR

loginDialog.getWindow().setLayout(600, 400);

Android open dialog; Unable to start activity ComponentInfo Unable to add window token null is not for an application

When I tried to open a dialog with getApplicationContext() this error prevented me from accomplishing the goal:

“Unable to start activity ComponentInfo Unable to add window token null is not for an application”

Dialog loginDialog = new Dialog(this);
loginDialog.setContentView(R.layout.loginlayout);
loginDialog.setTitle(R.string.loginScreenHeader);
loginDialog.show();

DO NOT USE:

Context mContext = getApplicationContext();
Dialog loginDialog = new Dialog(mContext);

Android find control reference in activity; reference control from code

There is a simple method that allows us to find a control from the code-behind (android’s activity): findViewById();

Remember to use setContentView(someLayout) before calling the find function to allow the controls to build themselves.

Find a button and bind an acion to it:

final Button button = (Button) findViewById(R.id.button_id);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //some action
            }
        });

Saturday, November 5, 2011

Check torrent port; how to check if your torrent port is open; check if your torrent port is forwarded properly

Some time ago there was an online tool from utorrent to check whether your port is forwarded properly. The service has been moved, however. Nowadays this functionality is built into utorrent.
So what should you do if you use a different torrent client? - e.g. Transmission or a torrent client on your router.

There is still an online solution for this but it's hard to find the proper site. One of the services that actually works is:

http://www.canyouseeme.org/

Have fun with it.

Friday, October 28, 2011

Silverlight DataGrid dynamic binding in DataGridTemplateColumn

The problem is that we want to bind a field from a custom object. This field is of type different from string (we could use DataGridTextColumn and set its binding like this:

DataGridColumns.Add(new DataGridTextColumn());
((DataGridBoundColumn) DataGridColumns[DataGridColumns.Count - 1]).Binding = new Binding() {Path = new PropertyPath("A")};    )

The only other Column type in SL4 is DataGridTemplateColumn. So we have to create a template, insert a TextBox into it and bind its text to our property. The solution looks as follows:

 

DataGridColumns.Add(new DataGridTemplateColumn());
string templateString = "<DataTemplate x:Key=\"CustomDataGridColumnTemplate\" "
    + "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"  "
    + "xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" >"
    + "<TextBox Name=\"CustomTextBox\" Text=\"{Binding [0]}\" />"
    + "</DataTemplate>";
templateString = templateString.Replace("[0]", "A");
DataTemplate mycolumntemplate = XamlReader.Load(templateString) as DataTemplate;
((DataGridTemplateColumn) DataGridColumns[DataGridColumns.Count - 1]).CellTemplate = mycolumntemplate;
DataGridColumns[DataGridColumns.Count - 1].Header = browserColumn.Name;
DataGridColumns[DataGridColumns.Count - 1].Width = DataGridLength.Auto;

 

Note: You don’t need to include any namespaces if you don’t use x:Name etc.

Friday, October 14, 2011

Silverlight DataGrid custom style desynchronized header and body columns; Silvelight DataGrid out of place

The problem lies in editing DataGrid style. When you wrap:

<sdk:DataGridCellsPresenter  Name="CellsPresenter"  />

with a border the header in not synchronized with the body of the grid anymore. The simple solution to this problem is to move:

sdk:DataGridFrozenGrid.IsFrozen="True"

from the Cells presenter to the most outer element you wrap the grid body with. Complete solution with Grid border looks like this:

<!-- CellPresenter content part -->
<Border BorderBrush="Black" BorderThickness="0.25" Controls:Grid.Column="1" sdk:DataGridFrozenGrid.IsFrozen="True">
    <sdk:DataGridCellsPresenter  Name="CellsPresenter"  />
</Border>

Tuesday, October 11, 2011

Silverlight CustomValidation attribute; ValidationResult.MemberNames.Count == 0

When writing CustomValidation remember to include memberNames in ValidationResult. ValidationResult.MemberNames include property names which are validated at a given moment (are connected to the validation result which we received).

Sample validation should look like the following:

public class CustomValidationMethods
{
    public static ValidationResult SthNumberValidation(string name, ValidationContext validationContext)
    {
        string[] memberNames = new string[] { validationContext.MemberName };

        if (name.StartsWith("B"))
            return ValidationResult.Success;
        else
            return new ValidationResult("Name does not begin with 'B'", memberNames);
    }
}

Silverlight System.Windows.Controls.ComboBox System.InvalidOperationException: Element is already the child of another element

Never try to use elements of Items collection of ComboBox directly and add them to a GRID like this:

SomeCellContainer.Add(SomeComboItems[iter]);

Everything works fine until you need to change the selected Item. When you press on the ComboBox (Silverlight behaviour) the application crashes with System.InvalidOperationException: Element is already the child of another element.

Thursday, October 6, 2011

Silverlight Hierarchical DataGrid; TreeList DataGrid in pure Silverlight

The purpose of this sample code is to create a DataGrid which rows can be expanded. In others words a combination of DataGrid and a TreeList.

Original post is available here:

http://blogs.perpetuumsoft.com/silverlight/how-to-turn-silverlight-datagrid-to-treegrid-in-15-minutes/

I just converted the project from VS2008 to VS2010&SL4:

http://sites.google.com/site/bkosarzyckistorage1/HierarchicalGridDemoVisualStudio2010.7z

Friday, September 23, 2011

Silverlight Passing event from Theme to View; Passing button's click as event from Theme to View's class property

View:

<controls:ChildWindow  [....]
Name="Window">

<perspControls:WizardControl Background="Red" TabStripPlacement="Left" TabNavigation="Once" >
                   
    <!-- Wizzard events -->
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Cancelling">
            <ei:ChangePropertyAction PropertyName="DialogResult" Value="False" TargetName="Window" />
        </i:EventTrigger>
    </i:Interaction.Triggers>

    <!-- Wizzard items -->
    <perspControls:WizardControl.Items>
        [... some items here ...]
    </perspControls:WizardControl.Items>
   
</perspControls:WizardControl>

ViewModel:

 

Theme:

<ResourceDictionary
    [....]
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
    >

    <Style TargetType="controls:WizardControl">
    [.....]
   
        <Setter Property="Template">
       
        [....]
       
            <Grid x:Name="TemplateLeft" >
            [...]
           
                <!-- Wizzard buttons -->
                <Grid Grid.Row="1">
                    <StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
                        <Button HorizontalAlignment="Right" Content="Wstecz" Command="{Binding WsteczCommand}" Width="70" />
                        <Button HorizontalAlignment="Right" Content="Dalej" Command="{Binding DalejCommand}" Width="70" />
                        <Button x:Name="CancelButton" Content="Anuluj" Command="{Binding CancelCommand}" DataContext="{TemplateBinding DataContext}"  />
                    </StackPanel>
                </Grid>
               
            </Grid>
           
           
Control Class:

public class WizardControl : TabControl
{
    public WizardControl()
    {
        DefaultStyleKey = typeof(WizardControl);
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        var cancelButton = (GetTemplateChild("CancelButton") as Button);
        cancelButton.Click += (s, e) =>
        {
            if (Cancelling != null)
            {
                Cancelling(this, e);
            }
        };
    }

    public event RoutedEventHandler Cancelling;
}       

Thursday, September 22, 2011

Silverlight Data Validation in controls

Overall validation description

In the View we set ValidatesOnExceptions=True.

<TextBox Name ="IntValueTextBox" Text="{Binding IntValue, Mode=TwoWay, ValidatesOnExceptions=True}">

In ViewModel the property that we want bind to and want to validate looks as follows:


[System.Diagnostics.DebuggerHidden()]
public string IntValue
{
    get { return intValue.ToString(); }
    [System.Diagnostics.DebuggerHidden()]
    set
    {
        int temp;
        if (!Int32.TryParse(value, out temp))
        {
            throw new Exception("Please enter a valid integer value");
        }
        else
        {
            intValue = Int32.Parse(value);
        }
    }
}
private int intValue;

Hiding validation exception for Visual Studio Debugger

While using validation (get;set; property approach) validation expceptions are thrown as follows:

throw new Exception("Please enter a valid integer value");

It causes quite disturbing effect of receiving errors in Visual Studio debugger. When using:

[System.Diagnostics.DebuggerHidden()]

in every property that we validate and its get; set; methods we will hide these error from the debugger.

Wednesday, September 21, 2011

Enable Windows 7-like menu in Windows 8 preview release; enable standard start menu in Windows 8 preview

There is a simple way to enable Windows 7 like menu in Windows 8. After completing the edit described below you will have two menus. The ugly Metro menu after moving your mouse to the lower left corner of the screen and pressing start icon AND THE STANDARD Windows 7 like start menu after just pressing the start key as usual :)

 

Open Run type regedit.exe hit Enter key to launch Registry Editor.
In the Registry Editor, navigate to

HKEY_CURRENT_USER\Software\Mic­rosoft\Windows\CurrentVersion\­Explorer

In the right pane, double-click on the entry named RPEnabled and change its value from 1 to 0 to enable the Windows 7 Start menu.

Friday, September 16, 2011

Read & Write <system.serviceModel> section fom app.config file in C#

 

System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(typeof(ConfigOperation).Assembly.Location);

System.ServiceModel.Configuration.ServiceModelSectionGroup serviceModelSection = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(configuration);

//setting clientCertificateName
var enumer = serviceModelSection.Behaviors.EndpointBehaviors.GetEnumerator(); enumer.MoveNext();
System.ServiceModel.Configuration.EndpointBehaviorElement endpointBehaviour = (System.ServiceModel.Configuration.EndpointBehaviorElement)enumer.Current;
System.ServiceModel.Configuration.ClientCredentialsElement clientCred = (System.ServiceModel.Configuration.ClientCredentialsElement)endpointBehaviour.First();
clientCred.ClientCertificate.FindValue = "CERTIFICATE_NAME”;

//save config file
configuration.Save(System.Configuration.ConfigurationSaveMode.Modified, true);
   

Thursday, September 15, 2011

convert .pem & .key certificate formats to .p12 certificate format. Import certificate with private key; merge .pem & .key certificates; System.NotSupportedException: The private key is not present in the X.509 certificate; error in System.IdentityModel.Tokens.X509AsymmetricSecurityKey.GetSignatureFormatter(String algorithm)

To have a valid certificate for client - soap_server connection in X.509 you need to have a certificate in your store that has a private key, that is a merged .pem (with certificate) and .key (with private key).

.key file:

-----BEGIN RSA PRIVATE KEY-----
[.....]
-----END RSA PRIVATE KEY-----

.pem file:

-----BEGIN CERTIFICATE-----
[.....]
-----END CERTIFICATE-----

The solution is to convert these two files to e.g. p12 format which contains both certificate and private key.

Solution

Do this by merging the files (just placing one part over the other or appending the .pem file to the .key file.

Then fire up the console command:

openssl pkcs12 -export -in keyAndPem.merge  -out  out_file.p12

Import the .p12 file to windows and you're good to go.

To check that your imported certificate has private key along with it look for this info in the properties of the certificate:

image

 

Using the certificate without private key will cause these errors in SOAP communication:

The private key is not present in the X.509 certificate;

error in System.IdentityModel.Tokens.X509AsymmetricSecurityKey.GetSignatureFormatter(String algorithm)

Monday, September 12, 2011

Silverlight; TextBox.TextChanged event in ViewModel; Firing command with command parameter in MVVM using MVVM Light Toolkit from Galasoft.ch

 

This code does two things: updates designated property in View class and fires a command in ViewModel based on some event from TextBox. In our case the event is TextChanged.
This is a real MVVM solution to this problem. You can download MVVM Light toolkit from http://www.galasoft.ch/mvvm/installing/#binaries.


<TextBox Name="textBox1" Text="{Binding Name, Mode=TwoWay}">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="TextChanged">
                            <!-- Update property in View class -->
                            <ei:ChangePropertyAction PropertyName="MarkEditionStatus" Value="True" TargetName="SomePropertyInViewClass" />
                            <!-- Fire a command in ViewModel
                            <cmd:EventToCommand Command="{Binding TextBox_TextChanged, Mode=OneWay}"
                                CommandParameter="{Binding Text, ElementName=textBox1, Mode=OneWay}"
                                MustToggleIsEnabledValue="True" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </TextBox>

#region TextBoxFunctions

ViewModel:

public ViewModelConstructor(....)
{
    [....]
   
    [....]
    TextBox_TextChanged = new ActionCommand((o) => textBox_TextChanged(o));
}

#region TextBoxFunctions

public ICommand TextBox_TextChanged { get; private set; }

private void textBox_TextChanged(object arg)
{
    MessageBox.Show("AAA");
}

#endregion TextBoxFunctions

Thursday, September 1, 2011

Control opening Views in PRISM - Single instance or opening many separate instances of the view in one region; Single instance views in PRISM; Silverlight

Controlling the bahaviour of the view (Single instance View or many separate instances) can be done from IsNavigationTarget method from INavigationAware interface.
This method returns Boolean value.

true - opens Single instance of the view
false - opens many separate instances of the view in one region


public class SomeViewModel : NotificationObject, IConfirmNavigationRequest, ITabbedContent
{

......

  bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
  {
      return true; //Opening Single instance of the view
  }

......

}

Wednesday, August 31, 2011

Show PRISM message box; Display message box using PRISM MVVM Silverlight

We want to display a message box with the help of PRISM in Silverlight.
There is a different class for displaying an question - Confirmation. We
can display our own window with InteractionRequest<OurViewModel> and some code in XAML
defining which view to run.


Message box class in defined in PRISM's namespace:
namespace: Microsoft.Practices.Prism.Interactivity.InteractionRequest

Class name is Notification.

SomeView, XAML:

<UserControl x:Class="WebClient.SomeView"
..... >

    <Grid x:Name="LayoutRoot" Background="White">
        <i:Interaction.Triggers>
            <prism:InteractionRequestTrigger SourceObject="{Binding SaveNotification}">
                <prism:PopupChildWindowAction/>
            </prism:InteractionRequestTrigger>
        </i:Interaction.Triggers>
    </Grid>
</UserControl>

SomeViewModel, cs:

public class SomeViewModel
{
    public SomeViewModel(......)
    {
        saveNotification = new InteractionRequest<Notification>();
    }

    private readonly InteractionRequest<Notification> saveNotification;

    //this function displays message box
    private void someFunction(object obj)
    {
        //show message box
        ((InteractionRequest<Notification>)saveNotification).Raise(new Notification { Title = "Information", Content = "User was saved." });           
    }

    public IInteractionRequest SaveNotification
    {
        get { return this.saveNotification; }
    }
}

Set property in View from ViewModel in MVVM using Interaction Triggers; Set View's property from ViewModel without code behind in Silverlight 4.0

We have a View which is a Window control with DialogResult property and we want to set this property to True without using code behind.

<controls:ChildWindow  x:Class="WebClient.Views.ConfWorkerView"

   xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
   xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
   xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions”
Name="Window" >

  <UserControl>
    <Grid>
    <Button HorizontalAlignment="Right" Content="Save"  Command="{Binding SaveCommand}" >
          <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
               <ei:ChangePropertyAction PropertyName="DialogResult" Value="True" TargetName="Window"/>
            </i:EventTrigger>
          </i:Interaction.Triggers>
       </Button>
    <Grid>
  <UserControl>
</controls:ChildWindow>

Tuesday, August 23, 2011

PRISM passing data in RegionContext

Define region in the following way - with regionName and region context defined

xmlns:regions="clr-namespace:Microsoft.Practices.Prism.Regions;assembly=Microsoft.Practices.Prism"

<ItemsControl MinHeight="400" regions:RegionManager.RegionName="RCP.WorkerShowPersonalDataRegion" regions:RegionManager.RegionContext="{Binding Path=CurrentWorker, Mode=TwoWay}" >
    <!-- PRISM registers various types of configuration views here -->
</ItemsControl>

 

Receive Context in ViewModel like this:
this.RegionContext = regionManager.Regions[RegionNames.WorkerShowPersonalDataRegion].Context;

This can be done in Constructor or e.g. OnNavigatedTo method from PRISM INavigationAware.

PRISM region in ItemsControl, Region.RegionContext is null when deleting views from region

When you delete views from your region, the RegionContext is set to null. This is probably done to
prevent memory leaks but is really frustrating at the beginning. To prevent RegionContext from being
deleted you have two options:
1) use <ContentControl as your region control. In this solution views will be replace and you won't have to delete view from region thus preventing RegionContext from being nulled
2) Clone the object that you set as RegionContext (not really a neat solution)

//delete views from your region
IViewsCollection views = regionManager.Regions[RegionNames.WorkerShowPersonalDataRegion].Views;
int count = views.Count();
foreach (var view in views)
{
    regionManager.Regions[RegionNames.WorkerShowPersonalDataRegion].Remove(view);
}
regionManager.Regions[RegionNames.WorkerShowPersonalDataRegion].Context = new Worker(CurrentWorker);

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
            }
        }

Tuesday, June 28, 2011

Latex insert chapter without chapter heading; latex chapter without preceding “chapter” heading; latex chapter without “chapter” phrase

To insert a chapter in Latex without the chapter heading (next page will be preserved, as well as font size etc) you can use \chapter*. Unfortunately chapter* is not added to table of contents automatically so you need to do it manually.

Source code:

\chapter*{Introduction}
  \addcontentsline{toc}{chapter}{Introduction}

Friday, June 24, 2011

MySQL Insert statement with nested CASE and SELECT

The MySQL manual is a little bit confusing so I just wanted to give an example of MySQL’s insert statement with nested CASE and SELECT.

INSERT INTO TEST (startdate, testname, ipaddress, hostname, customerid, application)
  SELECT NOW(),'TEMP_TESTNAME', '192.168.1.1', 'TEMP_HOST',
  CASE count(id)
      WHEN 1 THEN id
      ELSE (SELECT id FROM customer where customername like '%OTHER%')
  END
  , 'MARKET_XXX'
  FROM customer WHERE CUSTOMERNAME like '%XXX%';

Thursday, June 16, 2011

Flex add Buttons to an array; Flex add spark.components.TextInput to an mx.collections.ArrayCollection;

Whether you add buttons or textInput does not really matter. I had a couple of text inputs and wanted to change their properties all at once so I added them to an array.

TextInputs:

<s:TextInput x="10" y="6" width="287" fontWeight="bold" id="TestNameInput" />
<s:TextInput x="10" y="42" width="287" fontWeight="bold" id="IPInput" />
<s:TextInput x="10" y="74" width="287" fontWeight="bold" id="HostInput" />
<s:TextInput x="9" y="111" width="287" fontWeight="bold" id="CustomerInput" />
<s:TextInput x="10" y="150" width="287" fontWeight="bold" id="AppInput" />
<s:TextInput x="10" y="186" width="287" fontWeight="bold" id="MemoInput" />

Declare an array collection:

public var inputFieldsArray:ArrayCollection = new ArrayCollection(null);

Add text inputs to an array in the creation event:

protected function group1_creationCompleteHandler(event:FlexEvent):void
{
     //adding input fields to the array
     inputFieldsArray.addItem(TestNameInput);
     inputFieldsArray.addItem(IPInput);
     inputFieldsArray.addItem(HostInput);
     inputFieldsArray.addItem(CustomerInput);
     inputFieldsArray.addItem(AppInput);
     inputFieldsArray.addItem(MemoInput);
}

Wednesday, June 15, 2011

Import database in mysql from *.sql file; execute sql file under mysql on windows; Import exported database in mysql

You can use mysql.exe from c:\wamp\bin\mysql\mysql5.5.8\bin\

 

C:\>mysql -h 127.0.0.1 -u root -p wirtlab < c:\public\localhost.sql
Enter password: ***

wirtlab is the database name.

-p should be used WITHOUT giving the password
(as you can see mysql asks you for password after executing the command)

Flex Esc key should close opened pop-up window; How to close pop-up windows with Esc key Flex

To make Esc key close the current window you need to bind events:

<s:Group  xmlns:fx="http://ns.adobe.com/mxml/2009"
         xmlns:s="library://ns.adobe.com/flex/spark"
         xmlns:mx="library://ns.adobe.com/flex/mx"
         xmlns:local="*"
         width="1216" height="562" keyDown="group1_keyDownHandler(event)" creationComplete="titlewindow1_creationCompleteHandler(event)">

 

group1_keyDownHandler function is an event handler for user clicks:

protected function group1_keyDownHandler(event:KeyboardEvent):void
            {
                if (event.keyCode == Keyboard.ESCAPE) {
                    button1_clickHandler(null);
                }
            }

You need to bind event listener to this function manually as well (don’t really know why because you did it earlier):


protected function titlewindow1_creationCompleteHandler(event:FlexEvent):void
            {
                stage.addEventListener(KeyboardEvent.KEY_DOWN, group1_keyDownHandler);
            }

I have added some imports to enable events. These are:

      import flash.display.*;
      import flash.events.*;
      import flash.text.*;
      import flash.ui.Keyboard;