Showing posts with label .Net Framework. Show all posts
Showing posts with label .Net Framework. Show all posts

Friday, 7 June 2013

SGEN: Mixed mode assembly is built against version 'v2.0.50727'…

I found while building an VB application in Visual Studio 2012, in release mode for the first time, that I was confronted with cryptic build error;
SGEN: Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
After trawling through some Google results, I found the following post by Microsoft;

http://social.msdn.microsoft.com/Forums/en-US/clr/thread/2a5bf31e-df96-4bf1-a846-699da46b62fb

And also a couple of forums;

http://stackoverflow.com/questions/3749368/team-build-sgen-mixed-mode-assembly
http://social.msdn.microsoft.com/Forums/en-US/clr/thread/2a5bf31e-df96-4bf1-a846-699da46b62fb

Which suggests adding (or creating if it it doesn’t exist already) the following XML to the sgen.exe.config file;
<?xml version ="1.0"?>

<configuration>

    <startup useLegacyV2RuntimeActivationPolicy="true">

                <supportedRuntime version="v4.0" />

    </startup>   

</configuration>
For .Net 4.0 Projects, the sgen.exe.config file can be found at;
c:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools  (for x86 systems) 
c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools (for x64 systems)
For .Net 4.5 Projects, the sgen.exe.config file can be found at;
c:\Program Files\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools (for x86 systems) 
c:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools (for x64 systems)
Edit - 03-06-14:

For .Net 4.5.1 Projects, the sgen.exe.config file can be found at;
c:\Program Files\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.5.1 Tools (for x86 systems) 
c:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.5.1 Tools (for x64 systems)
Once I’d added the xml, the application built just fine.

The other alternative was to disable the option to Generate Serialization Assemblies in the offending project;

  • Project Settings for the offending Project
  • Compile Tab
  • Advance Compile Options Button
  • Set “Generate Serialization Assemblies” from “Auto” to “Off”

However, I recommend that you go with the XML option as suggested by Microsoft.

Thursday, 6 June 2013

WPF Binding Integer Validation with Null Values

I found a small hole in an application I am developing where a null value in a textbox bound to an integer value wouldn’t get validated.

It was slightly more complicated than that however. The xaml was as follows;

<TextBox Text="{Binding MyTextBoxText, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True, NotifyOnValidationError=True, Mode=TwoWay}"/>

Where my Validation was set for when the control lost focus.

When I added a new record, the value of the binding was set to null, this enforced by validation correctly. Same when I edited the text and left the control. However, if I edited the control when it had a value, say changing the value from a 2 to nothing, then the validation wouldn’t occur.

This was because the binding didn’t have a value for a null entry. Adding a TargetNullValue parameter to the binding and thus changing the binding to the following fixed the issue nicely;



<TextBox Text="{Binding TaskOrder, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True, NotifyOnValidationError=True, Mode=TwoWay, TargetNullValue=''}"/>

More information on the TargetNullValue Property can be found here;

http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.targetnullvalue.aspx

Tuesday, 21 May 2013

Binding the WPF WebBrowser Source Property

In an MVVM application I am currently creating, I had the need to embed the WPF WebBrowser control and quickly discovered that the Source Property is not a dependancy object, and so cannot be bound.

I quickly search around on StackOverflow.com and found a neat solution in c#;

http://stackoverflow.com/a/265648/1305169

The VB Version of which is;

   1: Namespace Helpers
   2:  
   3:     ''' <summary>
   4:     ''' Allows for the Source Property of the WebBrowser to be Bindable to the DataContext
   5:     ''' </summary>
   6:     ''' <remarks></remarks>
   7:     Public Class WebBrowserUtility
   8:         Private Sub New()
   9:         End Sub
  10:         Public Shared ReadOnly BindableSourceProperty As DependencyProperty = DependencyProperty.RegisterAttached("BindableSource", GetType(String), GetType(WebBrowserUtility), New UIPropertyMetadata(Nothing, AddressOf BindableSourcePropertyChanged))
  11:  
  12:         Public Shared Function GetBindableSource(obj As DependencyObject) As String
  13:             Return DirectCast(obj.GetValue(BindableSourceProperty), String)
  14:         End Function
  15:  
  16:         Public Shared Sub SetBindableSource(obj As DependencyObject, value As String)
  17:             obj.SetValue(BindableSourceProperty, value)
  18:         End Sub
  19:  
  20:         Public Shared Sub BindableSourcePropertyChanged(o As DependencyObject, e As DependencyPropertyChangedEventArgs)
  21:             Dim browser As WebBrowser = TryCast(o, WebBrowser)
  22:             If browser IsNot Nothing Then
  23:                 Dim uri As String = TryCast(e.NewValue, String)
  24:                 browser.Source = If(uri IsNot Nothing, New Uri(uri), Nothing)
  25:             End If
  26:         End Sub
  27:     End Class
  28:  
  29: End Namespace

You then use your new Bindable Property in the XAML as;



<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    xmlns:Helpers="clr-namespace:FrontEnd.Helpers"
    x:Class="frmKiosk"
    x:Name="Window"
    
    Width="1920" Height="1080" WindowStyle="None" WindowStartupLocation="CenterScreen" WindowState="Maximized" Background="#FF1327D0" Cursor="None">
 
    <WebBrowser x:Name="wbMain" Helpers:WebBrowserUtility.BindableSource="{Binding KioskWebAddress}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />
 
</Window>

Then simply creating a Property in the DataContext, and setting the source like;



KioskWebAddress = "c:/HTML/index.html"

Wednesday, 8 May 2013

