Wednesday, December 28, 2016

The secondary network interface did not show up

The secondary network interface did not show up

Find out the subnet mask:

/bin/ipcalc --netmask 172.31.26.153/20

Initialize the secondary:

# ifconfig eth1 172.31.26.153 netmask 255.255.240.0

Edit interfaces setting:

# vi /etc/network/interfaces

# The primary network interface
auto eth0
iface eth0 inet dhcp
post-up ip route add default via 10.0.0.1 dev eth0 tab 1
post-up ip rule add from 10.0.0.170/32 tab 1 priority 500

auto eth1
iface eth1 inet dhcp
post-up ip route add default via 10.0.0.1 dev eth1 tab 2
post-up ip rule add from 10.0.0.190/32 tab 2 priority 600

Restart network:

# /etc/init.d/networking restart

Reference:

http://work.allaboutken.com/node/21

Sunday, December 25, 2016

How to find which Linux distribution is being used

# awk -F '=' '/^ID=/ {print $2}' /etc/os-release | tr -d '"'

or

# awk -F '=' '/^ID=/ {print $2}' /etc/os-release | sed -e 's/"//g'

or

# awk -F '=' '/^ID=/ {print $2}' /etc/os-release | awk -F'"' '{print $2}'





Install Drupal 8

Install Drupal 8

# export DRUPAL_VERSION=8.2.4

Note: another way: DRUPAL_VERSION=8.2.4; export DRUPAL_VERSION

# export DRUPAL_MD5=288aa9978b5027e26f20df93b6295f6c

Note: another way: DRUPAL_MD5=288aa9978b5027e26f20df93b6295f6c; export DRUPAL_MD5

# curl -fSL "https://ftp.drupal.org/files/projects/drupal-${DRUPAL_VERSION}.tar.gz" -o drupal.tar.gz \
&& echo "${DRUPAL_MD5} *drupal.tar.gz" | md5sum -c - \
&& tar -xz --strip-components=1 -f drupal.tar.gz \
&& rm drupal.tar.gz \
&& chown -R www-data:www-data sites modules themes

# unset DRUPAL_VERSION
# unset DRUPAL_MD5
# env

Wednesday, December 21, 2016

Boot to Advanced Startup Options from Command on Windows 10

Win + R

shutdown /r /o /f /t 00

Tuesday, December 20, 2016

Remove all dangling (orphan) images

Remove all dangling (orphan) images:

# docker rmi $(docker images -q -f dangling=true)

Remove all dangling (orphan) volumes

Remove all dangling (orphan) volumes:

# docker volume ls -q -f dangling=true
# docker volume rm $(docker volume ls -q -f dangling=true)

Remove all your stopped containers

Remove all your stopped containers:

# docker rm -v $(docker ps -aq -f status=exited)

Note: -v argument will remove the volumes associated with the container that aren't referenced by other containers.

Stop all running containers

Stop all running containers:

# docker stop $(docker ps -q)

Saturday, December 3, 2016

LINQ LIMIT

LINQ LIMIT

optArr.Where(d => d.IsSelected == true).Select(d => d.ID).Skip(0).Take(1).FirstOrDefault();

Friday, December 2, 2016

listen to MouseOver event

listen to MouseOver event

public MainWindow()
{
    InitializeComponent();

    StackPanel stackpanel = new StackPanel(); 
    stackpanel.MouseEnter += new MouseEventHandler(stackpanel_MouseEnter);
    stackpanel.MouseLeave += new MouseEventHandler(stackpanel_MouseLeave);
}

void stackpanel_MouseLeave(object sender, MouseEventArgs e)
{
    StackPanel stackpanel = (StackPanel)sender;
    stackpanel.Background = Brushes.Transparent;
}

void stackpanel_MouseEnter(object sender, MouseEventArgs e)
{
    StackPanel stackpanel = (StackPanel)sender;
    stackpanel.Background = Brushes.LightGray;
}

Reference:

http://stackoverflow.com/questions/10184551/stackpanel-highlight-on-mouse-over-from-code-behind

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

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

Friday, October 28, 2016

How to Turn On or Off the Xbox Game Bar in Windows 10

How to Turn On or Off the Xbox Game Bar in Windows 10

The .reg files below will modify the DWORDs in the registry keys below.

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\GameDVR

AppCaptureEnabled DWORD

0 = Off
1 = On

HKEY_CURRENT_USER\System\GameConfigStore

GameDVR_Enabled DWORD

0 = Off
1 = On

Reference:

http://www.tenforums.com/tutorials/8637-game-bar-turn-off-windows-10-a.html

Wednesday, October 26, 2016

Get JSON data through ajax

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Windows.Input;

namespace AutoCompleteSample
{
    class StdLib
    {
        public static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public static async Task<string> AjaxV1(string uri)
        {
            try
            {
                // TODO: this is a temporary remove SSL ceritficate check solution. Please comment out this line in production.
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

                var httpClient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate });
                httpClient .DefaultRequestHeaders.Accept.Clear();
                httpClient .DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var response = await httpClient.GetAsync(uri);

                // will throw an exception if not successful
                response.EnsureSuccessStatusCode();

                //return await Task.Run(() => JsonObject.Parse(content));
                //return await Task.Run(() => content);
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return "{Status:false}";
            }
        }

        public static async Task<string> AjaxV2(string uri)
        {
            try
            {
                // TODO: this is a temporary remove SSL ceritficate check solution. Please comment out this line in production.
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

                var httpClient = new HttpClient();
                return await httpClient.GetStringAsync(uri);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return "{Status:false}";
            }
        }

        public static char ConvertKeyToChar(Key key)
        {
            return Convert.ToChar(KeyInterop.VirtualKeyFromKey(key));
        }

        public static string GetWebSrvURL()
        {
            string url = "";
            url += ConfigurationManager.AppSettings["WebSrvProtocol"] + "://" + ConfigurationManager.AppSettings["WebSrvDomain"] + ":" + ConfigurationManager.AppSettings["WebSrvPort"];
            return url;
        }
    }
}

Tuesday, October 25, 2016

using WPF Toolkit autocomplete

To install WPF Toolkit, run the following command in the Package Manager Console:

PM> Install-Package WPFToolkit

or

PM> Install-Package DotNetProjects.Wpf.Toolkit

MainWindow.xaml:

<Window x:Class="WpfApplication1.MainWindow"
        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"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        xmlns:toolkit1="http://schemas.microsoft.com/wpf/2008/toolkit"
        xmlns:toolkit2="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <toolkit1:DatePicker Width="100" Height="32" Margin="10,38,407,249"></toolkit1:DatePicker>
        <toolkit2:AutoCompleteBox x:Name="MyAC" Margin="10,75,0,0"
                         VerticalAlignment="Top"
                         HorizontalAlignment="Left"
                         Width="150"
                         ItemsSource="{Binding Collection}"
                         Height="23"
                         ValueMemberPath="DealerName"
                         SelectionChanged="MyAC_SelectionChanged"
                         >
                            <toolkit2:AutoCompleteBox.ItemTemplate>
                                <DataTemplate >
                                    <StackPanel Orientation="Horizontal" Width="300">
                                        <Label Content="{Binding IDDealer}" Width="100" Background="Black" Foreground="White"/>
                                        <Label Content="{Binding DealerName}" FontStyle="Italic" Foreground="DarkGray" />
                                    </StackPanel>
                                </DataTemplate>
                            </toolkit2:AutoCompleteBox.ItemTemplate>
        </toolkit2:AutoCompleteBox>
        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="301,75,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
    </Grid>
