RSS

Tag Archives: Csharp

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

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

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

Inlines and Run in TextBlock does not follow Language override

If you want to localize your application you generally override the LanguageProperty with your desired language:

FrameworkElement.LanguageProperty.OverrideMetadata(
    typeof(FrameworkElement), 
    new FrameworkPropertyMetadata(XmlLanguage.GetLanguage("de-DE")));

As stated in the documentation every control should now use the – in this case – German culture. Well this is not the case. If you have a TextBlock and set the Text property then this works, but if you have a TextBlock with Inline elements, then the en-us culture is used.
This is very stange. Why is that the case? TextBlock inherits from FrameworkElement and because you have overridden the FrameworkElement.LanguageProperty this works. But if you use Inlines, such as Run, Italic, Underline, … those controls inherits from FrameworkContentElement and not from FrameworkElement for which you do not have overridden the corresponding DependencyProperty. This is the only reason why Inlines do not follow the application wide culture. As solution for that you have to override the LanguageProperty for FrameworkContentElements.

FrameworkContentElement.LanguageProperty.OverrideMetadata(
    typeof(FrameworkElement),
    new FrameworkPropertyMetadata(XmlLanguage.GetLanguage("de-DE")))

This does not work because it says that is is already registered. So a workaround is to override if for every class that is one inheritance hierarchy lower than FrameworkContentElement:

 FrameworkContentElement.LanguageProperty.OverrideMetadata(
    typeof(DefinitionBase),
    new FrameworkPropertyMetadata(XmlLanguage.GetLanguage("de-DE")));

            FrameworkContentElement.LanguageProperty.OverrideMetadata(
    typeof(FixedDocument),
    new FrameworkPropertyMetadata(XmlLanguage.GetLanguage("de-DE")));

            FrameworkContentElement.LanguageProperty.OverrideMetadata(
    typeof(FixedDocumentSequence),
    new FrameworkPropertyMetadata(XmlLanguage.GetLanguage("de-DE")));

            FrameworkContentElement.LanguageProperty.OverrideMetadata(
    typeof(FlowDocument),
    new FrameworkPropertyMetadata(XmlLanguage.GetLanguage("de-DE")));

            FrameworkContentElement.LanguageProperty.OverrideMetadata(
    typeof(TableColumn),
    new FrameworkPropertyMetadata(XmlLanguage.GetLanguage("de-DE")));

            FrameworkContentElement.LanguageProperty.OverrideMetadata(
    typeof(TextElement),
    new FrameworkPropertyMetadata(XmlLanguage.GetLanguage("de-DE")));

Now the Inlines in TextBlock follows the culture that you have specified

 
Leave a comment

Posted by on September 25, 2014 in C-Sharp

 

Tags:

Cannot find all types required by the ‘async’ modifier

If you use the async and await keyword in .NET 4.0 with Visual Studio 2012, you may get following error.

Cannot find all types required by the ‘async’ modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?

The problem is that you have not installed the API that is necessary to use the ‘async’ and ‘await’ keyword in the 5.0 version of C#. Furthermore you get this exception only if you use those two keywords in .NET 4.0 applications. You will not see this exception neither in .NET 4.0 nor in WinRT apps.

The solution to this problem is to reference following nuGet package into all projects in which you want to use the ‘async’ and ‘await’ keyword:

Microsoft.CompilerServices.AsyncTargetingPack.

 
Leave a comment

Posted by on September 19, 2012 in C-Sharp

 

Tags: ,