Wednesday, November 30, 2016

Detecting WPF controls' Validation Errors when saving

Detecting WPF Validation Errors

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace erpcli.Lib
{
    static class Validator
    {
        // LINQ version
        public static bool IsValid(DependencyObject obj)
        {
            // The dependency object is valid if it has no errors and all
            // of its children (that are dependency objects) are error-free.
            // Reference: http://stackoverflow.com/questions/127477/detecting-wpf-validation-errors
            return !Validation.GetHasError(obj) &&
            LogicalTreeHelper.GetChildren(obj)
            .OfType<DependencyObject>()
            .All(IsValid);
        }

        /*
        public static bool IsValid(DependencyObject parent)
        {
            if (Validation.GetHasError(parent))
                return false;

            // Validate all the bindings on the children
            for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (!IsValid(child)) { return false; }
            }

            return true;
        }
        */
    }
}

Usage:

private void saveButton_Click(object sender, RoutedEventArgs e)
{

  if (Validator.IsValid(this.MyStackPanel)) // is valid
   {

    ....
   }
}

Reference:

http://stackoverflow.com/questions/127477/detecting-wpf-validation-errors

Wednesday, November 23, 2016

Center the window in WPF

Center the window in WPF

<Window WindowStartupLocation="CenterScreen"></Window>

Or

<Window WindowStartupLocation="CenterOwner"></Window>

Maximize the window in WPF

Maximize the window in WPF

<Window WindowState="Maximized">
</Window>

Disable edit function in DataGrid in WPF

<DataGrid IsReadOnly="True">
</DataGrid>

Prevent mutiple row selection (select single row) in WPF DataGrid

Prevent mutiple row selection (select single row) in WPF DataGrid

<DataGrid SelectionMode="Single" SelectionUnit="FullRow">
</DataGrid>

Monday, November 21, 2016

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=12.0.0.0

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=12.0.0.0

Install the follow two componments:

- SQL Server System CLR Types for SQL Server 2014

https://www.microsoft.com/en-ca/download/details.aspx?id=42295

- MICROSOFT® REPORT VIEWER 2015 RUNTIME

https://www.microsoft.com/en-ca/download/details.aspx?id=45496

Print line number for debugging in Go

Print line number for debugging in Go

Method 1:

// to change the flags on the default logger
log.SetFlags(log.LstdFlags | log.Lshortfile)

Method 2:

package main

import (
        "log"
        "runtime"
)

func MyFunc() {
        FancyHandleError()
}

func FancyHandleError() {
        // notice that we're using 1, so it will actually log the where
        // the error happened, 0 = this function, we don't want that.
        pc, fn, line, _ := runtime.Caller(1)
        log.Printf("[error] in %s[%s:%d]", runtime.FuncForPC(pc).Name(), fn, line)
}

func main() {
        MyFunc()
}

Method 3:

package main

import (
        //"log"
        //"runtime"
        "runtime/debug"
)

func MyFunc() {
        FancyHandleError()
}

func FancyHandleError() {
        debug.PrintStack()
}

func main() {
        MyFunc()
}

Reference:

https://golang.org/pkg/log/#pkg-constants

https://golang.org/pkg/runtime/debug/#PrintStack

http://stackoverflow.com/questions/24809287/how-do-you-get-a-golang-program-to-print-the-line-number-of-the-error-it-just-ca

Friday, November 18, 2016

Change WPF ComboBox dropdown width in C#

 <ComboBox Width="50" Height="40" MaxDropDownHeight="160">
        <ComboBox.ItemContainerStyle>
            <Style TargetType="ComboBoxItem">
                <Setter Property="Width" Value="60"/>
            </Style>
        </ComboBox.ItemContainerStyle>
        <ComboBoxItem Content="this is Item One "/>
        <ComboBoxItem Content="this is Item "/>
        <ComboBoxItem Content="this is "/>
        <ComboBoxItem Content="this "/>
    </ComboBox>

Wednesday, November 16, 2016

RDLC reports could not be find in the Visual Studio designer

I solved by doing the following steps.

1. Open Control Panel > Programs > Programs and Features, and select the entry for your version of Microsoft Visual Studio 2015. In our case, it was Microsoft Visual Studio Enterprise 2015.

2. Click the "Change" button on the top bar above the program list.

3. After the splash screen, a window will open. Press the "Modify" button.

4. Select Windows and Web Development > Microsoft SQL Server Data Tools, and check the box next to it.

5. Press the "Update" button on the lower-right hand side of the window.

6. Once the installation is complete, open your version of Visual Studio. After the new .dll files are loaded, Reporting functionality should be reimplemented, and you should be able to access all related forms, controls, and objects.

Reference:

https://forums.asp.net/t/2068802.aspx?In+Visual+Studio+Enterprise+2015+I+cannot+find+the+designer+for+RDLC+reports+anymore

ComboBox is extremely slow issue

Use VirtualizingStackPanel to improve performance.

<ComboBox Name="test" ItemsSource="{Binding}">
    <ComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </ComboBox.ItemsPanel>
</ComboBox>

Remove items from List

using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List<Dealer> myList = new List<Dealer> {
                new Dealer() {Text = "Dealer A", IsSelected = false },
                new Dealer() {Text = "Dealer B", IsSelected = true },
                new Dealer() {Text = "Dealer C", IsSelected = false },
            };

            myList.RemoveAll(x => x.IsSelected == true);

            foreach (Dealer d in myList)
            {
                Debug.WriteLine("ITem: " + d.Text);
            }
        }
    }

    class Dealer
    {
        public string Text { get; set; }
        public bool IsSelected { get; set; }
    }
}

Saturday, November 12, 2016

Convert comma separated string of ints to int array

Convert comma separated string of ints to int array

string sNumbers = "1,2,3,4,5";

If you want to throw an exception if a number couldn't be parsed, you can do it much more simply using LINQ:

(str ?? "").Split(',').Select<string, int>(int.Parse);

If you don't want to have the current error handling behaviour, it's really easy:

text.Split(',').Select(x => int.Parse(x));

return a list instead of int array:

var numbers = sNumbers.Split(',').Select(Int32.Parse).ToList();

List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );

// Uses Linq
var numbers = Array.ConvertAll(sNumbers.Split(','), int.Parse).ToList();

Reference:

http://stackoverflow.com/questions/1763613/convert-comma-separated-string-of-ints-to-int-array

http://stackoverflow.com/questions/911717/split-string-convert-tolistint-in-one-line