RSS

Unable to update the EntitySet because no <InsertFunction> element existing

Today I received a strange error when saving a newly created entity into the database.

Unable to update the EntitySet ‘EntityName’ because it has a DefiningQuery and no <InsertFunction> element exists in the element to support the current operation.

Well this is strange. The EntityName is a table in SQL and there should be no problems in inserting a new entry by using conn.Set<EntityName>().Create().

Looking at the SQL script to create the table, I realized that the problem was, that no Primary Key has been defined for the table. Therefore Entity Framework decided that EntityName should be traced as a View. Adding a primary key solved the above shown issue.

 
Leave a comment

Posted by on May 28, 2015 in C-Sharp, EF, SQL

 

Tags: , ,

Log request URI in ASP.NET Web API

If you want to know how your users call your ASP.NET Web API you can hook into the process by implementing a custom Message Handler. This is done by creating a class that inherits from DelegatingHandler. In the overwritten SendAsync method you can implement your logging structure:

public class UrlCallLogger : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
                                HttpRequestMessage request,
                                CancellationToken cancellationToken)
    {
        Debug.WriteLine(request.RequestUri);
        // do more with your logging
        // [...]
        return base.SendAsync(request, cancellationToken);
    }
}

Then in the Register method of the WebApiConfig class you have to add following line:

config.MessageHandlers.Add(new UrlCallLogger());

About how to config

 
Leave a comment

Posted by on May 26, 2015 in C-Sharp

 

Tags:

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

 
6 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:

 
Follow

Get every new post delivered to your Inbox.