问:
How to retrieve a value from key value pair in XML via SQL Query?
I have a column with name attributes in my database table which is a clob object storing XML data as below. Using SQL, I am trying to retrieve the values of key accountExpires which should give me the value of 123456789L as output.

I tried using nodes(Xquery) and CROSS APPLY etc but I am only fetching those which are typically in Value format like the IIQDisabled or accountFlags etc but I want to retrieve entry key and value pairs. Appreciate your help.

```<code><Attributes>
  <Map>
    <entry key="Division" value="TRAINING"/>
    <entry key="IIQDisabled">
      <value>
        <Boolean>true</Boolean>
      </value>
    </entry>
    <entry key="accountExpires" value="123456789L"/>
    <entry key="accountFlags">
      <value>
        <List>
          <String>Normal User Account</String>
          <String>User Account is Disabled</String>
        </List>
      </value>
    </entry>
    <entry key="department" value="LOYALTY CLUB"/>
    <entry key="distinguishedName" value="CN=Account02\,TM_Test02,OU=SailpointQA,OU=Users...."/>
    <entry key="employeeID" value="333223"/>
    <entry key="givenName" value="TM_Test02"/>
    <entry key="memberOf"/>
    <entry key="mobile" value="9"/>
    <entry key="sAMAccountName" value="TM_Test02.Account02"/>
    <entry key="sAMAccountType" value="805306368"/>
    <entry key="sn" value="Account02"/>
    <entry key="userAccountControl" value="514"/>
  </Map>
</Attributes>

select a.id as id
,pref.value('(@accountExpires)[1]', 'varchar(50)') as accountExpires
,pref.value('.', 'varchar(50)') as test
FROM (
select
         id,CONVERT(XML, attributes, 1) xmlCol
from [identityiq].[identityiq].[spt_work_item_archive]) a
CROSS APPLY xmlCol.nodes('//Attributes/Map') AS ApprovalItem(pref)
</code>```

Expected results :

```<code>id       accountExpires
-----------------
someid   123456789L
</code>```

But actually i am getting true Normal User Account  User Account is Disabled  if use pref.value('.', 'varchar(50)')  in the output as test column.

答:
From your own code I take this is SQL-Server. At least the syntax looks like this.

You can try this:

```<code>DECLARE @xml XML=
N'<Attributes>
  <Map>
    <entry key="Division" value="TRAINING"/>
    <entry key="IIQDisabled">
      <value>
        <Boolean>true</Boolean>
      </value>
    </entry>
    <entry key="accountExpires" value="123456789L"/>
    <entry key="accountFlags">
      <value>
        <List>
          <String>Normal User Account</String>
          <String>User Account is Disabled</String>
        </List>
      </value>
    </entry>
    <entry key="department" value="LOYALTY CLUB"/>
    <entry key="distinguishedName" value="CN=Account02\,TM_Test02,OU=SailpointQA,OU=Users...."/>
    <entry key="employeeID" value="333223"/>
    <entry key="givenName" value="TM_Test02"/>
    <entry key="memberOf"/>
    <entry key="mobile" value="9"/>
    <entry key="sAMAccountName" value="TM_Test02.Account02"/>
    <entry key="sAMAccountType" value="805306368"/>
    <entry key="sn" value="Account02"/>
    <entry key="userAccountControl" value="514"/>
  </Map>
</Attributes>';
</code>```

--The query

```<code>SELECT entr.value('@key','nvarchar(100)') AS AttrKey
      ,entr.value('@value','nvarchar(500)') AS AttrValue
      ,HasValueElement.value('local-name(.)','nvarchar(100)') AS ValueType
      ,HasValueElement.value('text()[1]','nvarchar(500)') AS ValueTypeValue
      ,IsAList.value('local-name(.)','nvarchar(100)') AS ListValueType
      ,IsAList.value('text()[1]','nvarchar(500)') AS ListValueValue

FROM @xml.nodes(N'/Attributes/Map/entry') A(entr)
OUTER APPLY A.entr.nodes(N'value/*') B(HasValueElement)
OUTER APPLY B.HasValueElement.nodes('*') C(IsAList);
</code>```

the result

```<code>+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| Division           | TRAINING                                            |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| IIQDisabled        | NULL                                                | Boolean | true |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| accountExpires     | 123456789L                                          |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| accountFlags       | NULL                                                | List    | NULL | String | Normal User Account      |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| accountFlags       | NULL                                                | List    | NULL | String | User Account is Disabled |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| department         | LOYALTY CLUB                                        |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| distinguishedName  | CN=Account02\,TM_Test02,OU=SailpointQA,OU=Users.... |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| employeeID         | 333223                                              |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| givenName          | TM_Test02                                           |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| memberOf           | NULL                                                |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| mobile             | 9                                                   |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| sAMAccountName     | TM_Test02.Account02                                 |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| sAMAccountType     | 805306368                                           |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| sn                 | Account02                                           |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| userAccountControl | 514                                                 |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
</code>```

Some explanation:

There are three kinds of data:

Simple key-value-pairs

Typed key-value-pairs

Typed list values

The query will use .nodes() to dive into all <entry> elements and return them as a derived table. The first OUTER APPLY will return addtional rows/columns in cases, where there is a <value> element below a given <entry>. This element might have a value (like the boolean "true"), or it might contain a typed list. The second OUTER APPLY dives - if this exists - into the sub-nodes of <value> and returns them as additional rows.

A Query like this would return it more in an EAV-style

```<code>SELECT entr.value('@key','nvarchar(100)') AS AttrKey
      ,COALESCE(entr.value('@value','nvarchar(500)'),HasValueElement.value('text()[1]','nvarchar(500)'),IsAList.value('text()[1]','nvarchar(500)')) AS AttrValue
      ,HasValueElement.value('local-name(.)','nvarchar(100)') AS ValueType
      ,IsAList.value('local-name(.)','nvarchar(100)') AS ListValueType

FROM @xml.nodes(N'/Attributes/Map/entry') A(entr)
OUTER APPLY A.entr.nodes(N'value/*') B(HasValueElement)
OUTER APPLY B.HasValueElement.nodes('*') C(IsAList);
</code>```

The result

```<code>+--------------------+-----------------------------------------------------+-----------+---------------+
| AttrKey            | AttrValue                                           | ValueType | ListValueType |
+--------------------+-----------------------------------------------------+-----------+---------------+
| Division           | TRAINING                                            |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| IIQDisabled        | true                                                | Boolean   |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| accountExpires     | 123456789L                                          |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| accountFlags       | Normal User Account                                 | List      | String        |
+--------------------+-----------------------------------------------------+-----------+---------------+
| accountFlags       | User Account is Disabled                            | List      | String        |
+--------------------+-----------------------------------------------------+-----------+---------------+
| department         | LOYALTY CLUB                                        |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| distinguishedName  | CN=Account02\,TM_Test02,OU=SailpointQA,OU=Users.... |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| employeeID         | 333223                                              |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| givenName          | TM_Test02                                           |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| memberOf           | NULL                                                |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| mobile             | 9                                                   |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| sAMAccountName     | TM_Test02.Account02                                 |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| sAMAccountType     | 805306368                                           |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| sn                 | Account02                                           |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| userAccountControl | 514                                                 |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
</code>```

Body:
I have a column with name attributes in my database table which is a clob object storing XML data as below. Using SQL, I am trying to retrieve the values of key accountExpires which should give me the value of 123456789L as output.

