Search This Blog

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
  }

......

}