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/