问:
My code is not working after dataGridView1.Rows.Clear() until end
My code is not working as I expected and I give the question to last days but I only checked after 2 days and I suppose my chance is gone to being answered. If that's wrong I'm asked second time excuse me well.

I have this weird going on to my codes with my visual studio pro. There are no error messages of disconnected loops. It seems like I give up to check something wrong all files of my point of sales project.

And I've given to updateb() and invoice(). So it's better off up like all codes in my specific file. So up like this.

```<code>using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace superpos3
{
    public partial class salesn : Form
    {
        public salesn()
        {
            InitializeComponent();
        }

       public static int totalPrice = 0;
        public static int payment = 0;
        public static int balance = 0;

        MySqlConnection con = new MySqlConnection("server= localhost; database =superpos;  username= root; password=; ");

        public void invoice()
        {

            con.Open();
            string query = "select max(id) from salesmain ";
            MySqlCommand cmd2 = new MySqlCommand(query, con);
            MySqlDataReader dr;
            dr = cmd2.ExecuteReader();
            if (dr.Read())
            {
                string val = dr[0].ToString();
                if (val == "")
                {
                    lbinvoice.Text = "1";

                }
                else
                {
                    int a;

                    a = int.Parse(dr[0].ToString());
                    a = a + 1;
                    lbinvoice.Text = a.ToString();

                }
                con.Close();
            }

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtno_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txtqty.Enabled = true;
                txtqty.Focus();
            }
        }

        private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {

                try
                {

                    string txt = "select * from products where id='" + txtno.Text + "'";
                    MySqlCommand cmd = new MySqlCommand(txt, con);
                    con.Open();
                    MySqlDataReader r = cmd.ExecuteReader();
                    while (r.Read())
                    {
                        int price = int.Parse(txtqty.Text.ToString()) * int.Parse(r[4].ToString());
                        totalPrice = totalPrice + price;
                        //discount
                        // totalPrice = totalPrice - totalPrice* Payment.discount/100;

                        dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);

                    }
                    lbitems.Text = " " + (dataGridView1.RowCount - 1) + "";
                    lbtotal.Text = " " + totalPrice + " ";

                    con.Close();

                }

                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "Error From Database");
                }

                txtno.Focus();
                txtno.Clear();

                txtqty.Enabled = false;
                txtqty.Clear();

            }

        }

        private void txtqty_TextChanged(object sender, EventArgs e)
        {

        }
        private string name;

        public string Staffname
        {
            get { return name; }
            set { name = value; }

        }

      public void updatedb()
        {

            for (int row = 0; row < dataGridView1.Rows.Count; row++)
            {

                string itmno = dataGridView1.Rows[row].Cells[1].Value.ToString();
                string itmqty = dataGridView1.Rows[row].Cells[3].Value.ToString();

                string t = "select * from products where id= '"+ itmno + "'";

                string oldqty = "", newqty = "";

                Connnew.DbSearch(t);

                while (Connnew.dr.Read())
                {

                    oldqty = Connnew.dr[5].ToString();
                    newqty = (int.Parse(oldqty) - int.Parse(itmqty)).ToString();
                }

                string t2 = "update products SET qty = '" + newqty + "' WHERE id = '" + itmno + "'";
                //t2 = t2.Replace("{0}", itmno);
                //t2 = t2.Replace("{2}", newqty);
                Connnew.DbUpdate(t2);
            }

        }

        private void salesn_Load(object sender, EventArgs e)
        {
            label6.Text = Staffname;
            lbldate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            lbltime.Text = DateTime.Now.ToShortTimeString();

            invoice();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,grosstotal)values(@saleid,@productname,@qty,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[4].Value);

                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,cashername,qty,grosstotal)values(@id,@date,@time,@cashername,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@cashername", label6.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();
                   int x = cmd.ExecuteNonQuery();
                   int y = cmd1.ExecuteNonQuery();

                    MessageBox.Show("Record added ..........");
                    updatedb();

             //until here everything worked fine but if additionally given below codes not wroking
               even the updatedb().

                    dataGridView1.Rows.Clear();
                    lbtotal.Text = "0";
                    lbitems.Text = "0";
                    txtno.Focus();
                    totalPrice = 0;

                    con.Close();
                    invoice();

                }
               }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }

            finally
            {
                con.Close();
            }
           }

        private void button2_Click(object sender, EventArgs e)
        {
            pay p = new pay();
            p.Show();
        }

        private void label6_Click(object sender, EventArgs e)
        {

        }
    }
}
</code>```

And I'm seeing everything is fine and still not find the issue of those.

And the connected with above related to Connnew.DbSearch(t) that "Connnew" is like:

```<code>using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace superpos3
{
    class Connnew
    {

        public static MySqlConnection con = new MySqlConnection("server= localhost; database =superpos; username= root; password=; ");
        public static MySqlCommand poscmd = new MySqlCommand();
        public static MySqlDataReader dr;

        public static void DbSearch(string txt)
        {

            con.Close();
            poscmd.Connection = con;
            poscmd.CommandText = txt;
            con.Open();
            dr = poscmd.ExecuteReader();
        }

        public static void DbUpdate(string txt)
        {
            con.Close();
            poscmd.Connection = con;
            poscmd.CommandText = txt;
            con.Open();
            poscmd.ExecuteNonQuery();
        }
    }
}
</code>```

I couldn't display the picture wholly screenshot or there is no permission here whatever. Please click down the below links.

please watch the sales window here

then please watch this one to know whats not work

Please let me know what is here the issue of the structure of codes or what is really going wrong...............(this question is ended and updated my question below)

I checked all but except the form1.cs file are irrelevant of the problem here. So additionally for here:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace superpos3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            progressBar1.Value = progressBar1.Value + 1;
            if (progressBar1.Value >= 100)
            {
                Login In = new Login();
                this.Hide();
                In.Show();

                timer1.Enabled = true;
                progressBar1.Visible = false;
                timer1.Enabled = false;
            }
        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }
    }
}
</code>```

答:
I've just deleted catch block and seen this error on the line below.

```<code>`string itmno = `dataGridView1.Rows[row].Cells[1].Value.ToString();`

The error is:System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=superpos3
  StackTrace:
   at superpos3.salesn.updatedb() in D:\superpos3\superpos3\superpos3\salesn.cs:line 174
   at superpos3.salesn.button1_Click(Object sender, EventArgs e) in D:\superpos3\superpos3\superpos3\salesn.cs:line 258
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at superpos3.Program.Main() in D:\superpos3\superpos3\superpos3\Program.cs:line 19
</code>```