</Window>

Note: if you are using "DotNetProjects.Wpf.Toolkit" instead of "WPFToolkit", the xml namespace should be:

        xmlns:toolkit1="clr-namespace:System.Windows.Controls;assembly=WPFToolkit"
        xmlns:toolkit2="clr-namespace:System.Windows.Controls;assembly=DotNetProjects.Input.Toolkit"


MainWindow.cs:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //public ObservableCollection<Dealer> DealerNameArr = new ObservableCollection<Dealer>();
        //public List<Dealer> DealerNameArr = new List<Dealer>();

        public MainWindow()
        {
            InitializeComponent();

            //this.DealerNameArr.Add(new Dealer() { IDDealer = 0, DealerName = "Dealer 0"});
            //this.DealerNameArr.Add(new Dealer() { IDDealer = 1, DealerName = "Dealer 1"});
            //this.DealerNameArr.Add(new Dealer() { IDDealer = 2, DealerName = "Dealer 2"});

            //MyAC.ItemsSource = DealerNameArr;

            //this.MyAC.PreviewKeyDown += new KeyEventHandler( (a, b) =>
            this.MyAC.Populating += new PopulatingEventHandler((a, b) =>
            {
                switch (b.Key)
                {
                    case Key.Delete:
                    case Key.Back:
                    case Key.Up:
                    case Key.Down:
                    case Key.Left:
                    case Key.Right:
                    case Key.Home:
                    case Key.End:
                        return;
                }

                string jsonStr = AjaxV1("https://erp.local:8443/CN/Demo1?term=" + ((AutoCompleteBox)a).Text + ConvertKeyToChar(b.Key));
                List<Dealer> DealerNameArr = new List<Dealer>();

                iojson i = new iojson();
                i.Decode(jsonStr);
                i.GetObjFromArr(0, DealerNameArr);

                MyAC.ItemsSource = DealerNameArr;
                //this.MyAC.ItemsSource.IsDropDownOpen = true;
            }
            );
        }

        public static char ConvertKeyToChar(Key key)
        {
            return Convert.ToChar(KeyInterop.VirtualKeyFromKey(key));
        }

        public static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public string AjaxV1(string uri)
        {
            try
            {
                // TODO: this is a temporary remove SSL ceritficate check solution. Please comment out this line in production.
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

                Debug.WriteLine("uri: " + uri);

                var httpClient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate });
                var response = httpClient.GetAsync(uri).Result;

                // will throw an exception if not successful
                response.EnsureSuccessStatusCode();

                string jsonStr = response.Content.ReadAsStringAsync().Result;

                Debug.WriteLine("JSON: " + jsonStr);

                //return await Task.Run(() => JsonObject.Parse(content));
                //return await Task.Run(() => content);
                //return response.Content.ReadAsStringAsync();
                return jsonStr;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return "{Status:false}";
            }
        }

        private void MyAC_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var item = ((AutoCompleteBox)sender).SelectedItem;
            Dealer d = (Dealer)item;
            textBlock.Text = d.DealerName + "_" + d.IDDealer;
        }
    }

    public class Dealer
    {
        public int IDDealer { get; set; }
        public string DealerName { get; set; }
    }
}

iojson.cs:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication1
{
    class iojson
    {
        public bool Status { get; set; }
        public List<object> ErrArr { get; set; }
        public int ErrCount { get; set; }
        public List<object> ObjArr { get; set; }
        public Dictionary<string, object> ObjMap { get; set; }

        public object GetObjFromArr(int k, object obj)
        {
            if (k < 0 || k >= this.ObjArr.Count)
            {
                return null;
            }

            var jsonRaw = this.ObjArr[k];

            if (obj == null)
            {
                return jsonRaw;
            }

            populateObj(obj, jsonRaw.ToString());
            return obj;
        }

        public object GetObjFromMap(string k, object obj)
        {
            var jsonRaw = this.ObjMap[k];

            if (obj == null)
            {
                return jsonRaw;
            }

            populateObj(obj, jsonRaw.ToString());
            return obj;
        }

        public string Encode()
        {
            return JsonConvert.SerializeObject(this);
        }

        public void Decode(string jsonStr)
        {
            populateObj(this, jsonStr);
        }

        public error populateObj<T>(T obj, string jsonStr)
        {
            var serializer = new JsonSerializer();

            using (var reader = new StringReader(jsonStr))
            {
                serializer.Populate(reader, obj);
            }

            return null;
        }
    }

    public struct ObjErr
    {
        public object obj;
        public error err;
    }

    public class error
    {
        public string S { get; set; }

        public void New(string s)
        {
            this.S = s;
        }

        public string Error()
        {
            return this.S;
        }
    }
}

Reference:

https://www.nuget.org/packages/WPFToolkit/

https://www.nuget.org/packages/DotNetProjects.Wpf.Toolkit/

https://github.com/dotnetprojects/WpfToolkit/blob/master/WpfToolkit/Samples/AutoCompleteBox/AutoCompleteBoxSample.xaml

Newline in a WPF label?

Method 1:

in WPF you can use the value "&#10;" or "&#xA;"

For example:

<b><label Content="Lorem&#10;ipsum" /></b>

("10" is the ASCII number for newline)

or

<b><label Content="Lorem&#xA;ipsum" /></b>

("A" is the ASCII number for newline in hex)

Method 2:

<Label><TextBlock>Lorem<LineBreak/>ipsum</TextBlock></Label>

Reference:

http://stackoverflow.com/questions/483802/newline-in-a-wpf-label

Monday, October 24, 2016

Reversing a String

str := "Hello, 世界"

for len(str) > 0 {
    r, size := utf8.DecodeLastRuneInString(str)
    fmt.Printf("%c %v\n", r, size)

    str = str[:len(str)-size]
}

Reference:

https://tip.golang.org/pkg/unicode/utf8/#DecodeLastRuneInString

Sunday, October 23, 2016

Automatic vertical scroll bar in WPF TextBlock?

<TextBox Name="myTextBox"
         TextWrapping="Wrap"
         ScrollViewer.HorizontalScrollBarVisibility="Auto"
         ScrollViewer.VerticalScrollBarVisibility="Auto"
         ScrollViewer.CanContentScroll="True">SOME TEXT
</TextBox>

"ScrollViewer currently allows two scrolling modes: smooth pixel-by-pixel scrolling (CanContentScroll = false) or discrete item-by-item scrolling (CanContentScroll = true). Currently WPF supports UI virtualization only when scrolling by item. Pixel-based scrolling is also called “physical scrolling” and item-based scrolling is also called “logical scrolling”

Reference:

http://stackoverflow.com/questions/1192335/automatic-vertical-scroll-bar-in-wpf-textblock

http://stackoverflow.com/questions/3724593/why-setting-scrollviewer-cancontentscroll-to-false-disable-virtualization

Friday, October 21, 2016

Passing data between WPF forms

Method 1: Pass the data into the construction or set the data through its public method:

Window2 newWindow = new Window2(strForm1Text);