I tried using nodes(Xquery) and CROSS APPLY etc but I am only fetching those which are typically in Value format like the IIQDisabled or accountFlags etc but I want to retrieve entry key and value pairs. Appreciate your help.

<Attributes>
  <Map>
    <entry key="Division" value="TRAINING"/>
    <entry key="IIQDisabled">
      <value>
        <Boolean>true</Boolean>
      </value>
    </entry>
    <entry key="accountExpires" value="123456789L"/>
    <entry key="accountFlags">
      <value>
        <List>
          <String>Normal User Account</String>
          <String>User Account is Disabled</String>
        </List>
      </value>
    </entry>
    <entry key="department" value="LOYALTY CLUB"/>
    <entry key="distinguishedName" value="CN=Account02\,TM_Test02,OU=SailpointQA,OU=Users...."/>
    <entry key="employeeID" value="333223"/>
    <entry key="givenName" value="TM_Test02"/>
    <entry key="memberOf"/>
    <entry key="mobile" value="9"/>
    <entry key="sAMAccountName" value="TM_Test02.Account02"/>
    <entry key="sAMAccountType" value="805306368"/>
    <entry key="sn" value="Account02"/>
    <entry key="userAccountControl" value="514"/>
  </Map>
</Attributes>

select a.id as id
,pref.value('(@accountExpires)[1]', 'varchar(50)') as accountExpires
,pref.value('.', 'varchar(50)') as test
FROM (
select
         id,CONVERT(XML, attributes, 1) xmlCol
from [identityiq].[identityiq].[spt_work_item_archive]) a
CROSS APPLY xmlCol.nodes('//Attributes/Map') AS ApprovalItem(pref)

Expected results :

id       accountExpires
-----------------
someid   123456789L

But actually i am getting true Normal User Account  User Account is Disabled  if use pref.value('.', 'varchar(50)')  in the output as test column.

Body:
From your own code I take this is SQL-Server. At least the syntax looks like this.

You can try this:

DECLARE @xml XML=
N'<Attributes>
  <Map>
    <entry key="Division" value="TRAINING"/>
    <entry key="IIQDisabled">
      <value>
        <Boolean>true</Boolean>
      </value>
    </entry>
    <entry key="accountExpires" value="123456789L"/>
    <entry key="accountFlags">
      <value>
        <List>
          <String>Normal User Account</String>
          <String>User Account is Disabled</String>
        </List>
      </value>
    </entry>
    <entry key="department" value="LOYALTY CLUB"/>
    <entry key="distinguishedName" value="CN=Account02\,TM_Test02,OU=SailpointQA,OU=Users...."/>
    <entry key="employeeID" value="333223"/>
    <entry key="givenName" value="TM_Test02"/>
    <entry key="memberOf"/>
    <entry key="mobile" value="9"/>
    <entry key="sAMAccountName" value="TM_Test02.Account02"/>
    <entry key="sAMAccountType" value="805306368"/>
    <entry key="sn" value="Account02"/>
    <entry key="userAccountControl" value="514"/>
  </Map>
</Attributes>';

--The query

SELECT entr.value('@key','nvarchar(100)') AS AttrKey
      ,entr.value('@value','nvarchar(500)') AS AttrValue
      ,HasValueElement.value('local-name(.)','nvarchar(100)') AS ValueType
      ,HasValueElement.value('text()[1]','nvarchar(500)') AS ValueTypeValue
      ,IsAList.value('local-name(.)','nvarchar(100)') AS ListValueType
      ,IsAList.value('text()[1]','nvarchar(500)') AS ListValueValue

FROM @xml.nodes(N'/Attributes/Map/entry') A(entr)
OUTER APPLY A.entr.nodes(N'value/*') B(HasValueElement)
OUTER APPLY B.HasValueElement.nodes('*') C(IsAList);

the result

+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| Division           | TRAINING                                            |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| IIQDisabled        | NULL                                                | Boolean | true |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| accountExpires     | 123456789L                                          |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| accountFlags       | NULL                                                | List    | NULL | String | Normal User Account      |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| accountFlags       | NULL                                                | List    | NULL | String | User Account is Disabled |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| department         | LOYALTY CLUB                                        |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| distinguishedName  | CN=Account02\,TM_Test02,OU=SailpointQA,OU=Users.... |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| employeeID         | 333223                                              |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| givenName          | TM_Test02                                           |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| memberOf           | NULL                                                |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| mobile             | 9                                                   |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| sAMAccountName     | TM_Test02.Account02                                 |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| sAMAccountType     | 805306368                                           |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| sn                 | Account02                                           |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+
| userAccountControl | 514                                                 |         | NULL |        | NULL                     |
+--------------------+-----------------------------------------------------+---------+------+--------+--------------------------+

Some explanation:

There are three kinds of data:

Simple key-value-pairs

Typed key-value-pairs

Typed list values

The query will use .nodes() to dive into all <entry> elements and return them as a derived table. The first OUTER APPLY will return addtional rows/columns in cases, where there is a <value> element below a given <entry>. This element might have a value (like the boolean "true"), or it might contain a typed list. The second OUTER APPLY dives - if this exists - into the sub-nodes of <value> and returns them as additional rows.

A Query like this would return it more in an EAV-style

SELECT entr.value('@key','nvarchar(100)') AS AttrKey
      ,COALESCE(entr.value('@value','nvarchar(500)'),HasValueElement.value('text()[1]','nvarchar(500)'),IsAList.value('text()[1]','nvarchar(500)')) AS AttrValue
      ,HasValueElement.value('local-name(.)','nvarchar(100)') AS ValueType
      ,IsAList.value('local-name(.)','nvarchar(100)') AS ListValueType

FROM @xml.nodes(N'/Attributes/Map/entry') A(entr)
OUTER APPLY A.entr.nodes(N'value/*') B(HasValueElement)
OUTER APPLY B.HasValueElement.nodes('*') C(IsAList);

The result

+--------------------+-----------------------------------------------------+-----------+---------------+
| AttrKey            | AttrValue                                           | ValueType | ListValueType |
+--------------------+-----------------------------------------------------+-----------+---------------+
| Division           | TRAINING                                            |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| IIQDisabled        | true                                                | Boolean   |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| accountExpires     | 123456789L                                          |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| accountFlags       | Normal User Account                                 | List      | String        |
+--------------------+-----------------------------------------------------+-----------+---------------+
| accountFlags       | User Account is Disabled                            | List      | String        |
+--------------------+-----------------------------------------------------+-----------+---------------+
| department         | LOYALTY CLUB                                        |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| distinguishedName  | CN=Account02\,TM_Test02,OU=SailpointQA,OU=Users.... |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| employeeID         | 333223                                              |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| givenName          | TM_Test02                                           |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| memberOf           | NULL                                                |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| mobile             | 9                                                   |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| sAMAccountName     | TM_Test02.Account02                                 |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| sAMAccountType     | 805306368                                           |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| sn                 | Account02                                           |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+
| userAccountControl | 514                                                 |           |               |
+--------------------+-----------------------------------------------------+-----------+---------------+


来源: stackexchange

问:
sqlalchemy.exc.InterfaceError: <unprintable InterfaceError object>
I'm trying out Flask but I'm having the error sqlalchemy.exc.InterfaceError: <unprintable InterfaceError object> while submitting a wtforms. The model class is:

```<code> class Post(db.Model):
__tablename__ = 'blog_posts'
id = db.Column(db.Integer, unique=True, primary_key=True)
title = db.Column(db.String(50), unique=False)
content = db.Column(db.Text, unique=False)
user_id = db.Column(db.String, db.ForeignKey('users.username'))

@staticmethod
def post_new_entry(title, content, user_id):
    """ Post new entry to database """
    new_post = Post(title=title, content=content, user_id=user_id)
    db.session.add(new_post)
    db.session.commit()
    return new_post

def __repr__(self):
    return 'PostID {}: {} by {}'.format(self.id, self.title, self.user_id)
</code>```

For my Form, I have the following:

```<code>class PostForm(Form):
title = StringField('Title', validators=[DataRequired(), Length(10, 65)])
post_content = TextAreaField('Content', validators=[DataRequired(), Length(50, 500)])
submit = SubmitField('Publish Post')
</code>```

The route is:

```<code>@main.route('/new_post/', methods=['GET', 'POST'])
@login_required
def add_post():
    form = PostForm()
    if form.validate_on_submit():
        Post.post_new_entry(title=form.title.data,
                            content=form.post_content.data,
                            user_id=current_user)
        flash("Amazing stuff! Thanks for your submission.")
        return redirect(url_for('main.index'))
    return render_template('single.html', form=form)
</code>```

On my html, I'm importing the wtf.html page of the flask-bootstrap:

```<code>{{ wtf.quick_form(form) }}
</code>```

The form shows right but I get the above error on form submission. Any tip or idea on how to proceed would be helpful.

答: I have received a similar message when writing data from my application to a database. This is due to the fact that the data that is written from the application needs to have the same format as a defined in the database a db.Column(db.String()) data type cannot have a list as input for example, or any other form.data. You need to use ``str()``` in these cases to prevent this error.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying out Flask but I'm having the error sqlalchemy.exc.InterfaceError: <unprintable InterfaceError object> while submitting a wtforms. The model class is:

 class Post(db.Model):
__tablename__ = 'blog_posts'
id = db.Column(db.Integer, unique=True, primary_key=True)
title = db.Column(db.String(50), unique=False)
content = db.Column(db.Text, unique=False)
user_id = db.Column(db.String, db.ForeignKey('users.username'))

@staticmethod
def post_new_entry(title, content, user_id):
    """ Post new entry to database """
    new_post = Post(title=title, content=content, user_id=user_id)
    db.session.add(new_post)
    db.session.commit()
    return new_post

def __repr__(self):
    return 'PostID {}: {} by {}'.format(self.id, self.title, self.user_id)

For my Form, I have the following:

class PostForm(Form):
title = StringField('Title', validators=[DataRequired(), Length(10, 65)])
post_content = TextAreaField('Content', validators=[DataRequired(), Length(50, 500)])
submit = SubmitField('Publish Post')

The route is:

@main.route('/new_post/', methods=['GET', 'POST'])
@login_required
def add_post():
    form = PostForm()
    if form.validate_on_submit():
        Post.post_new_entry(title=form.title.data,
                            content=form.post_content.data,
                            user_id=current_user)
        flash("Amazing stuff! Thanks for your submission.")
        return redirect(url_for('main.index'))
    return render_template('single.html', form=form)

On my html, I'm importing the wtf.html page of the flask-bootstrap:

{{ wtf.quick_form(form) }}

The form shows right but I get the above error on form submission. Any tip or idea on how to proceed would be helpful.


问:
ASP.net prevent gridview row click in edit mode
I have some issue with ASP.net Gridview that I hope people here can help me.

Requirements

Gridview whole row to be clickable to open another page

In editing mode, can change table values through edititemtemplate textbox

Problem

Textbox selection causes the entire row click event to fire and prevents user from changing the textbox text. User can edit table value without opening different page.

ASP Page

```<code><asp:GridView ID="remarksGV1" runat="server" AllowPaging="true" DataKeyNames="REM_ID"
            OnRowDataBound="remarksGV1_RowDataBound" OnSelectedIndexChanged="remarksGV1_SelectedIndexChanged"
            OnRowEditing="remarksGV1_RowEditing"
            OnRowCancelingEdit="remarksGV1_RowCancelingEdit"
            OnRowUpdating="remarksGV1_RowUpdating"
            AutoPostBack="false"
            HeaderStyle-CssClass="thead-dark"
            CssClass="table table-striped thead-dark table-borderless table-hover border-0 hand"
            AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="No.">
                    <ItemTemplate>
                        <%# Container.DataItemIndex + 1 %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Title">
                    <ItemTemplate>
                        <asp:Label ID="titleLbl" runat="server" Text='<%# Bind("REM_TITLE") %>' />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="titleTB" runat="server" />
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="REM_DESC" HeaderText="Remarks Description" ReadOnly="true" />
                <asp:BoundField DataField="CREATE_DATE" DataFormatString="{0:d}" HeaderText="Date Created" ReadOnly="true" />
                <asp:BoundField DataField="UPD_DATE" DataFormatString="{0:d}" HeaderText="Last Updated" ReadOnly="true" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Button Text="Edit" ID="EditBtn" CssClass="btn-action" runat="server" CommandName="Edit" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:Button Text="Update" ID="UpdateBtn" CssClass="btn-action" runat="server" CommandName="Update" />
                        <asp:Button Text="Cancel" ID="CancelBtn" CssClass="btn-action" runat="server" CommandName="Cancel" />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
</code>```

Code behind

```<code>private void BindGrid()
    {
        Debug.WriteLine("BindGrid called");

        int proj_code = Int32.Parse(ViewState["proj_cd"].ToString());

        ProjectRepository remarksRepository = new ProjectRepository();
        var remarks = remarksRepository.GetRemarks(proj_code, proj_task_code, proj_stask1_cd, proj_stask2_cd);
        remarksGV1.DataSource = remarks;
        remarksGV1.DataBind();
    }

    protected void Unnamed_Click(object sender, EventArgs e)
    {
        Launch.PageEvent(this, (LinkButton)sender, ViewState["proj_cd"].ToString());
    }

    protected void remarksGV1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            switch (e.Row.RowType)
            {
                case DataControlRowType.Header:
                    //...
                    break;
                case DataControlRowType.DataRow:
                    e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
                    break;
            }
        }
        catch
        {
            //...throw
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox titleTB = (e.Row.FindControl("titleTB") as TextBox);

            int prj_cd = Int32.Parse(ViewState["proj_cd"].ToString());
            ProjectRepository repository = new ProjectRepository();
            var remarks = repository.GetRemarks(prj_cd, proj_task_code, proj_stask1_cd, proj_stask2_cd);
            Debug.WriteLine("Remarks Count: " + remarks.Count);
            TMS_PROJ_REMARK remark = remarks.First(x => x.REM_ID == Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "REM_ID")));

            if (titleTB != null)
            {
                titleTB.Text = remark.REM_TITLE;
            }
        }
    }

    protected void remarksGV1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int row = remarksGV1.SelectedIndex;
        long rem_id = (long)remarksGV1.DataKeys[row]["REM_ID"];
        Debug.WriteLine("REM ID: " + rem_id);

        Session["edit_remarks"] = true;
        Dictionary<string, string> pairs = new Dictionary<string, string>();
        pairs["rem_id"] = rem_id.ToString();
        pairs["proj_cd"] = ViewState["proj_cd"].ToString();
        Launch.ToPage(this, "Project_Remarks_In_2.aspx", pairs);
    }

    protected void btnAddRemarks_Click(object sender, EventArgs e)
    {
        Session["new_remarks"] = true;
        Dictionary<string, string> pairs = new Dictionary<string, string>();
        pairs["proj_cd"] = ViewState["proj_cd"].ToString();

        string url = "Project_Remarks_In_1.aspx";

        Launch.ToPage(this, url, pairs);
    }

    private void SetTitle()
    {
        ProjectRepository repository = new ProjectRepository();
        TMS_PROJ_MASTER project = repository.GetProject(Convert.ToInt32(ViewState["proj_cd"]));
        this.Title = "Remarks - " + project.PROJ_TITLE;
    }

    protected void remarksGV1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        remarksGV1.EditIndex = e.NewEditIndex;
        BindGrid();
    }

    protected void remarksGV1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        // Do stuff
        ProjectRepository repository = new ProjectRepository();
        GridViewRow row = remarksGV1.Rows[e.RowIndex];
        TextBox titleTB = (row.FindControl("titleTB") as TextBox);

        long rem_id = Convert.ToInt64(remarksGV1.DataKeys[e.RowIndex].Value);
        var db = new THPEntities();
        TMS_PROJ_REMARK remark = db.TMS_PROJ_REMARK
            .First(x => x.REM_ID == rem_id);
        remark.REM_TITLE = titleTB.Text;
        remark.UPD_DATE = DateTime.Now;
        db.SaveChanges();

        // Bind Grid
        remarksGV1.EditIndex = -1;
        BindGrid();
    }

    protected void remarksGV1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        remarksGV1.EditIndex = -1;
        BindGrid();
    }