sorry I've missed the info here:
Please watch the sales window here

then please watch this one to know whats not work

Body:
My code is not working as I expected and I give the question to last days but I only checked after 2 days and I suppose my chance is gone to being answered. If that's wrong I'm asked second time excuse me well.

I have this weird going on to my codes with my visual studio pro. There are no error messages of disconnected loops. It seems like I give up to check something wrong all files of my point of sales project.

And I've given to updateb() and invoice(). So it's better off up like all codes in my specific file. So up like this.

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace superpos3
{
    public partial class salesn : Form
    {
        public salesn()
        {
            InitializeComponent();
        }

       public static int totalPrice = 0;
        public static int payment = 0;
        public static int balance = 0;

        MySqlConnection con = new MySqlConnection("server= localhost; database =superpos;  username= root; password=; ");

        public void invoice()
        {

            con.Open();
            string query = "select max(id) from salesmain ";
            MySqlCommand cmd2 = new MySqlCommand(query, con);
            MySqlDataReader dr;
            dr = cmd2.ExecuteReader();
            if (dr.Read())
            {
                string val = dr[0].ToString();
                if (val == "")
                {
                    lbinvoice.Text = "1";

                }
                else
                {
                    int a;

                    a = int.Parse(dr[0].ToString());
                    a = a + 1;
                    lbinvoice.Text = a.ToString();

                }
                con.Close();
            }

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtno_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txtqty.Enabled = true;
                txtqty.Focus();
            }
        }

        private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {

                try
                {

                    string txt = "select * from products where id='" + txtno.Text + "'";
                    MySqlCommand cmd = new MySqlCommand(txt, con);
                    con.Open();
                    MySqlDataReader r = cmd.ExecuteReader();
                    while (r.Read())
                    {
                        int price = int.Parse(txtqty.Text.ToString()) * int.Parse(r[4].ToString());
                        totalPrice = totalPrice + price;
                        //discount
                        // totalPrice = totalPrice - totalPrice* Payment.discount/100;

                        dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);

                    }
                    lbitems.Text = " " + (dataGridView1.RowCount - 1) + "";
                    lbtotal.Text = " " + totalPrice + " ";

                    con.Close();

                }

                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "Error From Database");
                }

                txtno.Focus();
                txtno.Clear();

                txtqty.Enabled = false;
                txtqty.Clear();

            }

        }

        private void txtqty_TextChanged(object sender, EventArgs e)
        {

        }
        private string name;

        public string Staffname
        {
            get { return name; }
            set { name = value; }

        }

      public void updatedb()
        {

            for (int row = 0; row < dataGridView1.Rows.Count; row++)
            {

                string itmno = dataGridView1.Rows[row].Cells[1].Value.ToString();
                string itmqty = dataGridView1.Rows[row].Cells[3].Value.ToString();

                string t = "select * from products where id= '"+ itmno + "'";

                string oldqty = "", newqty = "";

                Connnew.DbSearch(t);

                while (Connnew.dr.Read())
                {

                    oldqty = Connnew.dr[5].ToString();
                    newqty = (int.Parse(oldqty) - int.Parse(itmqty)).ToString();
                }

                string t2 = "update products SET qty = '" + newqty + "' WHERE id = '" + itmno + "'";
                //t2 = t2.Replace("{0}", itmno);
                //t2 = t2.Replace("{2}", newqty);
                Connnew.DbUpdate(t2);
            }

        }

        private void salesn_Load(object sender, EventArgs e)
        {
            label6.Text = Staffname;
            lbldate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            lbltime.Text = DateTime.Now.ToShortTimeString();

            invoice();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,grosstotal)values(@saleid,@productname,@qty,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[4].Value);

                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,cashername,qty,grosstotal)values(@id,@date,@time,@cashername,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@cashername", label6.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();
                   int x = cmd.ExecuteNonQuery();
                   int y = cmd1.ExecuteNonQuery();

                    MessageBox.Show("Record added ..........");
                    updatedb();

             //until here everything worked fine but if additionally given below codes not wroking
               even the updatedb().

                    dataGridView1.Rows.Clear();
                    lbtotal.Text = "0";
                    lbitems.Text = "0";
                    txtno.Focus();
                    totalPrice = 0;

                    con.Close();
                    invoice();

                }
               }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }

            finally
            {
                con.Close();
            }
           }

        private void button2_Click(object sender, EventArgs e)
        {
            pay p = new pay();
            p.Show();
        }

        private void label6_Click(object sender, EventArgs e)
        {

        }
    }
}

And I'm seeing everything is fine and still not find the issue of those.

And the connected with above related to Connnew.DbSearch(t) that "Connnew" is like:

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace superpos3
{
    class Connnew
    {

        public static MySqlConnection con = new MySqlConnection("server= localhost; database =superpos; username= root; password=; ");
        public static MySqlCommand poscmd = new MySqlCommand();
        public static MySqlDataReader dr;

        public static void DbSearch(string txt)
        {

            con.Close();
            poscmd.Connection = con;
            poscmd.CommandText = txt;
            con.Open();
            dr = poscmd.ExecuteReader();
        }

        public static void DbUpdate(string txt)
        {
            con.Close();
            poscmd.Connection = con;
            poscmd.CommandText = txt;
            con.Open();
            poscmd.ExecuteNonQuery();
        }
    }
}

I couldn't display the picture wholly screenshot or there is no permission here whatever. Please click down the below links.

please watch the sales window here

then please watch this one to know whats not work

Please let me know what is here the issue of the structure of codes or what is really going wrong...............(this question is ended and updated my question below)

I checked all but except the form1.cs file are irrelevant of the problem here. So additionally for here:

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