newWindow.TestMsg = strForm1Text;

Method 2: You can set the First window as the Second window's DataContext

namespace Banking_System
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnSwitchForm_Click(object sender, RoutedEventArgs e)
        {
            Window2 newWindow = new Window2(strForm1Text);
            newWindow.DataContext = this;
            newWindow.ShowDialog();
        }
    }

    public partial class MainWindow2 : Window
    {
        public MainWindow2()
        {
            var window1 = this.DataContext;
        }
    }
}

Method 3: using ShowDialog and a public method then testing that the DialogResult is true then reading the value from the method.

if (newWindow.ShowDialog() == true)
            this.Title = newWindow.myText();

Method 4: Create an event in your second window, have the parameters of the event's delegate contain whatever information you want to pass:

public class Popup : Window
{
    public event Action<string> Check;

    public void Foo()
    {
        //fire the event
        if (Check != null)
            Check("hello world");
    }
}

Then the main window can subscribe to that event to do what it wants with the information:

public class Main : Window
{
    private Label label;
    public void Foo()
    {
        Popup popup = new Popup();

        // use the Action<T> delegate with anonymous methods:
        popup.Check += delegate (string s)
        {
            label.Content = s;
        };

        // this is the shorthand of the above:
        popup.Check += value => label.Content = value;

        popup.ShowDialog();
    }
}

Method 5: create a CustomEvent and subscribe to it in the creating window like this.

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        Window1 newWindow = new Window1();
        newWindow.RaiseCustomEvent += new EventHandler<CustomEventArgs>(newWindow_RaiseCustomEvent);
        newWindow.Show();

    }

    void newWindow_RaiseCustomEvent(object sender, CustomEventArgs e)
    {
        this.Title = e.Message;
    }
}

Window1.xaml.cs

public partial class Window1 : Window
{
    public event EventHandler<CustomEventArgs> RaiseCustomEvent;

    public Window1()
    {
        InitializeComponent();
    }
    public string myText()
    {
        return textBox1.Text;
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {

        RaiseCustomEvent(this, new CustomEventArgs(textBox1.Text));
    }
}

public class CustomEventArgs : EventArgs
{
    public CustomEventArgs(string s)
    {
        msg = s;
    }
    private string msg;
    public string Message
    {
        get { return msg; }
    }
}

Method 6:

Since you are working with the WPF, use CommandBindings and Messaging. I also recommend you that you take a closser look at MVVM Frameworks, I prevere the MVVM Light Toolkit. There are a lot of HowTos for the framework, just ask google.

Reference:

http://stackoverflow.com/questions/30063550/how-should-i-pass-data-between-wpf-windows-involving-mainwindow-c

http://stackoverflow.com/questions/14433935/passing-data-between-wpf-forms

http://stackoverflow.com/questions/21607925/c-sharp-return-variable-from-child-window-to-parent-window-in-wpf

http://stackoverflow.com/questions/2282476/actiont-vs-delegate-event

Wednesday, October 19, 2016

Why are there two formats to the WpfToolkit namespace?

Why are there two formats to the WpfToolkit namespace?

        xmlns:toolkit1="http://schemas.microsoft.com/wpf/2008/toolkit"
        xmlns:toolkit2="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"

Well, they are slightly different.

The frst example you provided allows for a namespace declaration to map to multiple CLR namespaces. For example, System.Windows and System.Windows.Controls maps to the http://schemas.microsoft.com/winfx/2006/xaml/presentation namespace, allowing you to reference any controls from either mapped CLR namespace from a single declaration.

The second example is a fully qualified namespace declaration. It only maps to a single CLR namespace and you will only have access to controls in that single CLR namespace.

For more information on namespaces please visit this link: http://msdn.microsoft.com/en-us/library/ms747086.aspx

WpfToolkit/WpfToolkit/AssemblyAttrs.cs:

[assembly:XmlnsDefinition("http://schemas.microsoft.com/wpf/2008/toolkit", "Microsoft.Windows.Controls")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/wpf/2008/toolkit", "Microsoft.Windows.Controls.Primitives")]

Reference:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/4d136742-9850-4747-a7d0-3c21154fa12d/why-are-there-two-formats-to-the-wpftoolkit-namespace-when-should-i-use-each?forum=wpf

https://github.com/dotnetprojects/WpfToolkit/blob/3f638d3d738f3404ccd5fd6ee936cfa6653f1ddc/WpfToolkit/AssemblyAttrs.cs

Tuesday, October 18, 2016

To get the TextBox of Combobox you can use

To get the TextBox of Combobox you can use

TextBox TxtBox = (TextBox)myCombo.Template.FindName("PART_EditableTextBox", myCombo);

Disable select all text highlighting when using combobox in WPF

        private void MyComboBox_DropDownOpened(object sender, EventArgs e)
        {
            TextBox textBox = (TextBox)((ComboBox)sender).Template.FindName("PART_EditableTextBox", (ComboBox)sender);
            textBox.SelectionStart = ((ComboBox)sender).Text.Length;
            textBox.SelectionLength = 0;
        }

Reference:

http://stackoverflow.com/questions/1441645/wpf-dropdown-of-a-combobox-highlightes-the-text

http://stackoverflow.com/questions/3667275/remove-select-all-from-combobox-wpf

Saturday, October 15, 2016

How to make modal dialog in WPF?

Showing your window using the ShowDialog method:

 // set Owner property
w.Owner = Window.GetWindow(this);

// or
w.Owner = this;

// or
w.Owner = Application.Current.MainWindow;

// or
w.Owner = (Window)PresentationSource.FromVisual(this).RootVisual;

w.ShowDialog();

Note: Don't forget to set the Owner property on the dialog window. Otherwise, the user will get weird behavior when Alt+Tabbing, etc.

Reference:

http://stackoverflow.com/questions/499294/how-do-make-modal-dialog-in-wpf

Wednesday, October 12, 2016

Getting first day of the week in MySql using Week number

Getting first day of the week in MySql using Week number

SELECT
 ADDDATE(CURDATE(), INTERVAL (1 - DAYOFWEEK(CURDATE())) DAY) WeekStart,
 ADDDATE(CURDATE(), INTERVAL (7 - DAYOFWEEK(CURDATE())) DAY) WeekEnd

Reference:

http://stackoverflow.com/questions/3317980/getting-first-day-of-the-week-in-mysql-using-week-no

Thursday, October 6, 2016

How to convert a character in to equivalent System.Windows.Input.Key Enum value?

How to convert a character in to equivalent System.Windows.Input.Key Enum value?

            var c = Convert.ToChar(KeyInterop.VirtualKeyFromKey(key));
            Debug.WriteLine("k: " + key);
            Debug.WriteLine("c: " + c);

Reference:

http://stackoverflow.com/questions/289792/int-to-char-in-c-sharp

Lambda Expressions / statement

            this.MyAC.PreviewKeyDown += new KeyEventHandler(async (a, b) =>
                 this.MyAC.ItemsSource = await ViewModels.MainViewModel.GetItems(((RadAutoCompleteBox)a).SearchText, b.Key)
            );

            this.MyAC.PreviewKeyDown += new KeyEventHandler(async (a, b) =>
            {
                 this.MyAC.ItemsSource = await ViewModels.MainViewModel.GetItems(((RadAutoCompleteBox)a).SearchText, b.Key);
                 this.MyAC.ItemsSource.IsDropDownOpen = true;
            }
            );

            this.GridSearchBox.PreviewKeyDown += new KeyEventHandler(async (object a, KeyEventArgs b) =>
            {
                this.GridSearchBox.ItemsSource = await ViewModels.MainViewModel.GetItems(((ComboBox)a).Text, b.Key);
                this.GridSearchBox.IsDropDownOpen = true;
            }
            );

            w.MyAnswer += (value) =>
            {
                this.MyAnswer = value;
            };

            w.Closed += (object sender2, EventArgs e2) =>
            {
                SerialNumBox1.Text = this.MyAnswer;
            };

    child.Closed += new EventHandler(child_Closed);

    void child_Closed(object sender, EventArgs e)
    {
        // Child window closed
    }

            w.MyMsg2 += value2 => textBox3.Text = value2;

Wednesday, October 5, 2016

WPF: How do I set the Owner Window of a Dialog shown by a UserControl?

w.Owner = this;

w.Owner = Window.GetWindow(this);

To get the top level window your control is in, assuming there is one:

(Window)PresentationSource.FromVisual(this).RootVisual

To get the main window:

Application.Current.MainWindow

Reference:

http://stackoverflow.com/questions/607370/wpf-how-do-i-set-the-owner-window-of-a-dialog-shown-by-a-usercontrol

Tuesday, October 4, 2016

C# - Return variable from child window to parent window in WPF

Create an event in your second window, have the parameters of the event's delegate contain whatever information you want to pass:

public class Popup : Window
{
    public event Action<string> Check;

    public void Foo()
    {
        //fire the event
        if (Check != null)
            Check("hello world");
    }
}

Then the main window can subscribe to that event to do what it wants with the information:

public class Main : Window
{
    private Label label;
    public void Foo()
    {
        Popup popup = new Popup();
        popup.Check += value => label.Content = value;
        popup.ShowDialog();
    }
}

Reference:

http://stackoverflow.com/questions/21607925/c-sharp-return-variable-from-child-window-to-parent-window-in-wpf

Monday, October 3, 2016

Install latest Node.js on CentOS 7

Add Node.js Yum Repository:

# curl --silent --location https://rpm.nodesource.com/setup_6.x | bash -

Install Node.js and NPM:

# yum install nodejs

Check Node.js version:

# node -v

v6.7.0

Check NPM version:

# npm -v

3.10.3

Create Demo Web Server:

# vim demo_srv.js

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Welcome Node.js');
}).listen(3001, "127.0.0.1");

