RSS

Reflection: Call private Constructor with optional parameters

If you want to create a test for a class that has only a private constructor and that has some optional parameters you might result in nasty reflection problems. As you know private constructors can be easily called via reflection:

public class Test
{
    public static readonly Test Field1 = new Test("Value1");
    public static readonly Test Field2 = new Test("Value2", true);

    public Test(string value, bool isActive = false)
    {
        // [...]
    }
    // [...]
}


var ctor = typeof(Test).GetConstructor(
    BindingFlags.NonPublic |
    BindingFlags.Instance,
    null,
    new[] { typeof(string), typeof(bool)},
    null);

This code will not resolve the correct constructor and returns null, even though you pass only new[] { typeof(string)} as parameter for the type array. There is a simple binding flag that has additionally set: BindingFlags.OptionalParamBinding

By adding this enumeration value to the bindingAttr-parameter you have the working code:

var ctor = typeof(Test).GetConstructor(
    BindingFlags.NonPublic |
    BindingFlags.Instance |
    BindingFlags.OptionalParamBinding,
    null,
    new[] { typeof(string), typeof(bool)},
    null);

Just do not forget that if you do not pass a value for isActive you have to pass Type.Missing when you call the Invoke method. If you do not add the second parameter, even though it is optional, a TargetParameterCountException will be thrown.

var instance = ctor.Invoke(new[] { "Test", Type.Missing });

Edit

If you are using .NET 4.5 or newer you can also shorten the above code by creating an instance using GetTypeInfo with following code.

var instance = typeof(Test).GetTypeInfo()
                           .DeclaredConstructors
                           .First(i => i.IsPrivate)
                           .Invoke(new[]
                           {
                               "Test",
                               Type.Missing,
                               Type.Missing
                           });
 
Leave a comment

Posted by on April 16, 2015 in C-Sharp

 

Change synchronization interval for published calendars in Office 365

By default a subscribed ics. calendar from Office 365 contains calendars entries that range from -3 months to +6 months. If you want to publish a calendar on which subscribing users will see a yearly overview this time range is far too short. Therefore, listing calendar entries for the next half-year only is not ideal. The solution to this problem is to change the synchronization settings of Office 365 for the published calendar in such a way that the subscribed calendar synchronizes entries up to one year. This can be achieved using the PowerShell:

$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
$Office365PS = Import-PSSession $Session

if you execute the following command you will see:

Get-MailboxCalendarFolder -identity "MailboxName:NameOfCalendar"

RunspaceId : xxx
Identity : MailboxName:NameOfCalendar
PublishEnabled : True
PublishDateRangeFrom : ThreeMonths
PublishDateRangeTo : SixMonths
DetailLevel : FullDetails
SearchableUrlEnabled : False
PublishedCalendarUrl : http://outlook.office365.com/owa/calendar/xxx/calendar.html
PublishedICalUrl : http://outlook.office365.com/owa/calendar/xxx/calendar.ics
IsValid : True
ObjectState : Unchanged

To update the PublishDateRangeTo to OneYear — which is the largest value — just execute following command:

Set-MailboxCalendarFolder -identity "MailboxName:NameOfCalendar" -PublishDateRangeTo OneYear

Now, by executing following command again you will see the change of the PublishDateRangeTo value

Get-MailboxCalendarFolder -identity "MailboxName:NameOfCalendar"

RunspaceId : xxx
Identity : MailboxName:NameOfCalendar
PublishEnabled : True
PublishDateRangeFrom : ThreeMonths
PublishDateRangeTo : OneYear
DetailLevel : FullDetails
SearchableUrlEnabled : False
PublishedCalendarUrl : http://outlook.office365.com/owa/calendar/xxx/calendar.html
PublishedICalUrl : http://outlook.office365.com/owa/calendar/xxx/calendar.ics
IsValid : True
ObjectState : Unchanged

At the end do not forget to close the session:

Remove-PSSession $Session

Possible Error messages:

It may be that you encounter following error:

Import-PSSession : Files cannot be loaded because running scripts is disabled on this system. Provide a valid certificate with which to sign the files.

This is because your ExecutionPolicies are set to Rescricted. To change this type following command into the PowerShell with elevated rights.

Set-ExecutionPolicy RemoteSigned
 
Leave a comment

Posted by on February 5, 2015 in Uncategorized

 