</code>```

答:
I suggest in this part of your code, do not add the full line click when you edit the line (I have add one -if- to check for the edit).</p>

```<code> switch (e.Row.RowType)
            {
                case DataControlRowType.Header:
                    //...
                    break;
                case DataControlRowType.DataRow:
                    if((e.Row.RowState & DataControlRowState.Edit) != DataControlRowState.Edit)
                           e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
                    break;
            }
</code>```

Body:
I have some issue with ASP.net Gridview that I hope people here can help me.

Requirements

Gridview whole row to be clickable to open another page

In editing mode, can change table values through edititemtemplate textbox

Problem

Textbox selection causes the entire row click event to fire and prevents user from changing the textbox text. User can edit table value without opening different page.

ASP Page

<asp:GridView ID="remarksGV1" runat="server" AllowPaging="true" DataKeyNames="REM_ID"
            OnRowDataBound="remarksGV1_RowDataBound" OnSelectedIndexChanged="remarksGV1_SelectedIndexChanged"
            OnRowEditing="remarksGV1_RowEditing"
            OnRowCancelingEdit="remarksGV1_RowCancelingEdit"
            OnRowUpdating="remarksGV1_RowUpdating"
            AutoPostBack="false"
            HeaderStyle-CssClass="thead-dark"
            CssClass="table table-striped thead-dark table-borderless table-hover border-0 hand"
            AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="No.">
                    <ItemTemplate>
                        <%# Container.DataItemIndex + 1 %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Title">
                    <ItemTemplate>
                        <asp:Label ID="titleLbl" runat="server" Text='<%# Bind("REM_TITLE") %>' />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="titleTB" runat="server" />
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="REM_DESC" HeaderText="Remarks Description" ReadOnly="true" />
                <asp:BoundField DataField="CREATE_DATE" DataFormatString="{0:d}" HeaderText="Date Created" ReadOnly="true" />
                <asp:BoundField DataField="UPD_DATE" DataFormatString="{0:d}" HeaderText="Last Updated" ReadOnly="true" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Button Text="Edit" ID="EditBtn" CssClass="btn-action" runat="server" CommandName="Edit" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:Button Text="Update" ID="UpdateBtn" CssClass="btn-action" runat="server" CommandName="Update" />
                        <asp:Button Text="Cancel" ID="CancelBtn" CssClass="btn-action" runat="server" CommandName="Cancel" />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

Code behind

private void BindGrid()
    {
        Debug.WriteLine("BindGrid called");

        int proj_code = Int32.Parse(ViewState["proj_cd"].ToString());

        ProjectRepository remarksRepository = new ProjectRepository();
        var remarks = remarksRepository.GetRemarks(proj_code, proj_task_code, proj_stask1_cd, proj_stask2_cd);
        remarksGV1.DataSource = remarks;
        remarksGV1.DataBind();
    }

    protected void Unnamed_Click(object sender, EventArgs e)
    {
        Launch.PageEvent(this, (LinkButton)sender, ViewState["proj_cd"].ToString());
    }

    protected void remarksGV1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            switch (e.Row.RowType)
            {
                case DataControlRowType.Header:
                    //...
                    break;
                case DataControlRowType.DataRow:
                    e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
                    break;
            }
        }
        catch
        {
            //...throw
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox titleTB = (e.Row.FindControl("titleTB") as TextBox);

            int prj_cd = Int32.Parse(ViewState["proj_cd"].ToString());
            ProjectRepository repository = new ProjectRepository();
            var remarks = repository.GetRemarks(prj_cd, proj_task_code, proj_stask1_cd, proj_stask2_cd);
            Debug.WriteLine("Remarks Count: " + remarks.Count);
            TMS_PROJ_REMARK remark = remarks.First(x => x.REM_ID == Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "REM_ID")));

            if (titleTB != null)
            {
                titleTB.Text = remark.REM_TITLE;
            }
        }
    }

    protected void remarksGV1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int row = remarksGV1.SelectedIndex;
        long rem_id = (long)remarksGV1.DataKeys[row]["REM_ID"];
        Debug.WriteLine("REM ID: " + rem_id);

        Session["edit_remarks"] = true;
        Dictionary<string, string> pairs = new Dictionary<string, string>();
        pairs["rem_id"] = rem_id.ToString();
        pairs["proj_cd"] = ViewState["proj_cd"].ToString();
        Launch.ToPage(this, "Project_Remarks_In_2.aspx", pairs);
    }

    protected void btnAddRemarks_Click(object sender, EventArgs e)
    {
        Session["new_remarks"] = true;
        Dictionary<string, string> pairs = new Dictionary<string, string>();
        pairs["proj_cd"] = ViewState["proj_cd"].ToString();

        string url = "Project_Remarks_In_1.aspx";

        Launch.ToPage(this, url, pairs);
    }

    private void SetTitle()
    {
        ProjectRepository repository = new ProjectRepository();
        TMS_PROJ_MASTER project = repository.GetProject(Convert.ToInt32(ViewState["proj_cd"]));
        this.Title = "Remarks - " + project.PROJ_TITLE;
    }

    protected void remarksGV1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        remarksGV1.EditIndex = e.NewEditIndex;
        BindGrid();
    }

    protected void remarksGV1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        // Do stuff
        ProjectRepository repository = new ProjectRepository();
        GridViewRow row = remarksGV1.Rows[e.RowIndex];
        TextBox titleTB = (row.FindControl("titleTB") as TextBox);

        long rem_id = Convert.ToInt64(remarksGV1.DataKeys[e.RowIndex].Value);
        var db = new THPEntities();
        TMS_PROJ_REMARK remark = db.TMS_PROJ_REMARK
            .First(x => x.REM_ID == rem_id);
        remark.REM_TITLE = titleTB.Text;
        remark.UPD_DATE = DateTime.Now;
        db.SaveChanges();

        // Bind Grid
        remarksGV1.EditIndex = -1;
        BindGrid();
    }

    protected void remarksGV1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        remarksGV1.EditIndex = -1;
        BindGrid();
    }

Body:
I suggest in this part of your code, do not add the full line click when you edit the line (I have add one -if- to check for the edit).

 switch (e.Row.RowType)
            {
                case DataControlRowType.Header:
                    //...
                    break;
                case DataControlRowType.DataRow:
                    if((e.Row.RowState & DataControlRowState.Edit) != DataControlRowState.Edit)
                           e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
                    break;
            }


问:
TSQL Performance Issues with SYS tables
I'm running this script to get list of all objects which can use tables from my find list, this is raw list which later will be feed into sys.dm_sql_referenced_entities(Object). And I see super low performance, it's never finished, all tables have 2K rows max, is it because using SYSNAME data types maybe or something?

I see problem on that FindList join which takes 90% performance. I'm on production grade SQL Server 2016, where I never had any problems. There was dynamic SQL which produce this query, and I'm testing it now as a standalone script, my original join to find table was in first step, it's commented now, I played with different ways, results are same super slow (never finished). Used LEFT vs INNER join too to try, same thing. Appreciate you leads.

FindList table doesn't have any IDX, I think it won't help as I'm using LIKE on JOIN +  size is small (2K max). DB also small has total 100 objects in sys.modules

```<code>; WITH cte AS
(
    SELECT --TOP 2                     -- 100 rows
        mod.Definition,
        o.name ObjName,
        o.schema_id,
        sch.Name Schema_name,
        o.object_id,
        o.type ObjType,
        o.type_desc ObjTypeDesc
--       ,x.table_name --,
    FROM
        myDB.sys.sql_modules mod
--      INNER JOIN   (SELECT   TABLE_NAME FROM myDB.dbo.FindList  WHERE rn =1) x     ON    mod.Definition LIKE '%'+x.TABLE_NAME+' %'
    INNER JOIN
        myDB.sys.all_objects o ON o.object_id = mod.object_id
    INNER JOIN
        myDB.sys.schemas sch ON sch.schema_id = o.schema_id
    WHERE
        o.name LIKE '%'+'0'+'%'            -- this part from dynamic SQL
        OR '0'  = '0'
),  cte_table AS
(
    SELECT TABLE_NAME
    FROM myDB.dbo.FindList
    WHERE rn =1     -- 2000  rows
)
SELECT
    ROW_NUMBER() OVER ( ORDER BY (SELECT 1)) rowNum,
    mod.*,
    x.table_name