console.log('Server running at http://127.0.0.1:3001/');

Start the web server:

# node --debug demo_server.js

Reference:

https://nodejs.org/en/download/package-manager/#enterprise-linux-and-fedora

http://tecadmin.net/install-latest-nodejs-and-npm-on-centos/

Wednesday, September 21, 2016

Button Click event fires when pressing Enter key in different input

I had the same problem and solved it by adding type="button" attribute to the <button> element, by which IE thinks the button as a simple button instead of a submit button (which is default behavior of a <button> element).

Reference:

http://stackoverflow.com/questions/12325066/button-click-event-fires-when-pressing-enter-key-in-different-input-no-forms

A handy tool for writing RESTful API in golang. It enables you to exchange data between client and server through a uniform JSON format

A handy tool for writing RESTful API in golang. It enables you to exchange data between client and server through a uniform JSON format

iojson provides a convenient way to exchange data between your client and server through a uniform JSON format. It helps you to encode data from Go structs to a JSON string and to decode data from a JSON string to Go structs. iojson supports storing Go objects to a slice or to a map, which means you could reference your object either by a slice index or by a map key according to your preference. After populating data from JSON to Go objects, the methods of the objects remained working.

iojson also provides a HTTP middleware function, which works with Alice (a famous middleware chainer).

https://github.com/junhsieh/iojson

Tuesday, September 20, 2016

invalid indirect of typedSlice (type interface {})

invalid indirect of typedSlice (type interface {})

You can't dereference typedSlice, because it's an interface{}. You would have to extract the pointer with a type assertion

realSlice := *typedSlice.(*[]Demo)

cannot range over typedSlice (type interface {})

Again, since typedSlice is an interface{}, you can't range over it. If you want to range over the values you need to use a type assertion, or iterate manually via reflect:

for i := 0; i < o.Elem().Len(); i++ {
    ret = append(ret, o.Elem().Index(i).Interface())
}

Reference:

http://stackoverflow.com/questions/34163174/cant-use-range-on-slice-made-with-reflect-then-passed-json-unmarshal

Friday, September 16, 2016

HttpWebRequest cookie post header Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using System.Net;
using System.Diagnostics;

namespace HttpWebRequestExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        CookieContainer Cookie = null;
        string CSRFtoken = "";

        public MainWindow()
        {
            InitializeComponent();
        }

        private void LoginBtn_Click(object sender, RoutedEventArgs e)
        {
            Cookie = new CookieContainer(); // important

            PerformRequest("POST", "https://erp.local:8443/Login", "{\"ObjArr\":[{\"Username\":\"bot\",\"Password\":\"bot\"}]}");
        }

        private void ItemBtn_Click(object sender, RoutedEventArgs e)
        {
            PerformRequest("GET", "https://erp.local:8443/Item/List", "");
        }

        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            PerformRequest("POST", "https://erp.local:8443/Ship/Save", "{\"Status\":true,\"ErrArr\":[],\"ErrCount\":0,\"ObjArr\":[{\"IDCNShip\":0,\"InvoiceNum\":15,\"ContainerNum\":\"\",\"ETD\":\"2016-09-13\",\"ETA\":\"\",\"IDWarehouse\":0,\"TotalQty\":0,\"IsClosed\":false,\"ShippedDate\":\"\",\"Remark\":\"\",\"Created\":\"\",\"Changed\":\"\",\"CNShipItemWalkerArr\":[{\"LineNum\":0,\"RowNum\":1,\"ItemNum\":\"A0\",\"ItemName\":\"\",\"SizeLong\":\"\",\"ColorShort\":\"\",\"ColorShortZH\":\"\",\"Qty\":0,\"NetWeight\":0,\"GrossWeight\":0,\"UnitPrice\":0,\"Remark\":\"\",\"Created\":\"\",\"Changed\":\"\"}],\"CNShipItemPartArr\":[{\"LineNum\":0,\"BoxLabel\":\"ABC\",\"ItemNum\":\"A1\"}]}],\"Data\":{}}");
        }

        private void PerformRequest(string method, string url, string postData)
        {
            // TODO: this is a temporary remove SSL ceritficate check solution. Please comment out this line in production.
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = Cookie; // use the global cookie variable


            byte[] data = Encoding.UTF8.GetBytes(postData);

            request.Method = method;

            request.Headers.Add("X-CSRF-Token", CSRFtoken);

            if (method == "POST")
            {
                request.ContentType = "application/json; charset=utf-8";
                request.ContentLength = data.Length;

                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }

            WebResponse response = (HttpWebResponse)request.GetResponse();
            string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            CSRFtoken = response.Headers.Get("X-CSRF-Token");

            Debug.WriteLine("CSRFtoken: " + CSRFtoken);
            Debug.WriteLine(responseString);
        }

        public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    }
}