Tags:

StringFormat missing for Bindings in Windows Phone 8.1

There is currently no possibility to use StringFormat in bindings if you develop a Windows Phone 8 project. With normal Windows applications this is done with the following XAML code.

<TextBox Text="{Binding Path=MyProperty, StringFormat='{}{0:N0} pcs.'}" />

You will miss this feature in Windows Phone projects. But there is a simple solution to overcome this problem. The solution is to use a class that inherits from IValueConverter. There you provide the logic to apply the formatting of the string.

public sealed class StringFormatConverter : IValueConverter 
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
        {
            return null; 
        }
        if (parameter == null)
        {
            return value;
        }
        return string.Format((string)parameter, value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

In your XAML you can use this converter as follows:

<Grid>
    <Grid.Resources>
        <converters:StringFormatConverter x:Key="StringFormatConverter" />
    </Grid.Resources>
    <TextBox Text="{Binding Path=MyPropterty,
                            Converter={StaticResource StringFormatConverter},
                            ConverterParameter='{}{0:N0} pcs.'}" />
</Grid>
 
Leave a comment

Posted by on January 14, 2015 in C-Sharp, WP8.1, WPF

 

Tags: ,

TreeView in Windows Phone 8.1

There is currently no TreeView control in Windows Phone 8.1 but you can construct a TreeView very easy. Just create a Tree class and a DataTemplate as follows:

public class Tree<T> : INotifyPropertyChanged
{
    private bool _isExpanded;

    public Tree()
    {
        Children = new List<Tree<T>>();
    }

    public T Item { get; set; }
    public List<Tree<T>> Children { get; set; }

    public bool IsExpanded
    {
        get { return _isExpanded; }
        set
        {
            _isExpanded = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

public sealed class BooleanToVisibilityConverter : IValueConverter
{
    public object Convert(object value, 
                          Type targetType, 
                          object parameter,
                          string language)
    {
        return ((bool)(bool?)value) ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, 
                              Type targetType, 
                              object parameter, 
                              string language)
    {
        throw new NotImplementedException();
    }
}

In XAML you can write a PivotItem as follows. Below the XAML code you will find a sample MainViewModel that fills the data for the TreeView.

<Page x:Class="TreeViewTest.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:TreeViewTest"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      mc:Ignorable="d"
      Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.DataContext>
    <local:MainViewModel />
</Page.DataContext>
<Grid>
<Grid.Resources>
    <local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter />
</Grid.Resources>
<PivotItem Header="TreeViewSample">
    <PivotItem.Resources>
        <DataTemplate x:Key="NodeNestedTemplate">
            <StackPanel>
                <StackPanel Orientation="Horizontal">
                    <ToggleButton Name="ToggleButton"
                                  Content="đź”˝"
                                  MinWidth="10"
                                  BorderThickness="0"
                                  IsChecked="{Binding Path=IsExpanded, Mode=TwoWay}"
                                  Style="{x:Null}"/>

                    <Button BorderThickness="0">
                        <StackPanel>
                            <TextBlock Text="{Binding Path=Item.ArticleName}"
                                       Style="{ThemeResource ListViewItemTextBlockStyle}" />
                            <TextBlock Text="{Binding Path=Item.ArticleNumber}"
                                       Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}" />
                        </StackPanel>
                    </Button>
                </StackPanel>

                <StackPanel Orientation="Horizontal">
                    <Rectangle Width="1"
                               Height="{Binding Path=Height, ElementName=ListView}"
                               Fill="Red" />
                    <ListView MinHeight="0"
                              Name="ListView"
                              Margin="20"
                              Visibility="{Binding Path=IsExpanded, Converter={StaticResource BooleanToVisibilityConverter}}"
                              ItemsSource="{Binding Path=Children, Mode=TwoWay}"
                              ItemTemplate="{StaticResource NodeNestedTemplate}" />
                </StackPanel>
            </StackPanel>        
        </DataTemplate>
    </PivotItem.Resources>
    <ScrollViewer>
        <ContentControl Content="{Binding Path=MyPropertyInDataContextContainingTheTree, Mode=TwoWay}"
                        ContentTemplate="{StaticResource NodeNestedTemplate}" />
    </ScrollViewer>
</PivotItem>
</Grid>
</Page>
public class MainViewModel
{
    public MainViewModel()
    {
        MyTree = new Tree<Article>();
        MyTree.Item = new Article("root", "12345");

        MyTree.Children.Add(new Tree<Article>{Item = new Article("Art1","12345")});
        MyTree.Children.Add(new Tree<Article> {Item = new Article("Art2","12345")});

        MyTree.Children[0].Children.Add(new Tree<Article>{Item = new Article("Art1.1","12345")});
        MyTree.Children[0].Children.Add(new Tree<Article>){Item = new Article("Art1.2","12345")});
        MyTree.Children[0].Children.Add(new Tree<Article>){Item = new Article("Art1.3","12345")});

        MyTree.Children[0].Children[1].Children.Add(new Tree<Article>{Item = new Article("Art1.2.1", "12345")});
        MyTree.Children[0].Children[1].Children.Add(new Tree<Article>{Item = new Article("Art1.2.2", "12345")});

        MyTree.Children[1].Children.Add(new Tree<Article>{Item = new Article("Art2.1", "12345")});
        MyTree.Children[1].Children.Add(new Tree<Article>{Item = new Article("Art2.1", "12345")});
    }