namespace superpos3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            progressBar1.Value = progressBar1.Value + 1;
            if (progressBar1.Value >= 100)
            {
                Login In = new Login();
                this.Hide();
                In.Show();

                timer1.Enabled = true;
                progressBar1.Visible = false;
                timer1.Enabled = false;
            }
        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }
    }
}

Body:
I've just deleted catch block and seen this error on the line below.

`string itmno = `dataGridView1.Rows[row].Cells[1].Value.ToString();`

The error is:System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=superpos3
  StackTrace:
   at superpos3.salesn.updatedb() in D:\superpos3\superpos3\superpos3\salesn.cs:line 174
   at superpos3.salesn.button1_Click(Object sender, EventArgs e) in D:\superpos3\superpos3\superpos3\salesn.cs:line 258
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at superpos3.Program.Main() in D:\superpos3\superpos3\superpos3\Program.cs:line 19

sorry I've missed the info here:
Please watch the sales window here

then please watch this one to know whats not work


来源: stackexchange

问:
Flutter Emulator Error Connecting to Service Protocol
I am having an Issue with Flutter in Android studio, where whenever I run my flutter app, it will print this error; "Error connecting to the service protocol: HttpException: Connection closed before full header was received, uri = http://127.0.0.1:53305/9So9Wn564F4=/ws" , and it will "disconnect" from the app in the emulator.
The app will still run, but I can't use functions like Hot Reload.

I am on a Windows machine, and Flutter Doctor does not indicate any errors.
I have tried to read up on similar issues on github posts, but I have been unable to resolve the problem.

Do any of you guys have any ideas on how to solve this issue?

The problem does not occur when running on an actual device, only in the emulator.

答: For me it was caused by flutter_facebook_login plugin causing issue i removed it and i could afford to remove facebook login option but in your case you can try different version of flutter_facebook_login or you can use different plugin for loggin in using facebook.</p>

ContentLicense: CC BY-SA 4.0


问:
WPF Datagrid bind data list to a template column combobox
I've been searching for hours on how to bind data to combobox in a datagrid template column. I found some in the site but nothing seems to work. Here's what I've done so far:

```<code>public partial class CashReceipt : UserControl
    {
        private ObservableCollection<CashItem> itemsList;
        private ObservableCollection<string> accounts;
        public CashReceipt()
        {
            InitializeComponent();

            itemsList = new ObservableCollection<CashItem>();
            accounts = new ObservableCollection<string>()
            {
                "5710",
                "6010",
                "6510",
                "7010"
            };

            for (int i = 0; i < 5; ++i)
            {
                CashItem item = new CashItem();
                itemsList.Add(item);
            }

            clDatagrid.ItemsSource = itemsList;
        }
    }

    public struct CashItem
    {
        public string account { get; set; }
        public string description { get; set; }
        public decimal amount { get; set; }
    }
}
</code>```

The XAML is

```<code><UserControl x:Class="CashLedgerApp.CashReceipt"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:CashLedgerApp"
             mc:Ignorable="d"
             MinHeight="320" HorizontalAlignment="Stretch">
    <UserControl.Resources>
        <CollectionViewSource x:Key="AccountsList" Source="{Binding Path=accounts}"/>
    </UserControl.Resources>
    <Border Margin="100,20" BorderBrush="gray" BorderThickness="0.5">
        <Grid Background="White">
            <DataGrid x:Name="clDatagrid" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="8" Margin="10,0" VerticalAlignment="Stretch" MinHeight="30" AutoGenerateColumns="False" RowHeaderWidth="0" IsReadOnly="False" CanUserAddRows="True">
                <DataGrid.Resources>
                    <Style BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="{x:Type DataGridColumnHeader}">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="Height" Value="30"/>
                        <Setter Property="Background" Value="Black"/>
                        <Setter Property="Foreground" Value="White"/>
                        <Setter Property="BorderBrush" Value="White"/>
                        <Setter Property="BorderThickness" Value="0,0,1,0"/>
                    </Style>
                </DataGrid.Resources>
                <DataGrid.Columns>
                    <!--<DataGridComboBoxColumn x:Name="clAccount" Header="Compte No" Width="1*" SelectedValuePath="{Binding account}" SelectedValueBinding="{Binding Path=account}"/>-->
                    <DataGridTemplateColumn Header="Compte No" Width="1*">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ComboBox ItemsSource="{Binding Source={StaticResource AccountsList}}"
                                          SelectedItem="{Binding account}"
                                          DisplayMemberPath="account"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTextColumn Header="Description" Width="3*" Binding="{Binding description}"/>
                    <DataGridTextColumn Header="Montant" Width="1.5*" Binding="{Binding amount}">
                        <DataGridTextColumn.HeaderStyle>
                            <Style TargetType="DataGridColumnHeader">
                                <Setter Property="Background" Value="Black"/>
                                <Setter Property="Foreground" Value="White"/>
                                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                                <Setter Property="BorderThickness" Value="0"/>
                            </Style>
                        </DataGridTextColumn.HeaderStyle>
                    </DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Border>
</UserControl>
</code>```

When I execute this program, the combobox in the template column is always empty. The data in the accounts list is just a sample to make things work. I'll use data from database in the final version of the code. But I need to make it work first.
Thanks.

UPDATE
I made changes as you suggested @ASh, here is the C# and XAML (I added some data to the itemList collection, as expected, those data are displayed in the grid but the ComboBox in the DataGridTemplateColumn are still empty):

```<code>public partial class CashReceipt : UserControl
    {
        public ObservableCollection<CashItem> itemsList;
        public ObservableCollection<string> Accounts;
        public CashReceipt()
        {
            InitializeComponent();

            itemsList = new ObservableCollection<CashItem>();
            Accounts = new ObservableCollection<string>()
            {
                "5710",
                "6010",
                "6510",
                "7010"
            };

            for (int i = 0; i < 5; ++i)
            {
                CashItem item = new CashItem();
                item.description = "Achats";
                item.amount = 250000;
                itemsList.Add(item);
            }

            clDatagrid.ItemsSource = itemsList;
        }
    }

    public struct CashItem
    {
        public string account { get; set; }
        public string description { get; set; }
        public decimal amount { get; set; }
    }