Reference:

http://csharp-tricks-en.blogspot.ca/2015/03/http-requests-get-or-post-with-cookies.html

Wednesday, September 14, 2016

Convert JSON string to C# object

Convert JSON string to C# object

using System.Windows;

using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

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

        private void button_Click(object sender, RoutedEventArgs e)
        {
            string str = "{\"Status\":true,\"ErrArr\":[],\"ErrCount\":0,\"ObjArr\":[],\"Data\":{\"Test\":\"Hello\",\"ItemArr\":[{\"IDItem\":111,\"ItemNum\":\"AA01\",\"ItemName\":\"Computer\"},{\"IDItem\":112,\"ItemNum\":\"AA02\",\"ItemName\":\"Desk\"}]}}";

            MemoryStream jsonSource = new MemoryStream(Encoding.UTF8.GetBytes(str));
            var s = new DataContractJsonSerializer(typeof(RootObject));
            var j = (RootObject)s.ReadObject(jsonSource);

            Debug.WriteLine(str);

            Debug.WriteLine(j.Data.Test);

            for (int i = 0; i < j.Data.ItemArr.Count; i++)
            {
                Debug.WriteLine(j.Data.ItemArr[i].IDItem + "; " + j.Data.ItemArr[i].ItemNum + "; " + j.Data.ItemArr[i].ItemName);
            }
        }
    }


    [DataContract]
    public class ItemArr
    {
        [DataMember]
        public int IDItem { get; set; }

        [DataMember]
        public string ItemNum { get; set; }

        [DataMember]
        public string ItemName { get; set; }
    }

    [DataContract]
    public class Data
    {
        [DataMember]
        public string Test { get; set; }

        [DataMember]
        public List<ItemArr> ItemArr { get; set; }
    }

    [DataContract]
    public class RootObject
    {
        [DataMember]
        public bool Status { get; set; }

        [DataMember]
        public List<object> ErrArr { get; set; }

        [DataMember]
        public int ErrCount { get; set; }

        [DataMember]
        public List<object> ObjArr { get; set; }

        [DataMember]
        public Data Data { get; set; }
    }
}

Reference:

http://json2csharp.com/

Monday, August 22, 2016

How to prevent or disable favicon.ico requests?

How to prevent or disable favicon.ico requests?

The following uses data URI and can be used to avoid fake favicon requests:

<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon"> 

Reference:

http://stackoverflow.com/questions/1321878/how-to-prevent-favicon-ico-requests

Friday, August 12, 2016

C# .Net monitor directory file changed created

What does Dropbox use to monitor file changes in the Dropbox folder?

Native Windows applications track directory changes by using the FindFirstChangeNotification / FindNextChangeNotification functions.

https://www.quora.com/What-does-Dropbox-use-to-monitor-file-changes-in-the-Dropbox-folder

As name suggests FileSystemWatcher watches the Directory or Files for any modification. FileSystemWatcher is a class in .Net derived fromSystem.IO namespace that continuously monitors a specified Directory for file system changes. As soon as the change occurs it automatically raises a corresponding event. These events include Created, Renamed, Changed, Deleted and an Error event. Of course, there are several reasons why one needs File System Watcher in his application. As mentioned above there might be a requirement in application to log a File creation time or deletion time, etc. In short this acts as Directory watcher or File Watcher service. 

The file system watcher in C# monitors a specified directory along with files and subdirectories. The FileSystemWatcher has a property called "Filter" by which you can filter the files with specific extensions i.e. with the help of wild-card; even you can monitor File attributes like Last Access, Security, Last Write and Size of a file. 

Look at the below table for all events that gets raised byFileSystemWatcher while monitoring a specified Directory or file. 

Sr. No.
Event Name
Description
1
Created
When a new File or Folder gets created.
2
Renamed
When an existing file or folder gets renamed.
3
Deleted
When an existing file or folder gets deleted.
4
Changed
When an existing file or folder gets modified.
5
Error
When an error occurs.
Now let's look at the actual implementation of simple FileSystemWatcher. In this example, we will create a new Windows Forms on which user can be able to Select a Folder path to monitor. Please refer below screenshot, this would be our filesystemwatecher application. 

Please note that, We are using Visual Studio 2010 – Windows Form application to demonstrate the FileSystemWatcher that will monitor a folder for changes. In fact it monitors Directory, subdirectories along with files in it.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace a1ashiishFileSystemWatcher
{
    public partial class MainForm : Form
    {
        public ListBox listBox;
        public const String startMonitoring = "Start Minitoring...";
        public const String stopMonitoring = "Stop Minitoring...";

        public MainForm()
        {
            InitializeComponent();

            //Create a listBox to show activities of all Events.
            listBox = new ListBox();
            listBox.FormattingEnabled = true;
            listBox.Location = new System.Drawing.Point(23, 121);
            listBox.Name = "listBox";
            listBox.Size = new System.Drawing.Size(571, 238);
            listBox.TabIndex = 2;
            this.Controls.Add(listBox);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Create FolderBrowserDialog object.
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            // Show a button to create a new folder.
            folderBrowserDialog.ShowNewFolderButton = true;

            DialogResult dialogResult = folderBrowserDialog.ShowDialog();

            // Get selected path from FolderBrowserDialog control.
            if (dialogResult == DialogResult.OK)
            {
                textBox1.Text = folderBrowserDialog.SelectedPath;
                Environment.SpecialFolder root = folderBrowserDialog.RootFolder;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // Create a new FileSystemWatcher object.
            FileSystemWatcher fsWatcher = new FileSystemWatcher();

            switch (button2.Text)
            {
                // Start Monitoring...
                case startMonitoring:
                    if (!textBox1.Text.Equals(String.Empty))
                    {
                        listBox.Items.Add("Started FileSystemWatcher Service...");
                        fsWatcher.Path = textBox1.Text;

                        // Set Filter.
                        fsWatcher.Filter = (textBox2.Text.Equals(String.Empty)) ? "*.*" : textBox2.Text;

                        // Monitor files and subdirectories.
                        fsWatcher.IncludeSubdirectories = true;

                        // Monitor all changes specified in the NotifyFilters.
                        fsWatcher.NotifyFilter = NotifyFilters.Attributes |
                                                 NotifyFilters.CreationTime |
                                                 NotifyFilters.DirectoryName |
                                                 NotifyFilters.FileName |
                                                 NotifyFilters.LastAccess |
                                                 NotifyFilters.LastWrite |
                                                 NotifyFilters.Security |
                                                 NotifyFilters.Size;

                        fsWatcher.EnableRaisingEvents = true;

                        // Raise Event handlers.
                        fsWatcher.Changed += new FileSystemEventHandler(OnChanged);
                        fsWatcher.Created += new FileSystemEventHandler(OnCreated);
                        fsWatcher.Deleted += new FileSystemEventHandler(OnDeleted);
                        fsWatcher.Renamed += new RenamedEventHandler(OnRenamed);
                        fsWatcher.Error += new ErrorEventHandler(OnError);

                        button2.Text = stopMonitoring;
                        textBox1.Enabled = false;
                        textBox2.Enabled = false;
                    }
                    else
                    {
                        listBox.Items.Add("Please select folder to monitor....");
                    }
                    break;

                // Stop Monitoring...
                case stopMonitoring:
                default:

                    fsWatcher.EnableRaisingEvents = false;
                    fsWatcher = null;
                    button2.Text = startMonitoring;
                    textBox1.Enabled = true;
                    textBox2.Enabled = true;

                    listBox.Items.Add("Stopped FileSystemWatcher Service...");
                    break;
            }

        }

        // FileSystemWatcher - OnCreated Event Handler
        public void OnCreated(object sender, FileSystemEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format("Path : \"{0}\"   || Action : {1}", e.FullPath, e.ChangeType)); });
        }

        // FileSystemWatcher - OnChanged Event Handler
        public void OnChanged(object sender, FileSystemEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format("Path : \"{0}\"   || Action : {1}", e.FullPath, e.ChangeType)); });
        }

        // FileSystemWatcher - OnRenamed Event Handler
        public void OnRenamed(object sender, RenamedEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format("Path : \"{0}\"   || Action : {1} to \"{2}\"", e.FullPath, e.ChangeType, e.Name)); });
        }

        // FileSystemWatcher - OnDeleted Event Handler
        public void OnDeleted(object sender, FileSystemEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format("Path : \"{0}\"   || Action : {1}", e.FullPath, e.ChangeType)); });
        }

        // FileSystemWatcher - OnError Event Handler
        public void OnError(object sender, ErrorEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format("Error : {0}", e.GetException().Message)); });
        }

    }
}

