How to create and use a custom CultureInfo in WPF? - wpf

I need a method to display a WPF form with non-standard CultureInfo, which is customizable at runtime. E.g. the customer wants to read dates in "de-DE", but currencies in "en-US". The App should be able to display every currency in the world. Dates and Numberformats are almost "en-US" and "de-DE"
I already tried the "CultureAndRegionInfoBuilder", but it requires admin-rights for the application to register the created culture and it will not update the UI if I use the same name for that culture (e.g. "x-myapp-custom")
In "Application.xaml.vb" at startup:
Private Sub CreateCustomCulture(thisCultureName As String)
Dim myCultureBuilder = New CultureAndRegionInfoBuilder(thisCultureName, CultureAndRegionModifiers.Neutral)
myCultureBuilder.LoadDataFromRegionInfo(RegionInfo.CurrentRegion) 'DE
myCultureBuilder.LoadDataFromCultureInfo(Thread.CurrentThread.CurrentCulture) 'de-DE
Try
myCultureBuilder.Register()
Catch ex As Exception
Debug.WriteLine(ex.ToString)
End Try
End Sub
This is working fine, even if it requires to "run as admin" to register the CultureInfo
In "testwindow.xaml.vb":
Private Sub Testwindow_Loaded(sender As Object, e As RoutedEventArgs)
Me.Language = Markup.XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentUICulture.Name)
End Sub
This is also working fine.
But when I try to change Thread.CurrentThread.CurrentUICulture.NumberFormat.CurrencySymbol = "$" the setting is stored in the CultureInfo, but not reflected the WPF form. Even if I un- and re-register the CultureInfo and set the WPF language again.
I expect to have my bound Textboxes ({Binding TestCurrency, ElementName=testwindow, StringFormat=\{0:C2\}}) to show in "en-US" style (or at least with a dollar-sign), but it keeps showing in "de-DE".

Related

Tying ComboBox/NumericUpDown selections to an array?