Unable to open Database .SQL Files in Visual Studio 2012 Update 1 and onwards

This morning I attempted to open a .SQL file in my Visual Studio 2012 Update 2 installation, and was faced with the following Message Box;

enter image description here

Clicking the “Learn more…” link took me to a “Page Not Found” page, which wasn’t very handy.

A quick search on StackOverflow and I found;

http://stackoverflow.com/questions/15798422/what-about-sql-server-data-tools-for-vs2012-being-incompatible-with-sql-server-2

With a helpful answer by JorgenH directing me to update the SQL Server Data Tools found at this page;

http://msdn.microsoft.com/en-us/jj650015

I downloaded and installed the SQL Server Data Tools, shown at Step 2, from;

http://go.microsoft.com/fwlink/?LinkID=274984

Hey presto, problem sorted!

Tuesday, 26 March 2013

WPF - Programmatically Adding Buttons the MVVM Way

I recently came across a requirement to Programmatically Add Buttons to a WPF View in my MVVM based app. Obviously this is not entirely trivial as each Button must contain the correct Bindings to interact with the underlying ViewModel.

The way I tackled this was to use an ItemsControl, with a Canvas Control in the ItemsPanelTemplate. I then added a DataTemplate to the ItemTemplate, with our Button Template in this.

This Button Template contained the relevant binding to hook up the Command Property to my ViewModel.

For ease of use, I then created a Class which housed the various Properties I wanted to expose to each Button, such as it’s Position, CommandParameter and Content, and allowed me to return a Tickness for the Button Position.

From here I created an ObservableCollection of my new Button Class, and bound this to the ItemsControl.

The code can be seen below;

XAML:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Canvas x:Name="MyCanvas">
        <ItemsControl ItemsSource="{Binding MyButtons}" Height="237" Width="507">
            <ItemsControl.ItemsPanel >
                <ItemsPanelTemplate>
                    <Canvas IsItemsHost="true"></Canvas>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Margin="{Binding ControlMargin}" Content="{Binding Content}" Command="{Binding DataContext.ButtonCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" CommandParameter="{Binding ProductId}"></Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Canvas>
</Window>

FluidButton Class:



 

Public Class FluidButton
 
    Public Property Content As String
    Public Property LeftPos As Double
    Public Property TopPos As Double
    Public Property ProductId As Double
 
    ''' <summary>
    ''' Returns the Control Margin, using the Class Properties
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property ControlMargin As Thickness
        Get
            Return New Thickness With {.Left = LeftPos, .Top = TopPos}
        End Get
    End Property
    
End Class

Properties:



 

    ''' <summary>
    ''' Our Collection of Buttons or Products
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property MyButtons As ObservableCollection(Of FluidButton)
 
    ''' <summary>
    ''' Used to expose the Button Pressed Execute Commands to the UI for Binding
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks>Newed up in the Form Load Event</remarks>
    Public Property ButtonCommand As DelegateCommand
Adding Buttons:


 

MyButtons = New ObservableCollection(Of FluidButton)
 
MyButtons.Add(New FluidButton With {.Content = "Test1", .LeftPos = 0, .TopPos = 20, .ProductId = 1})
MyButtons.Add(New FluidButton With {.Content = "Test2", .LeftPos = 40, .TopPos = 30, .ProductId = 2})
MyButtons.Add(New FluidButton With {.Content = "Test3", .LeftPos = 80, .TopPos = 40, .ProductId = 3})
MyButtons.Add(New FluidButton With {.Content = "Test4", .LeftPos = 120, .TopPos = 50, .ProductId = 4})
MyButtons.Add(New FluidButton With {.Content = "Test5", .LeftPos = 160, .TopPos = 60, .ProductId = 5})

Monday, 7 January 2013

MVVM WPF Validating multiple items together

In an application I am developing, I required that two checkboxes be validated together, when either one of them were clicked. I also needed to only show the Validation error once in my Error Message Box.

To achieve this we first call the OnPropertyChanged routine, which in turn raises the PropertyChanged event, for each linked Property when any of the linked properties change.

For example;

Public Property Property1 As Boolean
    Get
        Return _Property1
    End Get
    Set(value As Boolean)
 
        If _Property1 <> value Then
 
            _Property1 = value
            OnPropertyChanged("Property1")
            OnPropertyChanged("Property2")
 
        End If
 
    End Set
End Property


For the Validation errors, I have employed a simple Key, Value Pair list to store all of the Validation Error Results. Thus, I simply check to see if the other Property has Registered an Error, and remove it if so;



 
        ''' <summary>
        ''' Validates the Current Item
        ''' </summary>
        ''' <param name="ColumnName"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Overrides Function ValidateItemValue(ColumnName As String) As String
            Dim strResult As String = ""
 
            Select Case ColumnName
 
                Case "Property1"
 
                    If Property1 = False And Property2 = False Then
 
                        strResult = "Please select either Property1, Propert2 or Both!"
 
                        If Me.lstErrors.ContainsKey("Property2") = True Then
 
                            Me.lstErrors.Remove("Property2")
 
                        End If
 
                    End If
 
                Case "Property2"
 
                    If Property1 = False And Property2 = False Then
 
                        strResult = "Please select either Property1, Property2 or Both!"
 
                        If Me.lstErrors.ContainsKey("Property1") = True Then
 
                            Me.lstErrors.Remove("Property1")
 
                        End If
 
                    End If
 
 
            End Select
 
            SortErrorList(ColumnName, strResult)        ' Add or Remove an Error Item
 
            Return strResult
 
        End Function