Reference:

http://www.csharptutorial.in/2013/04/Csharp.Net-How-To-Monitor-Directory-and-files-using-Csharp-FileSyestemWatcher.html#.U16l0vn3V4A

Wednesday, August 3, 2016

sum up group by criteria in Google Sheets


=sum(sumif(indirect(C4&"!$A$2:A"), A4, indirect(C4&"!$F$2:F"))*24)

Friday, July 29, 2016

對自己狠一點!成功的人,一定留給自己

「斬斷一切纏繞在自己身上的鎖鏈,
唯獨忠於自我」── 金鎮愛
「狠心」在韓文裡用「毒」字來表示,

「狠心」的意思,就是「遵守對自己的承諾」。

說得仔細一點,

就是

「斬斷一切纏繞在自己身上的鎖鏈,

唯獨忠於自我」,

首先你要學習的就是

「嘗試離開眾人獨處」。

──金鎮愛

獨處時間、獨處空間的力量
人要有獨處的時間,才會成長。
守護自己最簡單的方式,就是「獨處」。

獨處,和睡覺是同一個道理。

只能獨自入睡的睡眠時間裡,

人會將當天所學、所體驗過的事情,

在腦子裡接二連三銘記下來,

並啟動潛意識,做夢的同時,

也將新的刺激和新的能量填補進去。

睡眠對人的成長與生存不可或缺;

獨處對成長和生存,

也同樣是絕對需要的。



「脫離分內之事」的狀態 才是獨處
所謂獨處,

基本上就是「離群而出的狀態」。

對一個人來說,

人可以是最美好的天國,

也可以是最可怕的地獄;

可以給我們帶來無限的喜悅,

卻也可能拖住我們的腳步。

另外,

真正的獨處,

是指「脫離分內之事的狀態」。

當我們

從每天不斷重複的

各種分內之事中脫離的時候,

才能感受到生活操之在我。

任何人都需要,別說你例外
然而,

想要一個人獨處,

就非得去旅行嗎?

搞不好比起出發去旅行,

我們更需要的,

是在日常生活的枷鎖裡

擁有「自己的樂園」。

那就是「獨處的時間、獨處的空間」。

任何人都需要自己的時間、自己的空間。

不管是學生、教師、受雇者、

雇主、上班族、自由工作者、

妻子、丈夫、少男、少女,

更別說是兒童,甚至是嬰兒,

全都一樣。



人們想盡辦法 不讓自己獨處,
同時也不想讓 別人獨處?!


有趣的是,

人們卻傾向想盡辦法不讓自己獨處,

同時也不想讓別人獨處。

因為這個社會裡,

大家都害怕遭人「排擠」的關係嗎?

還是怕被人貼上不合群、沒人情味的標籤?

也可能是

因為我們文化中特有的「拉幫結派」社會特性,

或者是因為,

有太多人混雜在一起、太多資訊在空中交流,

形成了這時代的「群癮症」。



必須「狠下心」來才能擁有 獨處的時間
因此,

我們更迫切需要「獨處」的時間。

在無人妨礙,

只屬於自己的時間、空間裡,

好好品嘗沉浸在自己的時間、空間裡的滋味。

無論如何想辦法享受一下獨處時間和獨處空間吧!

獨處空間,

相較之下比較容易獲得。

但獨處時間,

就必須狠下心來才能擁有。

好好學習獨處空間和獨處時間的力學吧!

與自己對決的黎明時分
我的獨處時間,

只能選在黎明時分。

每天黎明,

是我和自己面對面,

與內在的我相遇的時間。

這一段時光充斥著煩惱與角力,

也讓我回顧各種折磨我的痛苦。

同時,

更是讓我集中精神處理非分內工作、

做我自己想做的事情的時間。

要不是有這段完全屬於我的時間,

我想我大概早就瘋掉,或逃到天涯海角去了。



當萬籟俱寂,
眾人皆睡我獨醒之際
我對黎明的崇拜,

可說如滔滔江水,一瀉千里。

當萬籟俱寂,

眾人皆睡我獨醒之際,

讓我有一種隱隱的喜悅。



沒有人找我,

也沒有討厭的電話,

只要能好好活用黎明的時間,

會覺得一天真的很夠用。

不管怎樣,

傍晚或夜裡的時間,

還是屬於消耗性質的。

邀約遊玩的人很多,

可玩可去的地方也很多,

燈火輝煌,充滿誘惑的地方更多。

悠哉地吃完一頓晚飯後,

想再回頭工作就很難。

想多玩點,是入夜後的心理;

相反地,

想多做點事情,就是黎明時的心理。

孤單,也是有好處的。

醒著的人一個都沒有,

營業的地方也不多。

因此,

黎明可說是一個沒有外界誘惑,

只能沉浸在自己世界的自我誘惑時間。

當然,

不是任何人都能成為「黎明型」,

個人情況上實在無法成為早鳥的話,

請繼續擠出其他的時間。

每個人都需要一段隱密又激烈地面對自己、

與自己對決的時間,

不管是晚上十二點前後,

還是上班前、上班後或下班後的時光。



一天至少兩個小時的時間
無論什麼人,

一天裡至少需要兩個小時這樣的時間。

為什麼是兩個小時,

因為去掉進入狀況的十五分鐘,

從狀況裡出來的十五分鐘,

集中精神大約九十分鐘,

就可以做很多事情,

所以兩個小時的時間差不多。

一天花兩個小時,

一年就有七百到八百個小時,

一個禮拜以

工作四十個小時來計算的話,

就等於至少有四個月的時間

是為了自己在工作,

如此累積下來的力量是很驚人的。



所以,
狠下心來讓自己擁有獨處的時間吧!
以自己幽禁自己的方式,

尋找自己的存在感,

擺脫日常生活的羈絆所導致的消耗感。

那麼,

你就能在人生的

分內之事與想做之事中間,

找到平衡點。