I'm working on a VB project that has a lot of comboboxes and numericupdown items.
Lets say we have ComboBox1, 2, 3, 4, and 5; and we have NumericUpDown1, 2, 3, 4, 5.
When the user clicks the "Save" button, I want to save all of their selected combobox items and numericupdown numbers to a CSV file. Is there an elegant/automatic way to tie all of the .SelectedIndex and .Value for these items to an array so I can easily write the array out to a CSV?
The only way I know to do this so far is to manually associate each one with an array position:
Arr(0) = ComboBox1.SelectedIndex
Arr(1) = ComboBox2.SelectedIndex
...
Arr(5) = NumericUpDown1.Value
Arr(6) = NumericUpDown2.Value
...
etc.
This wouldnt be too bad, except I have a LOT of these items, and writing a line for each one seems silly. I'm new to VB, so this might be an obvious solution to some. Any ideas?
Having them bound to an array would be really handy because I also allow the user to Load a CSV file, which I would like to automatically populate the ComboBoxes and NumericUpDowns from the CSV values. The only way I know to do this is to manually move each array item to the respective combobox/numeric item when they click the Load file button:
ComboBox1.SelectedIndex = Arr(0)
ComboBox2.SelectedIndex = Arr(1)
...
NumericUpDown1.Value = Arr(5)
NumericUpDown2.Value = Arr(6)
...
etc.
Edit: Here is some application info as requested...
The CSV file that can be saved/loaded looks like this:
#"Device Info","123456","asdfgh","0000","1.0x","1"
000F,0000,0032,0000,00C8,0001,0078,0101,0000,0001,0000,0001
010F,0078,0000,0103,0001,0000,000A,0005,0007,0006,0000
0001,000A,000A,000A,000A,0005,0005,0005,0002
...etc
The header line just has serial number, version, and other misc info; it is automatically generated by the target device. All of the other lines are configuration setpoints that the target device reads in and automatically configures itself. I'm writing this PC program to be able to edit (and create from scratch) these configuration CSV files with a nice GUI interface. Each item is tied to a specific setpoint, such as 000F = Language, 0032 = System Frequency, 00C8 = System Voltage, etc. The easiest way I saw to make this configuration program was to use numeric entry and drop-down comboboxes that the user can select what they want. Each NUD and CBOX equates to one of the CSV file data fields.
You can use Controls.Find() to get a reference to the desired control based on an index value. Here's a quick example to demonstrate what I mean:
For i As Integer = 1 To 30
Dim matches() As Control = Me.Controls.Find("NumericUpDown" & i, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is NumericUpDown Then
DirectCast(matches(0), NumericUpDown).Value = i
End If
Next
You can incorporate code like that into the load/save routines.
I would use binary serialization. This eliminates the need to format strings or xml when saving control properties. Similar to Plutonix's solution, it only works on certain types of control. However, it can be modified to work on any type of control - but only supports a single property to be loaded for each control. It will work on all controls of type X instead of controls named xName. You can add further restrictions by grouping the controls to be serialized in a panel or other means.
Make a new Form called Form1. Add some NumericUpDowns, TextBoxes, and ComboBoxes. Put some values in the ComboBoxes at design time, otherwise calling loadState() in Form_Load will be meaningless. However, loadState() can be called whenever (i.e. after the comboboxes have been populated).
You will need to import these two namespaces:
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
In your class:
Private Shared stateFileName As String = "SavedState.bin"
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
saveState(Me)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
loadState(Me)
End Sub
And these are the methods you will use to save and load states. The save state method:
Private Shared Sub saveState(instance As Form)
Dim controlProperties As Dictionary(Of String, Object) =
instance.Controls.OfType(Of Control).ToDictionary(Of String, Object)(
Function(c) c.Name,
Function(c)
' You can support different types of controls here too
If TypeOf c Is NumericUpDown Then
Return CType(c, NumericUpDown).Value
ElseIf TypeOf c Is ComboBox Then
Return CType(c, ComboBox).SelectedIndex
Else
' All other controls get their text property saved
' .Text is a property of Control
Return c.Text
End If
End Function)
Using myFileStream As Stream = File.Create(stateFileName)
Dim serializer As New BinaryFormatter
serializer.Serialize(myFileStream, controlProperties)
End Using
End Sub
The load state method:
Private Shared Sub loadState(instance As Form)
If File.Exists(stateFileName) Then
Using myFileStream As Stream = File.OpenRead(stateFileName)
Dim deserializer As New BinaryFormatter()
Dim controlProperties = CType(deserializer.Deserialize(myFileStream), Dictionary(Of String, Object))
For Each c As Control In instance.Controls
If controlProperties.ContainsKey(c.Name) Then
' You can support different types of controls here too
If TypeOf c Is NumericUpDown Then
CType(c, NumericUpDown).Value = CDec(controlProperties(c.Name))
ElseIf TypeOf c Is ComboBox Then
CType(c, ComboBox).SelectedIndex = CInt(controlProperties(c.Name))
Else
c.Text = controlProperties(c.Name).ToString()
End If
End If
Next
End Using
End If
End Sub
You should add exception handling, and note that a binary file is not meant to be edited by a human without the assistance of a machine.

Data Validation with MVVM-Light WPF and Linq to Entity Framework

I think I have read every article google returns when I search wpf mvvm-light data validation and I dont know which way to go. I am aware of josh smith, Karl Shifflett's, and MVVM LIGHT's own demo techniques for data validation. What I see is that most validation requires me to fully "re-abstract" my model in my view model. Meaning that I have to create a property in my viewmodel for each property of my model that I want to validate (and in some cases convert all these into string values for binding/validation). This seems like a lot or redundancy when all I want to do is mark most fields as required.
I am using LINQ to entity framework(with self tracking) for my model classes which come from a SQL server DB. As a result I would prefer to keep my business data validation/rules within my viewmodels. I write a simple service interface to get the data from the model and pass it to my viewmodel.
Most of the examples I can find are from as far back as 2008 (ie josh smith). Are these techniques still valid or are there more up to date best practices for mvvm data validation with .NET 4.5 etc.
So I am asking:
1) What methods do you suggest I use
2) What methods work best in a LINQ to EF with MVVM-Light Environment.
3) EDIT: I want to provide feedback to user as they enter data, not just when they submit form
thanks
The way I do this (not necessarily correct) is to do my validation in the ViewModel (where the CRUD operations typically take place), then if there are validation errors, abort saving/adding any data and use Messenger.Default.Send to send a custom message type to my view. Then I alert the user via a DialogBox or otherwise.
I've experimented with Binding ValidationRules in the past but found by far the most reliable and consistent method to be simple if statements.
I eventually ended up using the following. I changed my model to use LINQ to self tracking entities (see this article for info about STE http://msdn.microsoft.com/en-us/library/vstudio/ff407090%28v=vs.100%29.aspx).
LINQ to STE creates an OnPropertyChanged event that implements the iNotifyPropertyChanged interface.
I just created a public partial class for the matching model object (linq entity generated code) I wanted and added an event handler for the OnPropertyChanged event. I then used the IDataErrorInfo interface to validate and throw errors as I needed. This allows me to validate the fields as they change which gets reflected to the user. This also allows you to perform more advanced validation logic that may need to requery the database (i.e. to look for if a username is already used etc.) or throw a dialog box
Also, having the data validation in the model allows me to still have validation if i perform direct "batch" operations that bypass the UI.
I then used an HasErrors and HasChanges property and used them to create a Boolean value that gets attached to the relay commands, disabling the crud command buttons if errors are present.
I will post some simple code to outline what I just described, comment if you want more detail.
Here is the Entity Framework extension of the model class:
Imports System.ComponentModel
Partial Public Class client
Implements IDataErrorInfo
#Region "Properties / Declarations"
'Collection / error description
Private m_validationErrors As New Dictionary(Of String, String)
Private _HasChanges As Boolean = False
''Marks object as dirty, requires saving
Public Property HasChanges() As Boolean
Get
Return _HasChanges
End Get
Set(value As Boolean)
If Not Equals(_HasChanges, value) Then
_HasChanges = value
OnPropertyChanged("HasChanges")
End If
End Set
End Property
'Extends the class with a property that determines
'if the instance has validation errors
Public ReadOnly Property HasErrors() As Boolean
Get
Return m_validationErrors.Count > 0
End Get
End Property
#End Region
#Region "Base Error Objects"
'Returns an error message
'In this case it is a general message, which is
'returned if the list contains elements of errors
Public ReadOnly Property [Error] As String Implements System.ComponentModel.IDataErrorInfo.Error
Get
If m_validationErrors.Count > 0 Then
Return "Client data is invalid"
Else
Return Nothing
End If
End Get
End Property
Default Public ReadOnly Property Item(ByVal columnName As String) As String Implements System.ComponentModel.IDataErrorInfo.Item
Get
If m_validationErrors.ContainsKey(columnName) Then
Return m_validationErrors(columnName).ToString
Else
Return Nothing
End If
End Get
End Property
#End Region
#Region "Base Error Methods"
'Adds an error to the collection, if not already present
'with the same key
Private Sub AddError(ByVal columnName As String, ByVal msg As String)
If Not m_validationErrors.ContainsKey(columnName) Then
m_validationErrors.Add(columnName, msg)
End If
End Sub
'Removes an error from the collection, if present
Private Sub RemoveError(ByVal columnName As String)
If m_validationErrors.ContainsKey(columnName) Then
m_validationErrors.Remove(columnName)
End If
End Sub
#End Region
Public Sub New()
Me.HasChanges = False
End Sub
#Region "Data Validation Methods"
''handles event and calls function that does the actual validation so that it can be called explicitly for batch processes
Private Sub ValidateProperty(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) Handles Me.PropertyChanged
If e.PropertyName = "HasChanges" Then
Exit Sub
End If
IsPropertyValid(e.PropertyName)
HasChanges = True
End Sub
Public Function IsPropertyValid(sProperty As String) As Boolean
Select Case sProperty
''add validation by column name here
Case "chrLast"
If Me.chrLast.Length < 4 Then
Me.AddError("chrLast", "The last name is too short")
Return True
Else
Me.RemoveError("chrLast")
Return False
End If
Case Else
Return False
End Select
End Function
#End Region
End Class
then in the view model I included the following code to bind thecommand and evaluate whether or not it can be executed.
Public ReadOnly Property SaveCommand() As RelayCommand
Get
If _SaveCommand Is Nothing Then
_SaveCommand = New RelayCommand(AddressOf SaveExecute, AddressOf CanSaveExecute)
End If
Return _SaveCommand
End Get
End Property
Private Function CanSaveExecute() As Boolean
Try
If Selection.HasErrors = False And Selection.HasChanges = True Then
Return True
Else
Return False
End If
Catch ex As Exception
Return False
End Try
End Function
Private Sub SaveExecute()
''this is my LINQ to Self Tracking Entities DataContext
FTC_Context.SaveChanges()
End Sub
the following is how I bound my button (has custom styling in WPF)
<Button Content="" Height="40" Style="{DynamicResource ButtonAdd}" Command="{Binding SaveCommand}" Width="40" Cursor="Hand" ToolTip="Save Changes" Margin="0,0,10,10"/>
so, when there are no validation errors and the current client record "isDirty" the save button automatically becomes enabled, and disabled if any of those two conditions fail. This way I now have a simple way of validating any type of column/data I want for the entity, and I can provide user feedback as they enter data in the form, and only enable CRUD command buttons once all my "conditions" have been met.
This was quite a battle to figure out.

How to Implement Entity Framework on this example?

I have been working thru this WPF example and am trying to hook it up to my database using Entity Framework but am confused on how to do this. Can someone please offer some guidance on how this would be done?
The code has the following in CustomerRepository.cs
static List<Customer> LoadCustomers(string customerDataFile)
{
// In a real application, the data would come from an external source,
// but for this demo let's keep things simple and use a resource file.
using (Stream stream = GetResourceStream(customerDataFile))
using (XmlReader xmlRdr = new XmlTextReader(stream))
return
(from customerElem in XDocument.Load(xmlRdr).Element("customers").Elements("customer")
select Customer.CreateCustomer(
(double)customerElem.Attribute("totalSales"),
(string)customerElem.Attribute("firstName"),
(string)customerElem.Attribute("lastName"),
(bool)customerElem.Attribute("isCompany"),
(string)customerElem.Attribute("email")
)).ToList();
}
which is where I assume the hook to the database would happen but not sure how. I can create the Model.edmx file to connect to the database but not sure how to physically get the list of customers from the database.
Also, this example uses a List of Customers but most examples I have gone through use ObservableCollection for this type of data. Is one preferable over the other and why?
TIA,
Brian Enderle
My MVVM/EF projects typically load entities directly into the ViewModels or Into light collections in the view models. I don't create any kind of custom repository to sit between them.
Generally my ViewModels do one of two things,
Retrieves data on instancing
Takes an entity as a constructor argument.
When I retrieve data on instance, I generally use a background worker class, which queries the context, puts the results in a list, and passes the list out. The Work Completed method then puts the entities into viewmodels and puts the ViewModels in a ObservableCollection.
Similar to this:
Private WithEvents GetProjectsBackgroundWorker As BackgroundWorker
Private _Projects As New ObservableCollection(Of ProjectViewModel)
Public Sub New()
GetProjectsBackgroundWorker = New BackgroundWorker
GetProjectsBackgroundWorker.RunWorkerAsync()
End Sub
Public Property Projects() As ObservableCollection(Of ProjectViewModel)
Get
Return _Projects
End Get
Set(ByVal value As ObservableCollection(Of ProjectViewModel))
_Projects = value
End Set
End Property
#Region " GetProjects"
Private Sub GetProjectsBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles GetProjectsBackgroundWorker.DoWork
Dim results = From proj As Project In Context.Projects Where proj.flgActive = True And proj.flgReview = True Select proj
Dim ProjList As New List(Of Project)(results)
e.Result = ProjList
End Sub
Private Sub GetProjectsBackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles GetProjectsBackgroundWorker.RunWorkerCompleted
If e.Error Is Nothing Then
For Each p As Project In e.Result
Projects.Add(New ProjectViewModel(p, Context))
Next
Else
End If
End Sub
#End Region
In ViewModels that take an entity as an argument, they often take a context as argument, especially if something is a short time-span operation. Otherwise I detach entities from the context in the even something goes hay-wire with the database or the connection is lost or something.
To answer your second question, ObservableCollections are Enumerable collections that have collection change notification implemented. The collection will notify the UI when a new item is added/removed/moved. Typically any time I have entities that are going to be viewed or displayed in the UI, I host them in an Observable Collection. Otherwise I use something simpler, a List normally.

Infragistics UltraWinGrid EmptyDataText Equivalent?

We're using Infragistics UltraWinGrid as a base class for customized controls. One of the projects that will use this control to display search results has a requirement to display a user friendly message when no matches are located.
We'd like to encapsulate that functionality into the derived control - so no customization beyond setting the message to display is required by the programmer who uses the control. This would have to be done in generic fashion - one size fits all datasets.
Is there allowance in the UltraWinGrid for this type of usage already? If so, where would I find it hidden. :-)
If this functionality needs to be coded, I can think of an algorithm which would add a blank record to whatever recordset was set and place that into the grid. In your opinion, is this the best way to handle the solution?
I don't know if this will help, but here's to finishing up the thread. I didn't find a built in way, so I solved this problem as follows: In my class which inherits UltraGrid
Public Class MyGridPlain
Inherits Infragistics.Win.UltraWinGrid.UltraGrid
I added two properties, one to specify what the developer wants to say in the empty data case, and another to enable the developer to place their message where they want it
Private mEmptyDataText As String = String.Empty
Private mEmptyDataTextLocation As Point = New Point(30, 30)Public Shadows Property EmptyDataTextLocation() As Point
Get
Return mEmptyDataTextLocation
End Get
Set(ByVal value As Point)
mEmptyDataTextLocation = value
setEmptyMessageIfRequired()
End Set
End Property
Public Shadows Property EmptyDataText() As String
Get
Return mEmptyDataText
End Get
Set(ByVal value As String)
mEmptyDataText = value
setEmptyMessageIfRequired()
End Set
End Property
I added a method which will check for empty data and set the message if so. And another method which will remove the existing empty message.
Private Sub setEmptyMessageIfRequired()
removeExistingEmptyData()
'if there are no rows, and if there is an EmptyDataText message, display it now.
If EmptyDataText.Length > 0 AndAlso Rows.Count = 0 Then
Dim lbl As Label = New Label(EmptyDataText)
lbl.Name = "EmptyDataLabel"
lbl.Size = New Size(Width, 25)
lbl.Location = EmptyDataTextLocation
ControlUIElement.Control.Controls.Add(lbl)
End If
End SubPrivate Sub removeExistingEmptyData()
'any previous empty data messages?
Dim lblempty() As Control = Controls.Find("EmptyDataLabel", True)
If lblempty.Length > 0 Then
Controls.Remove(lblempty(0))
End If
End Sub
Last - I added a check for empty data to the grid's InitializeLayout event.
Private Sub grid_InitializeLayout(ByVal sender As Object, _
ByVal e As Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs) _
Handles MyBase.InitializeLayout
setEmptyMessageIfRequired()
End Sub