    public Tree<Article> MyTree { get; private set; } 
}

Then you may have a beautiful TreeView as in the following example:

TreeView

 
5 Comments

Posted by on January 8, 2015 in C-Sharp, WP8.1

 

Tags: ,

GIT: allow push to master only if build succeeds

It may be a requirement of companies, that the master and develop branch contains only code that is always compilable. Therefore we need to ensure that every push, or merge on a master branch results not in breaking the build of the application. This can be achieved with git-hook file that has the Name pre-commit and is copied into .git\hooks directory.

#!/bin/sh
branch=$(git rev-parse --abbrev-ref HEAD)

if [ "master" != "$branch" ] && [ "develop" != "$branch" ]; then
    exit 0;
fi

echo "To commit on a master or develop branch we need to check whether msbuild compiles successful."

"C:\Program Files (x86)\MSBuild\12.0\Bin\MSBuild.exe" /consoleloggerparameters:"ErrorsOnly;PerformanceSummary"
status=$?

if [ "$status" != "0" ]; then
    echo "Build failed. If you publish to the $branch branch you should ensure that the solution builds correctly"
fi
exit $status
 
Leave a comment

Posted by on December 18, 2014 in C-Sharp, Git

 

Tags:

GIT: push every commit immediately to origin

If I am working not on my primary PC I sometimes forget to push commits to the origin remote. Therefore next day I am in company I miss commits that are local on the other PC. To avoid that problem I wrote a git-hook that pushes every commit instantly to the origin-remote.

For this you need to create the file post-commit with following content

#!/bin/sh
#With this git-hook every commit is immeditely pushed to origin

branch=$(git rev-parse --abbrev-ref HEAD)
echo Pushing commit to origin/$branch
git push -u origin $branch

Save the file to the .git\hooks directory. Now after each git commit the commit is pushed to the remote.

 
Leave a comment

Posted by on December 17, 2014 in Git

 

Tags:

Found conflicts between different versions of the same dependent assembly

warning MSB3277: Found conflicts between different versions of the same dependent assembly that could not be resolved. These reference conflicts are listed in the build log when log verbosity is set to detailed.

First of all Change build log verbosity to detailed. This is done by changing the value for Tools>Options>Project and Solutions>Build and Run>MSBuild project outbut verbosity to detailed.

After that you can rebuild the solution. During build time MSBuild writes a lot of information to the Output-View. After build completition you have to search the whole log file for the corresponding assembly conflict. You can do this by using CTRL+F to open the search-view, entering “conflict” and hitting the search button. Visual Studio highlights all corresponding matches. Search for a message that states a sentence like the following:

There was a conflict between “System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ and “System.Windows.Interactivity, Version=4.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″.
“System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ was chosen because it was primary and “System.Windows.Interactivity, Version=4.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ was not.

Just remove the reference to the wrong assembly from the current built project System.Windows.Interactivity, Version=4.0.0.0 and add the reference to the correct assembly System.Windows.Interactivity, Version=4.5.0.0 and the warning is gone when you build the Project the next time.

After that you are free to change the build verbosity back to the previous value.

 
Leave a comment

Posted by on November 10, 2014 in C-Sharp

 

Tags: ,

 
Follow

Get every new post delivered to your Inbox.