與妨礙獨處的事物對抗
這麼多想奪走我時間的誘惑,
該如何擺脫?
然而,

這個世界不肯放我一人獨處,

總以各種方式干涉我,

想剝奪我的時間。

這麼多想奪走我時間的誘惑,

該如何擺脫?



電話最容易干擾我,我該怎麼做?
就以這個時代算得上妨礙獨處時間

排行榜第一名的「電話」為例吧!

我對於找上門來的電話,

訂下了幾項防禦原則。



(1)請託電話,一律以電子郵件連絡
請託電話,例如邀稿、邀約演講或訪談的,

一律以電子郵件連絡,

如此就能明快地在短時間內

傳遞資訊和掌握內容。



(2)訂好不接電話的時間。
例如當我必須全心投入工作的時候,

乾脆就把電話切斷幾天。

或是一天中有幾個小時不接電話,

就當作自己去旅行了。



(3)主要利用簡訊連絡。


(4)沒有來電顯示的電話,盡可能不接,
當作對方會另傳簡訊來。



(5)手機最好只用來撥出用。


要想堅持這些原則,

我自己也有必須盡力做到的原則,

就是「一定回信」。

不把時間 花在沒意義的事情上
不只是業務方面的電話,

連邀約性質的電話也隨即回覆。

因為從我自己無數次拜託他人,

也無數次被拒絕的經驗來看,

就算是被拒絕也想早點知道,

才能尋求其他管道。

不過,對於一些不著邊際的邀約,

也就沒有非得回覆的必要了。

不久之後我就了解到,

電話接到手軟,

不代表工作也接個不停。

有時反而是「如留言般簡短的電話」,

獲取實質機會的可能性更高。



這裡雖然舉了電話為例,

但對於不時剝奪我們時間的所有事物,
都必須建立起自己的原則。
推特、臉書等通訊軟體也可能使人上癮,

因此要有自己活用這些軟體的原則。

Reference:

http://www.cmoney.tw/notes/note-detail.aspx?nid=58236

Tuesday, July 26, 2016

代碼覆蓋率 (code coverage) 是開發流程蠻重要的一環

代碼覆蓋率 (code coverage) 是開發流程蠻重要的一環,用來評估專案內測試的覆蓋率,也代表了自己寫的程式,至少要測試過一次。在 Github 上面最常用的一套就是 Coveralls 相信大家對於此服務並不陌生,一個好的 Open Source 專案一定會在 Readme 上附上 Coveralls badge,證明自己寫的專案都有經過測試,請安心使用。

Coveralls https://coveralls.io/

codecov https://codecov.io/

Travis https://travis-ci.org/

Reference:

https://blog.wu-boy.com/2016/07/new-coverage-service-codecov-io/

Monday, July 25, 2016

How to create a Symbolic Link on Windows 10?

What's the correct way to make symlinks in Windows 10?

You can use either mklink (cmd built-in) or junction (from Windows SysInternals, which is part of Microsoft) in Windows 10 to create junctions.

Notes:

junction can also list junctions and determine if a file is a junction unlike mklink.

mklink is an internal command only available within a cmd shell.

By default Administrator privileges are required to create symbolic links.

It can also be granted to other users. The security setting "Create symbolic links" can be granted at:

Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment\

Using mklink:

F:\test>mklink /j test-junction test

Junction created for test-junction <<===>> test

Using junction:

F:\test>C:\apps\NirSoft\SysinternalsSuite\junction.exe test-junction test

Junction v1.06 - Windows junction creator and reparse point viewer
Copyright (C) 2000-2010 Mark Russinovich
Sysinternals - www.sysinternals.com

Created: F:\test\test-junction
Targetted at: F:\test\test

Reference:

http://superuser.com/questions/1020821/how-to-create-a-symbolic-link-on-windows-10

Saturday, July 23, 2016

Debian Quick Start

Network configuration:

# vi /etc/network/interfaces

// for ipv4

iface eth0 inet static
address 192.168.6.11
netmask 255.255.255.0
network 192.168.6.0
broadcast 192.168.6.255
gateway 192.168.6.1

// for ipv6, you just need to add the entires below the segment as

iface eth0 inet6 static
address 2001:db8::c0ca:1eaf
netmask 64
gateway 2001:db8::1ead:ed:beef

DNS configuration:

# vi /etc/resolv.conf

nameserver 8.8.8.8
nameserver 8.8.4.4

Advanced networking:

Create alias for eth0 to have multiple IP address.

#IP Aliasing
auto eth0:0
iface eth0:0 inet static
 name Ethernet alias LAN card
 address 192.168.6.12
 netmask 255.255.255.0
 broadcast 192.168.6.255
 network 192.168.6.0

Restart Networking Service:

# service networking restart

Install tmux:

# apt-get install tmux

Update apt to ensure we have the latest packages:

# apt-get update

Remove any Vim cruft that might already be on your system:

# dpkg --get-selections | grep -i vim
# dpkg -l | grep -i vim
# apt list --installed | grep -i vim

# apt-get remove vim vim-runtime gvim vim-tiny vim-common vim-gui-common

Install Vim:

# apt-get install vim-nox

Install Git:

# apt-get install git

Monday, July 18, 2016

v.IDOrder undefined (type interface {} is interface with no methods)

v.IDOrder undefined (type interface {} is interface with no methods)

  var f = struct {
    IDOrder   int64
    IsClose   bool
    IsConfirm bool
    IDUser    int64
  }{}
  fPtr := util.StructFieldPtrArr(&f)
  outArr := []interface{}{}

  for rs.Next() {
    if err := rs.Scan(fPtr...); err != nil {
      return nil, err
    }

    outArr = append(outArr, f)
  }

  for k, v := range outArr {
    // incorrect
    log.Printf("%v: %v, %v\n", k, v.IDOrder, v.IsConfirm)

    // correct
    log.Printf("%v: %v\n", k, v.(struct {
      IDOrder   int64
      IsClose   bool
      IsConfirm bool
      IDUser    int64
    }).IDOrder)

  }

Friday, July 15, 2016

To debug InnoDB lock waits for transaction or show how many rows are locked (look under transaction):

To debug InnoDB lock waits for transaction or show how many rows are locked (look under transaction):

Method 1:

SELECT * FROM INFORMATION_SCHEMA.INNODB_TRX;

https://dev.mysql.com/doc/refman/5.5/en/innodb-information-schema-transactions.html

Method 2:

Enabling the InnoDB Lock Monitor

To enable the InnoDB Lock Monitor for periodic output, create the innodb_lock_monitor table:

CREATE TABLE innodb_lock_monitor (a INT) ENGINE=INNODB;

To disable the InnoDB Lock Monitor, drop the table:

DROP TABLE innodb_lock_monitor;

As of MySQL 5.6.16, you can also enable the InnoDB Lock Monitor by setting the innodb_status_output_locks system variable to ON. As with the CREATE TABLE method for enabling InnoDB Monitors, both the InnoDB standard Monitor and InnoDB Lock Monitor must be enabled to have InnoDBLock Monitor data printed periodically:

set GLOBAL innodb_status_output=ON;
set GLOBAL innodb_status_output_locks=ON;

When you shut down the server, the innodb_status_output and innodb_status_output_locks variables are set to the default OFF value.