FROM
    cte mod
LEFT JOIN
    cte_table x ON mod.Definition LIKE '%' + x.TABLE_NAME + ' %'
</code>```

Estimated execution plan:

答:
Expressions like this are a performance killer:

```<code>mod.Definition LIKE '%' + x.TABLE_NAME + ' %'
</code>```

What you try to do could possible be included in:

```<code>sp_depends (Transact-SQL)
</code>```

sp_depends manual

ps: For more detailed answers you will need to provide a query that can execute on any blank system.  (included create table statements etc..)

Title: TSQL Performance Issues with SYS tables

Body:
I'm running this script to get list of all objects which can use tables from my find list, this is raw list which later will be feed into sys.dm_sql_referenced_entities(Object). And I see super low performance, it's never finished, all tables have 2K rows max, is it because using SYSNAME data types maybe or something?

I see problem on that FindList join which takes 90% performance. I'm on production grade SQL Server 2016, where I never had any problems. There was dynamic SQL which produce this query, and I'm testing it now as a standalone script, my original join to find table was in first step, it's commented now, I played with different ways, results are same super slow (never finished). Used LEFT vs INNER join too to try, same thing. Appreciate you leads.

FindList table doesn't have any IDX, I think it won't help as I'm using LIKE on JOIN +  size is small (2K max). DB also small has total 100 objects in sys.modules

; WITH cte AS
(
    SELECT --TOP 2                     -- 100 rows
        mod.Definition,
        o.name ObjName,
        o.schema_id,
        sch.Name Schema_name,
        o.object_id,
        o.type ObjType,
        o.type_desc ObjTypeDesc
--       ,x.table_name --,
    FROM
        myDB.sys.sql_modules mod
--      INNER JOIN   (SELECT   TABLE_NAME FROM myDB.dbo.FindList  WHERE rn =1) x     ON    mod.Definition LIKE '%'+x.TABLE_NAME+' %'
    INNER JOIN
        myDB.sys.all_objects o ON o.object_id = mod.object_id
    INNER JOIN
        myDB.sys.schemas sch ON sch.schema_id = o.schema_id
    WHERE
        o.name LIKE '%'+'0'+'%'            -- this part from dynamic SQL
        OR '0'  = '0'
),  cte_table AS
(
    SELECT TABLE_NAME
    FROM myDB.dbo.FindList
    WHERE rn =1     -- 2000  rows
)
SELECT
    ROW_NUMBER() OVER ( ORDER BY (SELECT 1)) rowNum,
    mod.*,
    x.table_name
FROM
    cte mod
LEFT JOIN
    cte_table x ON mod.Definition LIKE '%' + x.TABLE_NAME + ' %'

Estimated execution plan:

Body:
Expressions like this are a performance killer:

mod.Definition LIKE '%' + x.TABLE_NAME + ' %'

What you try to do could possible be included in:

sp_depends (Transact-SQL)

sp_depends manual

ps: For more detailed answers you will need to provide a query that can execute on any blank system.  (included create table statements etc..)


问:
Why isn't __bases__ accessible in the class body?
Class objects have a __bases__ (and a __base__) attribute:

```<code>>>> class Foo(object):
...     pass
...
>>> Foo.__bases__
(<class 'object'>,)
</code>```

Sadly, these attributes aren't accessible in the class body, which would be very convenient for accessing parent class attributes without having to hard-code the name:

```<code>class Foo:
    cls_attr = 3

class Bar(Foo):
    cls_attr = __base__.cls_attr + 2
    # throws NameError: name '__base__' is not defined
