RSS

Category Archives: C-Sharp

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

 

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

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

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.

 
3 Comments

Posted by on November 10, 2014 in C-Sharp

 

Tags: ,