<UserControl x:Class="CashLedgerApp.CashReceipt"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:CashLedgerApp"
             mc:Ignorable="d"
             MinHeight="320" HorizontalAlignment="Stretch">
    <UserControl.Resources>
        <CollectionViewSource x:Key="AccountsList" Source="{Binding Path=Accounts, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    </UserControl.Resources>
    <Border Margin="100,20" BorderBrush="gray" BorderThickness="0.5">
        <Grid Background="White">
            <DataGrid x:Name="clDatagrid" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="8" Margin="10,0" VerticalAlignment="Stretch" MinHeight="30" AutoGenerateColumns="False" RowHeaderWidth="0" IsReadOnly="False" CanUserAddRows="True">
                <DataGrid.Resources>
                    <Style BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="{x:Type DataGridColumnHeader}">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="Height" Value="30"/>
                        <Setter Property="Background" Value="Black"/>
                        <Setter Property="Foreground" Value="White"/>
                        <Setter Property="BorderBrush" Value="White"/>
                        <Setter Property="BorderThickness" Value="0,0,1,0"/>
                    </Style>
                </DataGrid.Resources>
                <DataGrid.Columns>
                    <DataGridTemplateColumn Header="Compte No" Width="1*">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ComboBox ItemsSource="{Binding Source={StaticResource AccountsList}}"
                                          SelectedItem="{Binding account}"
                                          DisplayMemberPath="account"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTextColumn Header="Description" Width="3*" Binding="{Binding description}"/>
                    <DataGridTextColumn Header="Montant" Width="1.5*" Binding="{Binding amount}">
                        <DataGridTextColumn.HeaderStyle>
                            <Style TargetType="DataGridColumnHeader">
                                <Setter Property="Background" Value="Black"/>
                                <Setter Property="Foreground" Value="White"/>
                                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                                <Setter Property="BorderThickness" Value="0"/>
                            </Style>
                        </DataGridTextColumn.HeaderStyle>
                    </DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Border>
</UserControl>
</code>```

I might have missed something I think but can't figure out what.

答:
Binding {Binding Path=accounts} will work if you make accounts a public property (currently it is a private field)

```<code>public ObservableCollection<string> accounts { get; private set; }
</code>```

also naming conventions suggest it should become Accounts (and {Binding Path=Accounts})

additionally simple Binding searches properties in DataContext, but in your case Accounts is a property of UserControl itself, so it is necessary to change source of Binding:

```<code><CollectionViewSource x:Key="AccountsList"
                      Source="{Binding Path=Accounts, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</code>```

Body:
I've been searching for hours on how to bind data to combobox in a datagrid template column. I found some in the site but nothing seems to work. Here's what I've done so far:

public partial class CashReceipt : UserControl
    {
        private ObservableCollection<CashItem> itemsList;
        private ObservableCollection<string> accounts;
        public CashReceipt()
        {
            InitializeComponent();

            itemsList = new ObservableCollection<CashItem>();
            accounts = new ObservableCollection<string>()
            {
                "5710",
                "6010",
                "6510",
                "7010"
            };

            for (int i = 0; i < 5; ++i)
            {
                CashItem item = new CashItem();
                itemsList.Add(item);
            }

            clDatagrid.ItemsSource = itemsList;
        }
    }

    public struct CashItem
    {
        public string account { get; set; }
        public string description { get; set; }
        public decimal amount { get; set; }
    }
}

The XAML is

<UserControl x:Class="CashLedgerApp.CashReceipt"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:CashLedgerApp"
             mc:Ignorable="d"
             MinHeight="320" HorizontalAlignment="Stretch">
    <UserControl.Resources>
        <CollectionViewSource x:Key="AccountsList" Source="{Binding Path=accounts}"/>
    </UserControl.Resources>
    <Border Margin="100,20" BorderBrush="gray" BorderThickness="0.5">
        <Grid Background="White">
            <DataGrid x:Name="clDatagrid" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="8" Margin="10,0" VerticalAlignment="Stretch" MinHeight="30" AutoGenerateColumns="False" RowHeaderWidth="0" IsReadOnly="False" CanUserAddRows="True">
                <DataGrid.Resources>

                </DataGrid.Resources>
                <DataGrid.Columns>

                    <DataGridTemplateColumn Header="Compte No" Width="1*">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ComboBox ItemsSource="{Binding Source={StaticResource AccountsList}}"
                                          SelectedItem="{Binding account}"
                                          DisplayMemberPath="account"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTextColumn Header="Description" Width="3*" Binding="{Binding description}"/>
                    <DataGridTextColumn Header="Montant" Width="1.5*" Binding="{Binding amount}">
                        <DataGridTextColumn.HeaderStyle>

                        </DataGridTextColumn.HeaderStyle>
                    </DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Border>
</UserControl>

When I execute this program, the combobox in the template column is always empty. The data in the accounts list is just a sample to make things work. I'll use data from database in the final version of the code. But I need to make it work first.
Thanks.

UPDATE
I made changes as you suggested @ASh, here is the C# and XAML (I added some data to the itemList collection, as expected, those data are displayed in the grid but the ComboBox in the DataGridTemplateColumn are still empty):

public partial class CashReceipt : UserControl
    {
        public ObservableCollection<CashItem> itemsList;
        public ObservableCollection<string> Accounts;
        public CashReceipt()
        {
            InitializeComponent();

            itemsList = new ObservableCollection<CashItem>();
            Accounts = new ObservableCollection<string>()
            {
                "5710",
                "6010",
                "6510",
                "7010"
            };

            for (int i = 0; i < 5; ++i)
            {
                CashItem item = new CashItem();
                item.description = "Achats";
                item.amount = 250000;
                itemsList.Add(item);
            }

            clDatagrid.ItemsSource = itemsList;
        }
    }

    public struct CashItem
    {
        public string account { get; set; }
        public string description { get; set; }
        public decimal amount { get; set; }
    }