</code>```

Is there a reason why __bases__ and __base__ can't be accessed in the class body?

(To be clear, I'm asking if this is a conscious design decision. I'm not asking about the implementation; I know that __bases__ is a descriptor in type and that this descriptor can't be accessed until a class object has been created. I want to know why python doesn't create __bases__ as a local variable in the class body.)

答:
I am not answering as to why it was decided to be implemented the way it was, I'm answering why it wasn't implemented as a "local variable in the class body":

Simply because nothing in python is a local variable magically defined in the class body.  Python doesn't like names magically appearing out of nowhere.

Body:
Class objects have a __bases__ (and a __base__) attribute:

>>> class Foo(object):
...     pass
...
>>> Foo.__bases__
(<class 'object'>,)

Sadly, these attributes aren't accessible in the class body, which would be very convenient for accessing parent class attributes without having to hard-code the name:

class Foo:
    cls_attr = 3

class Bar(Foo):
    cls_attr = __base__.cls_attr + 2
    # throws NameError: name '__base__' is not defined

Is there a reason why __bases__ and __base__ can't be accessed in the class body?

(To be clear, I'm asking if this is a conscious design decision. I'm not asking about the implementation; I know that __bases__ is a descriptor in type and that this descriptor can't be accessed until a class object has been created. I want to know why python doesn't create __bases__ as a local variable in the class body.)


问:
Compare two images from DB and file
I want to compare an uploaded pic with all images in database , if it is matching then should display data with image , the compare is simple by converting each image to binary see this

I am using this code but its not working:

```<code>protected void CompareImages(object sender, EventArgs e)
{
    if (this.FileUpload1.HasFile)
    {
        Stream fs = FileUpload1.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(constr))
        {
            string sqlQuery = "SELECT * from [MostWanted] WHERE Photo = @FileName";

            using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
            {
                cmd.Parameters.AddWithValue("@FileName", Path.GetFileName(this.FileUpload1.PostedFile.FileName));
                conn.Open();
                Byte[] bytes2 = (Byte[])cmd.ExecuteScalar();
                conn.Close();
                if (bytes2 != null)
                {
                    if (bytes.Length == bytes2.Length)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Equal Images')", true);
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Images are not equal')", true);
                    }
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('File Not found in the table')", true);
                }
            }
        }
    }
}
</code>```

答:
Have column named data varbinary(max) to store the image file

Query statement need not have where condition

Remove the add parameter line. It works perfectly then, by comparing binary data alone

ContentLicense: CC BY-SA 3.0

Title: Compare two images from DB and file

Body:
I want to compare an uploaded pic with all images in database , if it is matching then should display data with image , the compare is simple by converting each image to binary see this

I am using this code but its not working:

protected void CompareImages(object sender, EventArgs e)
{
    if (this.FileUpload1.HasFile)
    {
        Stream fs = FileUpload1.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(constr))
        {
            string sqlQuery = "SELECT * from [MostWanted] WHERE Photo = @FileName";

            using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
            {
                cmd.Parameters.AddWithValue("@FileName", Path.GetFileName(this.FileUpload1.PostedFile.FileName));
                conn.Open();
                Byte[] bytes2 = (Byte[])cmd.ExecuteScalar();
                conn.Close();
                if (bytes2 != null)
                {
                    if (bytes.Length == bytes2.Length)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Equal Images')", true);
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Images are not equal')", true);
                    }
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('File Not found in the table')", true);
                }
            }
        }
    }
}


问:
Azure DevOps build pipeline for Angular and Failed to exec build script Node error
I am working with Azure DevOps CI/CD for Angular 7 project but it is failing with following at the time of building angular code:

Error: Npm failed with return code: 1

Going through the pipeline task log I found that Node is exiting with following error:

2019-05-27T06:57:25.6984762Z npm verb lifecycle fuse@7.1.0~build: CWD: D:\a\1\s\Client
  2019-05-27T06:57:25.6984945Z npm info lifecycle fuse@7.1.0~build: Failed to exec build script
  2019-05-27T06:57:25.6985117Z npm verb stack Error: fuse@7.1.0 build: node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --dev "--prod"
  2019-05-27T06:57:25.6985258Z npm verb stack Exit status 1
  2019-05-27T06:57:25.6985401Z npm verb stack     at EventEmitter. (C:\npm\prefix\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
  2019-05-27T06:57:25.6985577Z npm verb stack     at EventEmitter.emit (events.js:189:13)
  2019-05-27T06:57:25.6985721Z npm verb stack     at ChildProcess. (C:\npm\prefix\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
  2019-05-27T06:57:25.6986143Z npm verb stack     at ChildProcess.emit (events.js:189:13)
  2019-05-27T06:57:25.6986311Z npm verb stack     at maybeClose (internal/child_process.js:970:16)
  2019-05-27T06:57:25.6986453Z npm verb stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
  2019-05-27T06:57:25.6986609Z npm verb pkgid fuse@7.1.0
  2019-05-27T06:57:25.6986743Z npm verb cwd D:\a\1\s\Client
  2019-05-27T06:57:25.6986877Z npm verb Windows_NT 10.0.14393
  2019-05-27T06:57:25.6987017Z npm verb argv "C:\Program Files\nodejs\node.exe" "C:\npm\prefix\node_modules\npm\bin\npm-cli.js" "run" "build" "--" "--prod"
  2019-05-27T06:57:25.6987169Z npm verb node v10.15.3
  2019-05-27T06:57:25.6987304Z npm verb npm  v6.9.0
  2019-05-27T06:57:25.6987435Z npm ERR! code ELIFECYCLE
  2019-05-27T06:57:25.6987584Z npm ERR! errno 1
  2019-05-27T06:57:25.6987890Z npm ERR! fuse@7.1.0 build: node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --dev "--prod"
  2019-05-27T06:57:25.6988173Z npm ERR! Exit status 1

I tried looking through different threads based upon error keywords but have not found a fix yet. Please note that everything works fine in the development environment.

I am not allowed to attach file or image so I am pasting pipeline YAML here:

trigger:
- master

pool:
  vmImage: 'vs2017-win2016'

steps:
- task: Npm@1
  displayName: 'npm install'
  inputs:
    command: install
    workingDir: Client

- task: Npm@1
  displayName: 'Build Angular'
  inputs:
    command: custom
    customCommand: run build -- --prod
    workingDir: Client

- task: PublishPipelineArtifact@0
  inputs:
    artifactName: 'angular'
    targetPath: 'Client/dist'```

Please help.

答:
Your first task must be install Angular CLI.

```<code>- task: Npm@1
  displayName: angular/cli
  inputs:
    command: custom
    workingDir: Client
    verbose: false
    customCommand: 'install @angular/cli -g'
</code>```

Can you try running it to the first step?

Body:
I am working with Azure DevOps CI/CD for Angular 7 project but it is failing with following at the time of building angular code:

Error: Npm failed with return code: 1

Going through the pipeline task log I found that Node is exiting with following error:

2019-05-27T06:57:25.6984762Z npm verb lifecycle fuse@7.1.0~build: CWD: D:\a\1\s\Client
  2019-05-27T06:57:25.6984945Z npm info lifecycle fuse@7.1.0~build: Failed to exec build script
  2019-05-27T06:57:25.6985117Z npm verb stack Error: fuse@7.1.0 build: node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --dev "--prod"
  2019-05-27T06:57:25.6985258Z npm verb stack Exit status 1
  2019-05-27T06:57:25.6985401Z npm verb stack     at EventEmitter. (C:\npm\prefix\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
  2019-05-27T06:57:25.6985577Z npm verb stack     at EventEmitter.emit (events.js:189:13)
  2019-05-27T06:57:25.6985721Z npm verb stack     at ChildProcess. (C:\npm\prefix\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
  2019-05-27T06:57:25.6986143Z npm verb stack     at ChildProcess.emit (events.js:189:13)
  2019-05-27T06:57:25.6986311Z npm verb stack     at maybeClose (internal/child_process.js:970:16)
  2019-05-27T06:57:25.6986453Z npm verb stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
  2019-05-27T06:57:25.6986609Z npm verb pkgid fuse@7.1.0
  2019-05-27T06:57:25.6986743Z npm verb cwd D:\a\1\s\Client
  2019-05-27T06:57:25.6986877Z npm verb Windows_NT 10.0.14393
  2019-05-27T06:57:25.6987017Z npm verb argv "C:\Program Files\nodejs\node.exe" "C:\npm\prefix\node_modules\npm\bin\npm-cli.js" "run" "build" "--" "--prod"
  2019-05-27T06:57:25.6987169Z npm verb node v10.15.3
  2019-05-27T06:57:25.6987304Z npm verb npm  v6.9.0
  2019-05-27T06:57:25.6987435Z npm ERR! code ELIFECYCLE
  2019-05-27T06:57:25.6987584Z npm ERR! errno 1
  2019-05-27T06:57:25.6987890Z npm ERR! fuse@7.1.0 build: node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --dev "--prod"
  2019-05-27T06:57:25.6988173Z npm ERR! Exit status 1

I tried looking through different threads based upon error keywords but have not found a fix yet. Please note that everything works fine in the development environment.

I am not allowed to attach file or image so I am pasting pipeline YAML here:

trigger:
- master

pool:
  vmImage: 'vs2017-win2016'

steps:
- task: Npm@1
  displayName: 'npm install'
  inputs:
    command: install
    workingDir: Client

- task: Npm@1
  displayName: 'Build Angular'
  inputs:
    command: custom
    customCommand: run build -- --prod
    workingDir: Client

- task: PublishPipelineArtifact@0
  inputs:
    artifactName: 'angular'
    targetPath: 'Client/dist'

Please help.

Body:
Your first task must be install Angular CLI.

- task: Npm@1
  displayName: angular/cli
  inputs:
    command: custom
    workingDir: Client
    verbose: false
    customCommand: 'install @angular/cli -g'

Can you try running it to the first step?


问:
What are the often misunderstood concepts in C++?
What are the often misunderstood concepts in c++?</p>

答:
That C++ does have automatic resource management.

(Most people who claim that C++ does not have memory management try to use new and delete way too much, not realising that if they allowed C++ to manage the resource themselves, the task gets much easier).

Example: (Made with a made up API because I do not have time to check the docs now)

```<code>// C++
void DoSomething()
{
  File file("/tmp/dosomething", "rb");
  ... do stuff with file...
  // file is automatically free'ed and closed.
}

// C#
public void DoSomething()
{
  File file = new File("/tmp/dosomething", "rb");
  ... do stuff with file...

  // file is NOT automatically closed.
  // What if the caller calls DoSomething() in a tight loop?
  // C# requires you to be aware of the implementation of the File class
  // and forces you to accommodate, thus voiding implementation-hiding
  // principles.
  // Approaches may include:
  // 1) Utilizing the IDisposable pattern.
  // 2) Utilizing try-finally guards, which quickly gets messy.
  // 3) The nagging doubt that you've forgotten something /somewhere/ in your
  //    1 million loc project.
  // 4) The realization that point #3 can not be fixed by fixing the File
  //    class.
}
</code>```

OwnerDisplayName: rajKumar

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: starblue

Body:
That C++ does have automatic resource management.

(Most people who claim that C++ does not have memory management try to use new and delete way too much, not realising that if they allowed C++ to manage the resource themselves, the task gets much easier).

Example: (Made with a made up API because I do not have time to check the docs now)

// C++
void DoSomething()
{
  File file("/tmp/dosomething", "rb");
  ... do stuff with file...
  // file is automatically free'ed and closed.
}

// C#
public void DoSomething()
{
  File file = new File("/tmp/dosomething", "rb");
  ... do stuff with file...

  // file is NOT automatically closed.
  // What if the caller calls DoSomething() in a tight loop?
  // C# requires you to be aware of the implementation of the File class
  // and forces you to accommodate, thus voiding implementation-hiding
  // principles.
  // Approaches may include:
  // 1) Utilizing the IDisposable pattern.
  // 2) Utilizing try-finally guards, which quickly gets messy.
  // 3) The nagging doubt that you've forgotten something /somewhere/ in your
  //    1 million loc project.
  // 4) The realization that point #3 can not be fixed by fixing the File
  //    class.
}

OwnerDisplayName: Arafangion

LastEditorDisplayName: Arafangion


问:
How to efficiently utilize 10+ computers to import data
We have flat files (CSV) with >200,000,000 rows, which we import into a star schema with 23 dimension tables. The biggest dimension table has 3 million rows. At the moment we run the importing process on a single computer and it takes around 15 hours. As this is too long time, we want to utilize something like 40 computers to do the importing.

My question

How can we efficiently utilize the 40 computers to do the importing. The main worry is that there will be a lot of time spent replicating the dimension tables across all the nodes as they need to be identical on all nodes. This could mean that if we utilized 1000 servers to do the importing in the future, it might actually be slower than utilize a single one, due to the extensive network communication and coordination between the servers.

Does anyone have suggestion?

EDIT:

The following is a simplification of the CSV files:

```<code>"avalue";"anothervalue"
"bvalue";"evenanothervalue"
"avalue";"evenanothervalue"
"avalue";"evenanothervalue"
"bvalue";"evenanothervalue"
"avalue";"anothervalue"
</code>```

After importing, the tables look like this:

dimension_table1

```<code>id  name
1   "avalue"
2   "bvalue"
</code>```

dimension_table2

```<code>id  name
1   "anothervalue"
2   "evenanothervalue"
</code>```

Fact table

```<code>  dimension_table1_ID       dimension_table2_ID
    1                      1
    2                      2
    1                       2
    1                       2
    2                       2
    1                       1
</code>```

答: This is a very generic question and does not take the database backend into account. Firing with 40 or 1000 machines on a database backend that can not handle the load will give you nothing. Such a problem is truly to broad to answer it in a specific way..you should get in touch with people inside your organization with enough skills on the DB level first and then come back with a more specific question.</p>

Body:
We have flat files (CSV) with >200,000,000 rows, which we import into a star schema with 23 dimension tables. The biggest dimension table has 3 million rows. At the moment we run the importing process on a single computer and it takes around 15 hours. As this is too long time, we want to utilize something like 40 computers to do the importing.

My question

How can we efficiently utilize the 40 computers to do the importing. The main worry is that there will be a lot of time spent replicating the dimension tables across all the nodes as they need to be identical on all nodes. This could mean that if we utilized 1000 servers to do the importing in the future, it might actually be slower than utilize a single one, due to the extensive network communication and coordination between the servers.

Does anyone have suggestion?

EDIT:

The following is a simplification of the CSV files:

"avalue";"anothervalue"
"bvalue";"evenanothervalue"
"avalue";"evenanothervalue"
"avalue";"evenanothervalue"
"bvalue";"evenanothervalue"
"avalue";"anothervalue"

After importing, the tables look like this:

dimension_table1

id  name
1   "avalue"
2   "bvalue"

dimension_table2

id  name
1   "anothervalue"
2   "evenanothervalue"

Fact table

  dimension_table1_ID       dimension_table2_ID
    1                      1
    2                      2
    1                       2
    1                       2
    2                       2
    1                       1


问:
Type Conflict While Writing NUnit Tests
I am getting the below warning in VS Code while writing Unit Tests with NUnit:

The type 'MyClass' in 'MyProject.cs' conflicts with the imported type 'MyClass' in 'MyProject, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'Myproject\Tests\MyClass.cs'. (CS0436) [Tests]

These are the steps I took so far:

Navigated to my desired folder for all C# projects (e.g. E:\MyCSharpProjects).

Created a new C# Console Project via dotnet new console -o MyProject.

Wrote some code.

Ran the following command once: dotnet new -i NUnit3.DotNetNew.Template. I assume this installs NUnit project templates.

Created a new folder inside MyProject's root folder called Tests.

Navigated inside the new Tests folder and ran the following commands:

dotnet new nunit

dotnet add reference ../MyProject.csproj

Installed the NUnit package via NuGet on MyProject.csproj.

Wrote some test code.

NOTE 1: For both MyProject.csproj and Tests.csproj, I set TargetFramework to netcoreapp2.2 because I do not want to use 3.0 just yet.

NOTE 2: To avoid build errors, I stop Assembly Information generation by adding the following entries under PropertyGroup to both my .csproj files:

```<code><GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
<GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
</code>```

NOTE 3: Below is my MyProject.csproj file:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
    <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
    <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="NUnit" Version="*"/>
  </ItemGroup>

</Project>
</code>```

NOTE 4: Below is my Tests.csproj file:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <IsPackable>false</IsPackable>
    <GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
    <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
    <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="nunit" Version="*" />
    <PackageReference Include="NUnit3TestAdapter" Version="*" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="*" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\StudentService.csproj" />
  </ItemGroup>

</Project>
</code>```

The warning started showing up once I tried referencing a class inside my Tests project called MyClass. This class is only declared inside my Tests project and does not have any name conflicts with MyProject. I have however read that this might be caused by Tests.csproj referencing MyProject.csproj while being located inside MyProject.

My C# project is structured as follows:

```<code>E:\MyCSharpProjects
    MyProject
        MyProject.csproj
        <MyProject code files>
        Tests
            Tests.csproj
            <Tests code files>
</code>```

My questions are:

Is having a test project that references my actual project the only way to use NUnit?

Is there a way to only have 1 C# project that has NUnit tests inside it, similar to Java and JUnit?

I am keeping my test project inside my actual project so they are always together. Is this the standard practice? And if not, what is?

How do I get rid of said warning? I'm don't want to ignore it because I don't like having warnings in my code.

UPDATE: In case my questions are too broad to answer, a link on standards on how to write NUnit tests from beginning to end would also be useful.

SUMMARY: desmondgc's answer worked! Turns out all I needed to do was add a .sln file to my project and everything worked perfectly! No warnings, and no need to disable Assembly Information generation at all!

Many thanks to everyone who helped!

答:
Please see Unit testing C# with NUnit and .NET Core from the .NET Core Guide. They propose a directory structure like this:

```<code>/unit-testing-using-nunit
    unit-testing-using-nunit.sln
    /PrimeService
        Source Files
        PrimeService.csproj
    /PrimeService.Tests
        Test Source Files
        PrimeService.Tests.csproj
</code>```

This is generally what I've used on all my projects, as well.

Regarding the warning, it sounds like you've defined the same class and namespace in both projects. The namespace should usually mirror the directory structure, so if you have a project called MyProject, a test project called MyProject.Tests and a class called MyClass in each, I would expect to find the fully-qualified names MyProject.MyClass and MyProject.Tests.MyClass. Even better, call the test class MyClassTests or something like this.

Title: Type Conflict While Writing NUnit Tests

Body:
I am getting the below warning in VS Code while writing Unit Tests with NUnit:

The type 'MyClass' in 'MyProject.cs' conflicts with the imported type 'MyClass' in 'MyProject, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'Myproject\Tests\MyClass.cs'. (CS0436) [Tests]

These are the steps I took so far:

Navigated to my desired folder for all C# projects (e.g. E:\MyCSharpProjects).

Created a new C# Console Project via dotnet new console -o MyProject.

Wrote some code.

Ran the following command once: dotnet new -i NUnit3.DotNetNew.Template. I assume this installs NUnit project templates.

Created a new folder inside MyProject's root folder called Tests.

Navigated inside the new Tests folder and ran the following commands:

dotnet new nunit

dotnet add reference ../MyProject.csproj

Installed the NUnit package via NuGet on MyProject.csproj.

Wrote some test code.

NOTE 1: For both MyProject.csproj and Tests.csproj, I set TargetFramework to netcoreapp2.2 because I do not want to use 3.0 just yet.

NOTE 2: To avoid build errors, I stop Assembly Information generation by adding the following entries under PropertyGroup to both my .csproj files:

<GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
<GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>

NOTE 3: Below is my MyProject.csproj file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
    <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
    <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="NUnit" Version="*"/>
  </ItemGroup>

</Project>

NOTE 4: Below is my Tests.csproj file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <IsPackable>false</IsPackable>
    <GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
    <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
    <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="nunit" Version="*" />
    <PackageReference Include="NUnit3TestAdapter" Version="*" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="*" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\StudentService.csproj" />
  </ItemGroup>

</Project>

The warning started showing up once I tried referencing a class inside my Tests project called MyClass. This class is only declared inside my Tests project and does not have any name conflicts with MyProject. I have however read that this might be caused by Tests.csproj referencing MyProject.csproj while being located inside MyProject.

My C# project is structured as follows:

E:\MyCSharpProjects
    MyProject
        MyProject.csproj
        <MyProject code files>
        Tests
            Tests.csproj
            <Tests code files>

My questions are:

Is having a test project that references my actual project the only way to use NUnit?

Is there a way to only have 1 C# project that has NUnit tests inside it, similar to Java and JUnit?

I am keeping my test project inside my actual project so they are always together. Is this the standard practice? And if not, what is?

How do I get rid of said warning? I'm don't want to ignore it because I don't like having warnings in my code.

UPDATE: In case my questions are too broad to answer, a link on standards on how to write NUnit tests from beginning to end would also be useful.

SUMMARY: desmondgc's answer worked! Turns out all I needed to do was add a .sln file to my project and everything worked perfectly! No warnings, and no need to disable Assembly Information generation at all!

Many thanks to everyone who helped!

Body:
Please see Unit testing C# with NUnit and .NET Core from the .NET Core Guide. They propose a directory structure like this:

/unit-testing-using-nunit
    unit-testing-using-nunit.sln
    /PrimeService
        Source Files
        PrimeService.csproj
    /PrimeService.Tests
        Test Source Files
        PrimeService.Tests.csproj

This is generally what I've used on all my projects, as well.

Regarding the warning, it sounds like you've defined the same class and namespace in both projects. The namespace should usually mirror the directory structure, so if you have a project called MyProject, a test project called MyProject.Tests and a class called MyClass in each, I would expect to find the fully-qualified names MyProject.MyClass and MyProject.Tests.MyClass. Even better, call the test class MyClassTests or something like this.


问:
image icon not displaying for firebase push notification in android Pie
I have implemented the push notification and works fine in all os except Pie. In pie notification image is not displaying.

I have updated the default icon in manifiest.
I have updated the icon in code OnMessageRecived.

```<code> <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@mipmap/ic_launcher_new"/>
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/white" />
    <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/channel_id"/>

   NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.mipmap.ic_launcher_new)
                .setLargeIcon(bitmap)
                .setContentTitle(title)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(secondText).setBigContentTitle(title))
                .setContentText(secondText)
                .setChannelId(channelId)
                .setPriority(Notification.PRIORITY_HIGH);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addNextIntent(intent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                0,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
        mBuilder.setContentIntent(resultPendingIntent);

        notificationManager.notify(notificationId, mBuilder.build());
</code>```

答:
Implement your NotificationCompat.Builder like this:

```<code>Notification notification = new NotificationCompat.Builder(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    notification.setSmallIcon(R.drawable.icon_transperent);
    notification.setColor(getResources().getColor(R.color.notification_color));
} else {
    notification.setSmallIcon(R.drawable.icon);
}
</code>```

Body:
I have implemented the push notification and works fine in all os except Pie. In pie notification image is not displaying.

I have updated the default icon in manifiest.
I have updated the icon in code OnMessageRecived.

 <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@mipmap/ic_launcher_new"/>
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/white" />
    <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/channel_id"/>

   NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.mipmap.ic_launcher_new)
                .setLargeIcon(bitmap)
                .setContentTitle(title)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(secondText).setBigContentTitle(title))
                .setContentText(secondText)
                .setChannelId(channelId)
                .setPriority(Notification.PRIORITY_HIGH);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addNextIntent(intent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                0,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
        mBuilder.setContentIntent(resultPendingIntent);

        notificationManager.notify(notificationId, mBuilder.build());

Body:
Implement your NotificationCompat.Builder like this:

Notification notification = new NotificationCompat.Builder(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    notification.setSmallIcon(R.drawable.icon_transperent);
    notification.setColor(getResources().getColor(R.color.notification_color));
} else {
    notification.setSmallIcon(R.drawable.icon);
}