To disable the InnoDB Lock Monitor, set innodb_status_output_locks to OFF. Set innodb_status_output to OFF to also disable the standard InnoDB Monitor.

Note: To enable the InnoDB Lock Monitor for SHOW ENGINE INNODB STATUS output, you are only required to enable innodb_status_output_locks.

https://dev.mysql.com/doc/refman/5.6/en/innodb-enabling-monitors.html

Method 3:

Run MySQL command in shell under console:

# mysql -u root -p -e 'SHOW ENGINE INNODB STATUS\G'


------------
TRANSACTIONS
------------
Trx id counter 381
Purge done for trx's n:o < 37F undo n:o < 0
History list length 39
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0, not started
MySQL thread id 84, OS thread handle 0x7f5b66aff700, query id 975 localhost root
SHOW ENGINE INNODB STATUS
---TRANSACTION 0, not started
MySQL thread id 50, OS thread handle 0x7f5b66c23700, query id 838 192.168.6.112 jun
---TRANSACTION 32E, not started
MySQL thread id 33, OS thread handle 0x7f5b8c04a700, query id 693 192.168.6.112 jun
---TRANSACTION 35F, not started
MySQL thread id 31, OS thread handle 0x7f5b66c6c700, query id 518 192.168.6.112 jun
---TRANSACTION 340, not started
MySQL thread id 28, OS thread handle 0x7f5b66bda700, query id 381 192.168.6.112 jun
---TRANSACTION 380, ACTIVE 1 sec starting index read
mysql tables in use 2, locked 2
LOCK WAIT 2 lock struct(s), heap size 376, 1 row lock(s)
MySQL thread id 83, OS thread handle 0x7f5b66b91700, query id 973 127.0.0.1 go_erp statistics
SELECT   SO.idOrder , SOLine.changed , SOLine.orderQty FROM SO INNER JOIN SOLine ON SO.idOrder = SOLine.idOrder WHERE SO.idOrder = 1 ORDER BY SO.idOrder FOR UPDATE
------- TRX HAS BEEN WAITING 1 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 323 n bits 72 index `PRIMARY` of table `go_erp`.`SO` trx id 380 lock_mode X locks rec but not gap waiting
------------------
---TRANSACTION 37F, ACTIVE 2 sec
5 lock struct(s), heap size 1248, 3 row lock(s), undo log entries 1
MySQL thread id 82, OS thread handle 0x7f5b66b48700, query id 969 127.0.0.1 go_erp
----------------------------

Method 4:

Install innotop:

# yum install innotop

Reference:

https://dev.mysql.com/doc/refman/5.5/en/innodb-information-schema-transactions.html

https://dev.mysql.com/doc/refman/5.5/en/innodb-trx-table.html

http://www.xaprb.com/blog/2007/09/18/how-to-debug-innodb-lock-waits/

Monday, July 11, 2016

excluding .svn .git files from find command

# find . -type d '(' -name .git -o -name vendor ')' -prune -o -type f

Note: Using -prune to avoid recursing into .svn and .git directories is better than using a regex.

Reference:

http://stackoverflow.com/questions/15883563/excluding-svn-git-files-from-findxargsgrep-pipe

Saturday, July 9, 2016

蘇格拉底的「詭辯」:乾淨的人 與 髒的人,我請這 2 個人 洗澡,誰會 先去洗澡?

在哲學課上學生們向蘇格拉底請教:
「老師,能不能用實例說明一下究竟什麼叫詭辯?」

蘇格拉底稍作考慮一下,然後說:
「有兩個人到我這裡來做客,
一個人很乾淨,一個人很髒。
我請這兩個人洗澡,
你們想想,他們兩個人誰會先去洗澡?」

繼續看下去...

從洗澡看什麼叫「詭辯」

「那還用說,當然是那個髒人。」
一個學生脫口而出。

「不對,是乾淨人。」
蘇格拉底反駁道,
「因為乾淨人養成了洗澡的習慣,
髒人卻認為沒什麼好洗的。」

「再想想看,究竟是誰會先洗澡了呢?」
「是乾淨人。」兩個學生接著說。

「不對,是髒人。
因為髒人比乾淨人更需要洗澡。」
蘇格拉底又反駁道。

然後蘇格拉底再次問道:
「如此看來,兩個客人中究竟誰會先去洗澡呢?」

「髒人!」
三個學生喊著重複了第一次的回答。
「又錯了。當然是兩個都洗了。」
蘇格拉底說,
「乾淨人有洗澡的習慣,而髒人需要洗澡。」

「怎麼樣,到底誰會先去洗澡了呢?」
「那看來是兩個人都洗了。」
四個學生猶豫不決地回答。
「不對,兩個人都沒洗。」
蘇格拉底解釋說,
「因為髒人沒有洗澡的習慣,
而乾淨人不需要洗澡。」

「老師說得都有道理,
但是我們究竟該怎樣理解呢?」
學生們不滿地說,

「你講的每次都不一樣,而又總是對的!」


蘇格拉底說:
「正是如此。你們看,

外表上、形式上好像是運用正確的推理手段,

實際上違反邏輯規律,

做出似是而非的結論,

這就是詭辯!
常見的詭辯手法有偷換論題、
捏造論據、循環論證、
機械類比、強詞奪理、斷章取義等等。」

再從洗澡看出詭辯中的「邏輯錯誤」

學生們又向蘇格拉底請教:
「老師,詭辯就是有意識地為某種謬論做論證,
其中有巧妙的不易發現的邏輯錯誤。
能不能用實例說明一下怎樣才能識破詭辯中的邏輯錯誤?」
蘇格拉底思考了一會兒,
給學生們出了下面的智力測驗題:

「有兩位工人,
一同維修一個多年沒有維修過的又老又舊的破煙囪。
當他們從煙囪裡爬出來的時候,
一位很乾淨,另一位卻滿臉滿身的煤灰。
請問你們:誰會先去洗澡呢?」

一位學生說:
「當然是那位滿臉滿身煤灰的工人會先去洗澡嘍!」

蘇格拉底說:
「是嗎?請你們注意,
乾淨的工人看見另一位滿臉滿身的煤灰,
覺得從煙囪裡爬出來真是骯髒;
另一位看到對方很乾淨,就不這麼想了,
而認為自己一定也很乾淨。
我現在再問你們,誰會先去洗澡?」

兩位學生很興奮地爭先恐後地回答:
「哦!我知道了!
乾淨的工人看到骯髒的工人時,
覺得他自己必定也是骯髒的。
但是骯髒的工人看到乾淨的工人時,
卻覺得自己並不髒啊!
所以一定是那位乾淨的工人先跑去洗澡了。」

蘇格拉底看了看其他的學生,
所有的學生似乎都同意這個答案。

只見蘇格拉底慢條斯理地說:
「這個答案也是錯的。
兩個人同時從又老又舊的破煙囪裡爬出來,
怎麼可能一個是乾淨的,
而另一個是髒的呢?
這就叫做不合邏輯,
也就是詭辯中的邏輯錯誤。」

學生們又向蘇格拉底請教:
「老師,應該怎樣看待詭辯的作用呢?」

蘇格拉底回答:

「會說的不如會聽的。

詭辯有效,但有限。

巧詐不如拙誠,千般巧計不如本份為人。」

Reference: http://www.cmoney.tw/notes/note-detail.aspx?nid=57994