<UserControl x:Class="CashLedgerApp.CashReceipt"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:CashLedgerApp"
             mc:Ignorable="d"
             MinHeight="320" HorizontalAlignment="Stretch">
    <UserControl.Resources>
        <CollectionViewSource x:Key="AccountsList" Source="{Binding Path=Accounts, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    </UserControl.Resources>
    <Border Margin="100,20" BorderBrush="gray" BorderThickness="0.5">
        <Grid Background="White">
            <DataGrid x:Name="clDatagrid" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="8" Margin="10,0" VerticalAlignment="Stretch" MinHeight="30" AutoGenerateColumns="False" RowHeaderWidth="0" IsReadOnly="False" CanUserAddRows="True">
                <DataGrid.Resources>

                </DataGrid.Resources>
                <DataGrid.Columns>
                    <DataGridTemplateColumn Header="Compte No" Width="1*">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ComboBox ItemsSource="{Binding Source={StaticResource AccountsList}}"
                                          SelectedItem="{Binding account}"
                                          DisplayMemberPath="account"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTextColumn Header="Description" Width="3*" Binding="{Binding description}"/>
                    <DataGridTextColumn Header="Montant" Width="1.5*" Binding="{Binding amount}">
                        <DataGridTextColumn.HeaderStyle>

                        </DataGridTextColumn.HeaderStyle>
                    </DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Border>
</UserControl>

I might have missed something I think but can't figure out what.

Body:
Binding {Binding Path=accounts} will work if you make accounts a public property (currently it is a private field)

public ObservableCollection<string> accounts { get; private set; }

also naming conventions suggest it should become Accounts (and {Binding Path=Accounts})

additionally simple Binding searches properties in DataContext, but in your case Accounts is a property of UserControl itself, so it is necessary to change source of Binding:

<CollectionViewSource x:Key="AccountsList"
                      Source="{Binding Path=Accounts, RelativeSource={RelativeSource AncestorType=UserControl}}"/>


问:
The form of Plaintext in real number CKKS Encoding Microsoft SEAL
I wonder about the size and form of Plaintext in CKKS Encoding for real number, taking small N for example:

Input vector array = [1.1, 2.2]

N = 8, scale Delta = 2^2 = 4

Number of slot = N/2 = 4

Form of Plaintext:

ptx = [4.4 8.8 0.0 0.0] with size of N/2
or:

ptx = [4.4 8.8 0.0 0.0 | 0.0 0.0 0.0 0.0] with size of N
or:

ptx = [4.4 8.8 0.0 0.0 | 4.4 8.8 0.0 0.0] with size of N

Thank you for your help!

答:
I really appreciate your help. I was vague how to encode and encrypt a message vector into a ciphertext using CKKS scheme, which I cannot print out in SEAL code. Anyway, I wonder that:

Steps from 2 to 5 transform a N-size vector into a N-size NTT-form ciphertext.

What is different between doubling a vector of real numbers and a vector of complex numbers in step 1,

How can we map real & image parts of complex numbers into N/2 slots in step 2?

Please don't laugh at me if the question is stupid :). Thanks for your help.


问:
MySQL Python connector - Update not updating
I'm using MySQL in Python but my update function isn't updating the row and I can't understand the message error.

```<code>def atualizaCartelaTabela(campo,valor,jogador):
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        sql = """UPDATE Cartela
                SET %s = %s
                WHERE PONTOS = %s"""
        atualiza = (campo,valor,jogador)
        cursor.execute(sql,atualiza)
    except Error as e:
        print("Erro ao atualizar campos da tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

def atualizaCartelaTabela(campo,valor,jogador):
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        sql = """UPDATE Cartela
                SET %s = %s
                WHERE PONTOS = %s"""
        atualiza = (campo,valor,jogador)
        cursor.execute(sql,atualiza)
    except Error as e:
        print("Erro ao atualizar campos da tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

atualizaCartelaTabela('Um',2,'Jogador 1')
</code>```

The error I'm getting:

1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Um' = 2
WHERE PONTOS = 'Jogador 1'' at line 2

And, this is the function used to create the table(working):

```<code>def criaTabelaCartela():
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        cursor.execute("CREATE TABLE Cartela (PONTOS VARCHAR(10), Um int(2), Dois int(1), Tres int(1), Quatro int(1), Cinco int(1), Seis int(1), Full int(1), SequenciaBaixa int(1), Trinca int(1), Quadra int(1), SequenciaAlta int(1), Yahtzee int(1), PontuaçãoFinal int(1))")
        connection.commit()
    except Error as e:
        print("Erro ao criar tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
</code>```

答:
Looking at these 3 statements for what's causing the error:

```<code>sql = """UPDATE Cartela
        SET %s = %s
        WHERE PONTOS = %s"""
atualiza = (campo,valor,jogador)
cursor.execute(sql,atualiza)
</code>```

When you put SET X = "y" in the update query, the column name X cannot be parameterised. Only the values.

So the column name for campo should be substituted directly in the SQL string, not during execute - but note that this is UNSAFE. Change the first parameter to the {} notation for format and leave the values as %s so that they are parameters for execute():

```<code>sql = """UPDATE Cartela
        SET {} = %s
        WHERE PONTOS = %s""".format(campo)  # unsafe
atualiza = valor, jogador
cursor.execute(sql, atualiza)
</code>```

As a safety check, make sure that the value of campo is the name of one of the columns of the table, except PONTOS or any of the import key columns. Better to check that it's in a white-list of column that you want to allow updating.

Body:
I'm using MySQL in Python but my update function isn't updating the row and I can't understand the message error.