SubSonic and a dateTimePicker control on a Windows Form

Question #1: Latest working Version
I'm currently using SubSonic 2.1 built 491.
Is there a later build? Where can I get it?
I know 2.2 was released but it doesn't come with a Setup and I wouldn't know how to modify the App.Config/Web.Config to work with it.
Question #2: Issue with dateTimePicker control on Windows Form.
I keep getting System.FormatException trying to retrieve data From SubSonic to that control or saving data from that control to the Database through SubSonic.
For example, if I want to save the Time only, I can use the .Text property. To save the Date, I need to use the .Value property of the control.
I've tried all sorts of conversion such as Convert.ToDateTime(dateTimePicker.Value.ToString()) and others but I can't find a consistent pattern that would not throw an exception. Any help on this would be greatly appreciated.
Re Question 1 - I don't think any app.config / web.config change is required between SS2.1 and 2.2
For Question 2 - are you using the new data types in MSSQL2008 by any chance? If so, SS2.2 doesn't seem to handle them properly yet.
Just stumbled upon your post.
I'm not sure if It was a FormatException, but I got a Exception with a databound DateTimePicker, too.
The problem is that
DateTimePicker.MinimumDateTime = #1/1/1753#
while
DateTime.MinValue = #1/1/0001#
New DateTime = #1/1#0001#
So if bind a property to a DataGridView that returns a DateTime value earlier than #1/1/1753# or later then #12/31/9998# ( DateTimePicker.MaximumDateTime ) you get an exception.
I solved this with my own inherited DateTimePicker (sorry, but it's written in vb)
To use it you can just bind your Subsonic object to the value property. But you have to set the ShowCheckBox property to true and bind a bool value to the CheckedValue property (to indicate that the date is set) which is persisted in your db, too.
Now If an empty date is returned, the date is set to Now and the checkedValue to false, leading to a disabled DateTimePicker.
If you check the Checkbox or choose a date with the calender) the checkbox is set to true and the Checkbox is checked.
Attention: Do not bind the Checked property directly, bind the CheckedValue property.
Imports System.ComponentModel
Public Class MyDateTimePicker
Inherits System.Windows.Forms.DateTimePicker
<Bindable(True)> _
Public Overloads Property Value() As DateTime
Get
If Not MyBase.Checked And (MyBase.Value < DateTimePicker.MinimumDateTime Or MyBase.Value > DateTimePicker.MaximumDateTime) Then
Return DateTime.Now
Else
Return MyBase.Value
End If
End Get
Set(ByVal value As DateTime)
If ((value < DateTimePicker.MinimumDateTime Or value > DateTimePicker.MaximumDateTime) Or value = #1/1/1900#) Then
MyBase.Value = DateTime.Now
MyBase.Checked = False
Else
MyBase.Value = value
End If
End Set
End Property
Private _CheckedValue As Boolean
<Bindable(True)> _
Public Property CheckedValue() As Boolean
Get
Return _CheckedValue
End Get
Set(ByVal value As Boolean)
_CheckedValue = value
End Set
End Property
Protected Overrides Sub OnMouseUp(ByVal e As System.Windows.Forms.MouseEventArgs)
MyBase.OnMouseUp(e)
RefreshCheckedValue()
End Sub
Protected Overrides Sub OnKeyUp(ByVal e As System.Windows.Forms.KeyEventArgs)
MyBase.OnKeyDown(e)
RefreshCheckedValue()
End Sub
Private Sub RefreshCheckedValue()
CheckedValue = Me.Checked
If Not Me.DataBindings("CheckedValue") Is Nothing Then
Me.DataBindings("CheckedValue").WriteValue()
End If
End Sub
Protected Overrides Sub OnBindingContextChanged(ByVal e As System.EventArgs)
MyBase.OnBindingContextChanged(e)
Static checkedInitialized As Boolean
If Not checkedInitialized AndAlso Not Me.DataBindings("CheckedValue") Is Nothing Then
Me.Checked = Me.CheckedValue
checkedInitialized = True
End If
End Sub
End Class

Resources