def atualizaCartelaTabela(campo,valor,jogador):
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        sql = """UPDATE Cartela
                SET %s = %s
                WHERE PONTOS = %s"""
        atualiza = (campo,valor,jogador)
        cursor.execute(sql,atualiza)
    except Error as e:
        print("Erro ao atualizar campos da tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

def atualizaCartelaTabela(campo,valor,jogador):
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        sql = """UPDATE Cartela
                SET %s = %s
                WHERE PONTOS = %s"""
        atualiza = (campo,valor,jogador)
        cursor.execute(sql,atualiza)
    except Error as e:
        print("Erro ao atualizar campos da tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

atualizaCartelaTabela('Um',2,'Jogador 1')

The error I'm getting:

1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Um' = 2
WHERE PONTOS = 'Jogador 1'' at line 2

And, this is the function used to create the table(working):

def criaTabelaCartela():
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        cursor.execute("CREATE TABLE Cartela (PONTOS VARCHAR(10), Um int(2), Dois int(1), Tres int(1), Quatro int(1), Cinco int(1), Seis int(1), Full int(1), SequenciaBaixa int(1), Trinca int(1), Quadra int(1), SequenciaAlta int(1), Yahtzee int(1), PontuaçãoFinal int(1))")
        connection.commit()
    except Error as e:
        print("Erro ao criar tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

Body:
Looking at these 3 statements for what's causing the error:

sql = """UPDATE Cartela
        SET %s = %s
        WHERE PONTOS = %s"""
atualiza = (campo,valor,jogador)
cursor.execute(sql,atualiza)

When you put SET X = "y" in the update query, the column name X cannot be parameterised. Only the values.

So the column name for campo should be substituted directly in the SQL string, not during execute - but note that this is UNSAFE. Change the first parameter to the {} notation for format and leave the values as %s so that they are parameters for execute():

sql = """UPDATE Cartela
        SET {} = %s
        WHERE PONTOS = %s""".format(campo)  # unsafe
atualiza = valor, jogador
cursor.execute(sql, atualiza)

As a safety check, make sure that the value of campo is the name of one of the columns of the table, except PONTOS or any of the import key columns. Better to check that it's in a white-list of column that you want to allow updating.


问:
Creating pipeline in sklearn with custom functions?
How to create sklearn pipeline with custom functions?
I have a two functions, one for cleaning data and second for building model.

```<code>def preprocess(df):
   ……………….
   # clean data
   return df_clean

def model(df_clean):
   …………………
   #split data train and test and build randomForest Model
   return model
</code>```

So I use FunctionTransformer and created pipeline

```<code>from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import FunctionTransformer

pipe = Pipeline([("preprocess", FunctionTransformer(preprocess)),("model",FunctionTransformer(model))])

pred = pipe.predict_proba(new_test_data)
print(pred)
</code>```

I know above is wrong, not sure how to work on, in the pipe I need to pass the training data first then, I have to pass new_test_data?

答:
you need to create your own class that inherits BaseEstimator, TransformerMixin of sklearn.

then specify your function in fit/transform/fit_transform / predict/predict_prob  etc functions of your own class.

Put customized functions in Sklearn pipeline

Body:
How to create sklearn pipeline with custom functions?
I have a two functions, one for cleaning data and second for building model.

def preprocess(df):
   ……………….
   # clean data
   return df_clean

def model(df_clean):
   …………………
   #split data train and test and build randomForest Model
   return model

So I use FunctionTransformer and created pipeline

from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import FunctionTransformer

pipe = Pipeline([("preprocess", FunctionTransformer(preprocess)),("model",FunctionTransformer(model))])

pred = pipe.predict_proba(new_test_data)
print(pred)

I know above is wrong, not sure how to work on, in the pipe I need to pass the training data first then, I have to pass new_test_data?


问:
TSQL Update Column based on other Column
I've below table with data,

```<code>    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    SET ANSI_PADDING ON
    GO

    CREATE TABLE [dbo].[tbl_Test](
        [Id1] [int] NOT NULL,
        [Id2] [int] NOT NULL,
        [id3] [int] NOT NULL,
        [D_OldValue] [varchar](100) NOT NULL,
        [R_Value] [varchar](100) NOT NULL,

     CONSTRAINT [PK_tbl_Test] PRIMARY KEY CLUSTERED
    (
        [Id1] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO

    SET ANSI_PADDING OFF
    GO

    USE [temporary_databases];
SET NOCOUNT ON;
SET XACT_ABORT ON;
GO

BEGIN TRANSACTION;
INSERT INTO [dbo].[tbl_Test]([Id1], [Id2], [id3], [D_OldValue], [R_Value])
SELECT 437, 163, 163, N'BW', N'Ford' UNION ALL
SELECT 493, 163, 163, N'BW', N'Stock' UNION ALL
SELECT 1224, 163, 163, N'BW', N'Wood' UNION ALL
SELECT 1225, 163, 163, N'BW', N'FRD' UNION ALL
SELECT 1232, 163, 163, N'BW', N'COW' UNION ALL
SELECT 1240, 163, 163, N'BW', N'FRD1' UNION ALL
SELECT 2160, 163, 163, N'BW', N'Log'
COMMIT;
RAISERROR (N'[dbo].[tbl_Test]: Insert Batch: 1.....Done!', 10, 1) WITH NOWAIT;
GO
</code>```

I've requirement in my excel as below

+------+-----+-----+------------+---------+------------+

```<code>| Id1  | Id2 | id3 | D_OldValue | R_Value | D_NewValue |

+------+-----+-----+------------+---------+------------+

|  437 | 163 | 163 | BW         | Ford    | BF         |

|  493 | 163 | 163 | BW         | Stock   | WS         |

| 1224 | 163 | 163 | BW         | Wood    | WS         |

| 1225 | 163 | 163 | BW         | FRD     | BF         |

| 1232 | 163 | 163 | BW         | COW     | WS         |

| 1240 | 163 | 163 | BW         | FRD1    | BF         |

| 2160 | 163 | 163 | BW         | Log     | WS         |

+------+-----+-----+------------+---------+------------+
</code>```

now I need to update D_OldValue column in (tbl_test) with D_NewValue
  (Excel Table) I've tried with simple Update query like
      Update tbl_Test set D_OldValue = 'BF' where D_OldValue = 'BW'  But it updates all BW to BF Final output should be

```<code>+------+-----+-----+------------+---------+
| Id1  | Id2 | id3 | D_OldValue | R_Value |
+------+-----+-----+------------+---------+
|  437 | 163 | 163 | BF         | Ford    |
|  493 | 163 | 163 | WS         | Stock   |
| 1224 | 163 | 163 | WS         | Wood    |
| 1225 | 163 | 163 | BF         | FRD     |
| 1232 | 163 | 163 | WS         | COW     |
| 1240 | 163 | 163 | BF         | FRD1    |
| 2160 | 163 | 163 | WS         | Log     |
+------+-----+-----+------------+---------+

Thanks
</code>```

答:
By using the below query all the rows will be updated. If you want to update particular rows, add where condition    </p>

```<code>Update tbl_Test set D_OldValue = D_NewValue
</code>```

Body:
I've below table with data,

    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    SET ANSI_PADDING ON
    GO

    CREATE TABLE [dbo].[tbl_Test](
        [Id1] [int] NOT NULL,
        [Id2] [int] NOT NULL,
        [id3] [int] NOT NULL,
        [D_OldValue] [varchar](100) NOT NULL,
        [R_Value] [varchar](100) NOT NULL,

     CONSTRAINT [PK_tbl_Test] PRIMARY KEY CLUSTERED
    (
        [Id1] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO

    SET ANSI_PADDING OFF
    GO

    USE [temporary_databases];
SET NOCOUNT ON;
SET XACT_ABORT ON;
GO

BEGIN TRANSACTION;
INSERT INTO [dbo].[tbl_Test]([Id1], [Id2], [id3], [D_OldValue], [R_Value])
SELECT 437, 163, 163, N'BW', N'Ford' UNION ALL
SELECT 493, 163, 163, N'BW', N'Stock' UNION ALL
SELECT 1224, 163, 163, N'BW', N'Wood' UNION ALL
SELECT 1225, 163, 163, N'BW', N'FRD' UNION ALL
SELECT 1232, 163, 163, N'BW', N'COW' UNION ALL
SELECT 1240, 163, 163, N'BW', N'FRD1' UNION ALL
SELECT 2160, 163, 163, N'BW', N'Log'
COMMIT;
RAISERROR (N'[dbo].[tbl_Test]: Insert Batch: 1.....Done!', 10, 1) WITH NOWAIT;
GO

I've requirement in my excel as below

+------+-----+-----+------------+---------+------------+

| Id1  | Id2 | id3 | D_OldValue | R_Value | D_NewValue |

+------+-----+-----+------------+---------+------------+

|  437 | 163 | 163 | BW         | Ford    | BF         |

|  493 | 163 | 163 | BW         | Stock   | WS         |

| 1224 | 163 | 163 | BW         | Wood    | WS         |

| 1225 | 163 | 163 | BW         | FRD     | BF         |

| 1232 | 163 | 163 | BW         | COW     | WS         |

| 1240 | 163 | 163 | BW         | FRD1    | BF         |

| 2160 | 163 | 163 | BW         | Log     | WS         |

+------+-----+-----+------------+---------+------------+

now I need to update D_OldValue column in (tbl_test) with D_NewValue
  (Excel Table) I've tried with simple Update query like
      Update tbl_Test set D_OldValue = 'BF' where D_OldValue = 'BW'  But it updates all BW to BF Final output should be

+------+-----+-----+------------+---------+
| Id1  | Id2 | id3 | D_OldValue | R_Value |
+------+-----+-----+------------+---------+
|  437 | 163 | 163 | BF         | Ford    |
|  493 | 163 | 163 | WS         | Stock   |
| 1224 | 163 | 163 | WS         | Wood    |
| 1225 | 163 | 163 | BF         | FRD     |
| 1232 | 163 | 163 | WS         | COW     |
| 1240 | 163 | 163 | BF         | FRD1    |
| 2160 | 163 | 163 | WS         | Log     |
+------+-----+-----+------------+---------+

Thanks

Body:
By using the below query all the rows will be updated. If you want to update particular rows, add where condition

Update tbl_Test set D_OldValue = D_NewValue


问:
Encode special characters with UTF-8 characters
I have a String Address: Mount Road (Back) [Contact-Ron] & give him the {data}
I need to use SAX parser and it doesn't parse special characters, we need to replace them with UTF-8 characters.
Example-- & is replaced with &amp.
Is there any way to replace special characters with their corresponding UTF-8 characters without individually writing replace code ?

答: Take a look at https://github.com/owasp/owasp-java-encoder. OWASP Java Encoder is easy to use and handles various safety issues. </p>


问:
How to populate form with JSON data using data store?
How to populate form with JSON data using data store? How are the textfields connected with store, model?

```<code>Ext.define('app.formStore', {
extend: 'Ext.data.Model',
fields: [
   {name: 'naziv', type:'string'},
   {name: 'oib', type:'int'},
   {name: 'email', type:'string'}
]
});

var myStore = Ext.create('Ext.data.Store', {
model: 'app.formStore',
proxy: {
    type: 'ajax',
    url : 'app/myJson.json',
    reader:{
        type:'json'
    }
},
autoLoad:true
});

Ext.onReady(function() {

var testForm = Ext.create('Ext.form.Panel', {
                    width: 500,
                    renderTo: Ext.getBody(),
                    title: 'testForm',
                    waitMsgTarget: true,
                    fieldDefaults: {
                        labelAlign: 'right',
                        labelWidth: 85,
                        msgTarget: 'side'
                    },
                    items: [{
                        xtype: 'fieldset',
                        title: 'Contact Information',
                        items: [{
                                xtype:'textfield',
                                fieldLabel: 'Name',
                                name: 'naziv'
                            }, {
                                xtype:'textfield',
                                fieldLabel: 'oib',
                                name: 'oib'
                            }, {
                                xtype:'textfield',
                                fieldLabel: 'mail',
                                name: 'email'
                        }]
                    }]

            });

    testForm.getForm().loadRecord(app.formStore);
 });
</code>```

JSON

```<code>[
    {"naziv":"Lisa", "oib":"2545898545", "email":"lisa@simpson.com"}
]
</code>```

答:
The field names of your model and form should match. Then you can load the form using loadRecord(). For example:

```<code>var record = Ext.create('XYZ',{
    name: 'Abc',
    email: 'abc@abc.com'
});
formpanel.getForm().loadRecord(record);
</code>```

or, get the values from already loaded store.

ContentLicense: CC BY-SA 3.0

Body:
How to populate form with JSON data using data store? How are the textfields connected with store, model?

Ext.define('app.formStore', {
extend: 'Ext.data.Model',
fields: [
   {name: 'naziv', type:'string'},
   {name: 'oib', type:'int'},
   {name: 'email', type:'string'}
]
});

var myStore = Ext.create('Ext.data.Store', {
model: 'app.formStore',
proxy: {
    type: 'ajax',
    url : 'app/myJson.json',
    reader:{
        type:'json'
    }
},
autoLoad:true
});

Ext.onReady(function() {

var testForm = Ext.create('Ext.form.Panel', {
                    width: 500,
                    renderTo: Ext.getBody(),
                    title: 'testForm',
                    waitMsgTarget: true,
                    fieldDefaults: {
                        labelAlign: 'right',
                        labelWidth: 85,
                        msgTarget: 'side'
                    },
                    items: [{
                        xtype: 'fieldset',
                        title: 'Contact Information',
                        items: [{
                                xtype:'textfield',
                                fieldLabel: 'Name',
                                name: 'naziv'
                            }, {
                                xtype:'textfield',
                                fieldLabel: 'oib',
                                name: 'oib'
                            }, {
                                xtype:'textfield',
                                fieldLabel: 'mail',
                                name: 'email'
                        }]
                    }]

            });

    testForm.getForm().loadRecord(app.formStore);
 });

JSON

[
    {"naziv":"Lisa", "oib":"2545898545", "email":"lisa@simpson.com"}
]

Body:
The field names of your model and form should match. Then you can load the form using loadRecord(). For example:

var record = Ext.create('XYZ',{
    name: 'Abc',
    email: 'abc@abc.com'
});
formpanel.getForm().loadRecord(record);

or, get the values from already loaded store.


问:
MSAL - Application can request permission even if it's not configured in 'API Permissions'
I have created a small .NET Core 3.1 console application using the MSAL library which requests scope api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope2

Custom API exposes two scopes

api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope1

api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope2

I have also configured another application named test-app in Azure Active Directory which represents my console application.

I have configured only one API permission (api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope1) for this application. My understanding is with this configuration in place client app will only be able to request for scope test1 and it won't allow test-app to request for scope2

Below is screenshot

This is my code:

```<code>//<PackageReference Include="Microsoft.Identity.Client" Version="4.13.0" />
namespace console_client
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Azure AD parameters
            var clientId = "dddeefa5-d95c-4931-a53d-2382deee27c3";
            var tenant = "-- MY TENANT ID--";
            var instance = "https://login.microsoftonline.com/";
            #endregion

            var client = PublicClientApplicationBuilder
                .Create(clientId)
                .WithDefaultRedirectUri()
                .WithAuthority($"{instance}{tenant}")
                .Build();

            List<string> scopes = new List<string>();

            try
            {
                // I was under impression that this call will throw as exception as
                // this app is requesting 'testscope2' which is not included in API Permissions
                // while configuring test-app in Azure Active Directory (dddeefa5-d95c-4931-a53d-2382deee27c3 )
                // But I was able to retrieve token back with testscope2 in it.
                scopes.Add("api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope2");
                var authenticationResult = client.AcquireTokenInteractive(scopes).ExecuteAsync().Result;
                Console.WriteLine($"Interactive Access token is : {authenticationResult.AccessToken}");
            }
            catch (Exception ex)
            {
                System.Console.WriteLine($"******* {ex.Message}");
            }
        }
    }
}
</code>```

Question

Am I missing anything? Why am I getting the access token back even if the app doesn't have permission configured?

Thanks

答:
TL;DR it is a feature.

With the v2 endpoint / MSAL, you can request for scopes that are not defined in your app manifest.
The ones in your app registration are the static permissions required by your application.
But your application can also request dynamic permissions at login time.
The user/admin would still need to consent to that of course, an app won't get a permission without consent.

Your app seems to be a single-tenant app so this doesn't really make a difference for you.
It is mainly for multi-tenant SaaS applications that can require the minimum needed permissions in the app registration/manifest, and then request more permissions for opt-in features as they are needed.

By the way, if you want to use the permissions defined in your app registration, you can request a special scope: api://55a047a1-a0d1-4b6b-9896-751a848e1e06/.default (your app ID URI or client id + "/.default").
This will make AAD look at your app registration to decide which permissions to check consent for.

Body:
I have created a small .NET Core 3.1 console application using the MSAL library which requests scope api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope2

Custom API exposes two scopes

api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope1

api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope2

I have also configured another application named test-app in Azure Active Directory which represents my console application.

I have configured only one API permission (api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope1) for this application. My understanding is with this configuration in place client app will only be able to request for scope test1 and it won't allow test-app to request for scope2

Below is screenshot

This is my code:

//<PackageReference Include="Microsoft.Identity.Client" Version="4.13.0" />
namespace console_client
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Azure AD parameters
            var clientId = "dddeefa5-d95c-4931-a53d-2382deee27c3";
            var tenant = "-- MY TENANT ID--";
            var instance = "https://login.microsoftonline.com/";
            #endregion

            var client = PublicClientApplicationBuilder
                .Create(clientId)
                .WithDefaultRedirectUri()
                .WithAuthority($"{instance}{tenant}")
                .Build();

            List<string> scopes = new List<string>();

            try
            {
                // I was under impression that this call will throw as exception as
                // this app is requesting 'testscope2' which is not included in API Permissions
                // while configuring test-app in Azure Active Directory (dddeefa5-d95c-4931-a53d-2382deee27c3 )
                // But I was able to retrieve token back with testscope2 in it.
                scopes.Add("api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope2");
                var authenticationResult = client.AcquireTokenInteractive(scopes).ExecuteAsync().Result;
                Console.WriteLine($"Interactive Access token is : {authenticationResult.AccessToken}");
            }
            catch (Exception ex)
            {
                System.Console.WriteLine($"******* {ex.Message}");
            }
        }
    }
}

Question

Am I missing anything? Why am I getting the access token back even if the app doesn't have permission configured?

Thanks